Datawhale練習(xí)之二手車價格預(yù)測
數(shù)據(jù)探索性分析(EDA)
1. 總覽數(shù)據(jù)概況
數(shù)據(jù)庫載入
#coding:utf-8 #導(dǎo)入warnings包,利用過濾器來實現(xiàn)忽略警告語句。 import warnings warnings.filterwarnings('ignore') import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import missingno as msno
數(shù)據(jù)載入
## 1) 載入訓(xùn)練集和測試集; path = './' Train_data = pd.read_csv(path+'car_train_0110.csv', sep=' ') Test_data = pd.read_csv(path+'car_testA_0110.csv', sep=' ')
確定path,如果是在notebook環(huán)境,我通常使用 !dir查看當(dāng)前目錄
特征說明
新技能:使用.append()同時觀察前5行與后5行
## 2) 簡略觀察數(shù)據(jù)(head()+shape) Train_data.head().append(Train_data.tail())
觀察數(shù)據(jù)維度
Train_data.shape,Test_data.shape
總覽概況: .describe()查看統(tǒng)計量,.info()查看數(shù)據(jù)類型
1.1 判斷數(shù)據(jù)缺失和異常
1.1.1 查看nan
Train_data.shape,Test_data.shape
也可直接查看nan,有以下兩種方式 ↓ :
Train_data.isnull().sum()
可視化na更直觀
# find na tmp = df_train.isnull().any() tmp[tmp.values==True]
新技能: msno庫(缺失值可視化)的使用
Train_data.isnull().sum().plot( kind= 'bar')
可視化看下缺省值
msno.matrix(Train_data.sample(250))
其中,Train_data.sample(250)表示隨機(jī)抽樣250行,白色條紋表示缺失
直接顯示未缺失的樣本數(shù)量/每特征
msno.bar(Train_data.sample(250),labels= True)
使用msno中的 .heatmap()查看缺失值之間的相關(guān)性
msno.heatmap(Train_data.sample(250))
1.1.2 *異常值檢測(重要!易忽略)
通過Train_data.info()了解數(shù)據(jù)類型
Train_data.info()
1.2 了解預(yù)測值的分布
特征分為類別特征和數(shù)字特征
查看分布的意義在于:
a. 及時將非正態(tài)分布數(shù)據(jù)變化為正態(tài)分布數(shù)據(jù)
b. 異常檢測
1.2.1 數(shù)字特征分析
Train_data['price']
發(fā)現(xiàn)都是int
統(tǒng)計分布 ↓
Train_data['price'].value_counts()
## 1) 總體分布概況(無界約翰遜分布等) import scipy.stats as st y = Train_data['price'] plt.figure(1); plt.title('Johnson SU') sns.distplot(y, kde=False, fit=st.johnsonsu) plt.figure(2); plt.title('Normal') sns.distplot(y, kde=False, fit=st.norm) plt.figure(3); plt.title('Log Normal') sns.distplot(y, kde=False, fit=st.lognorm)
結(jié)論:price不服從正態(tài)分布,因此在進(jìn)行回歸之前,它必須進(jìn)行轉(zhuǎn)換。無界約翰遜分布擬合效果較好。
1.2.1.1 相關(guān)性分析
1.2.1.2 *偏度和峰值
偏度(skewness),統(tǒng)計數(shù)據(jù)分布偏斜方向和程度,是統(tǒng)計數(shù)據(jù)分布非對稱程度的數(shù)字特征。定義上偏度是樣本的三階標(biāo)準(zhǔn)化矩。
峰度(peakedness;kurtosis)又稱峰態(tài)系數(shù)。表征概率密度分布曲線在平均值處峰值高低的特征數(shù)。直觀看來,峰度反映了峰部的尖度。
## 2) 查看skewness and kurtosis sns.distplot(Train_data['price']); print("Skewness: %f" % Train_data['price'].skew()) print("Kurtosis: %f" % Train_data['price'].kurt())
批量計算skew
Train_data.skew()
查看skew的分布情況
批量計算kurt
Train_data.kurt()
查看kurt的分布情況
查看目標(biāo)變量的分布
## 3) 查看預(yù)測值的具體頻數(shù) plt.hist(Train_data['price'], orientation = 'vertical',histtype = 'bar', color ='red') plt.show()
結(jié)論:大于20000得值極少,其實這里也可以把這些當(dāng)作特殊得值(異常值)直接用填充或者刪掉
由于np.log(0)==-inf,無法繪圖,因此改用log(1+x)繪制分布bar,和教程里有出入,教程里用log繪圖如下:(我畫不出來,因為-inf會報錯)
# log變換之后的分布較均勻,可以進(jìn)行l(wèi)og變換進(jìn)行預(yù)測,這也是預(yù)測問題常用的trick plt.hist(np.log(1+Train_data['price']), orientation = 'vertical',histtype = 'bar', color ='red') plt.show()
分離label即預(yù)測值
Y_train = Train_data['price']
#這個區(qū)別方式適用于沒有直接label coding的數(shù)據(jù)
#這里不適用,需要人為根據(jù)實際含義來區(qū)分
#數(shù)字特征
numeric_features = Train_data.select_dtypes(include=[np.number])
numeric_features.columns
#類型特征
categorical_features = Train_data.select_dtypes(include=[np.object])
categorical_features.columns
numeric_features = ['power', 'kilometer', 'v_0', 'v_1', 'v_2', 'v_3', 'v_4', 'v_5', 'v_6', 'v_7', 'v_8', 'v_9', 'v_10', 'v_11', 'v_12', 'v_13','v_14' ] categorical_features = ['name', 'model', 'brand', 'bodyType', 'fuelType', 'gearbox', 'notRepairedDamage', 'regionCode',]
# 特征nunique分布 for cat_fea in categorical_features: print(cat_fea + "的特征分布如下:") print("{}特征有個{}不同的值".format(cat_fea, Train_data[cat_fea].nunique())) print(Train_data[cat_fea].value_counts())
每個特征情況都會逐個如下所示:
test data顯示同理
numeric_features.append('price') numeric_features
price_numeric = Train_data[numeric_features] correlation = price_numeric.corr() correlation
只截了一部分
查看相關(guān)性(強->弱)
print(correlation['price'].sort_values(ascending = False),'\n')
可視化correction
f , ax = plt.subplots(figsize = (7, 7)) plt.title('Correlation of Numeric Features with Price',y=1,size=16) sns.heatmap(correlation,square = True, vmax=0.8)
price完成歷史使命,刪掉
del price_numeric['price']
## 2) 查看幾個特征得 偏度和峰值 for col in numeric_features: print('{:15}'.format(col), 'Skewness: {:05.2f}'.format(Train_data[col].skew()) , ' ' , 'Kurtosis: {:06.2f}'.format(Train_data[col].kurt()) )
1.2.1.3 *每個數(shù)字特征的分布可視化(易忽略)
## 3) 每個數(shù)字特征得分布可視化 f = pd.melt(Train_data, value_vars=numeric_features) g = sns.FacetGrid(f, col="variable", col_wrap=2, sharex=False, sharey=False) g = g.map(sns.distplot, "value")
只截了部分:
結(jié)論:匿名特征(v_*)相對分布均勻
1.2.1.4 *數(shù)字特征相互之間的關(guān)系可視化(易忽略)
## 4) 數(shù)字特征相互之間的關(guān)系可視化 sns.set() columns = ['price', 'v_12', 'v_8' , 'v_0', 'power', 'v_5', 'v_2', 'v_6', 'v_1', 'v_14'] sns.pairplot(Train_data[columns],size = 2 ,kind ='scatter',diag_kind='kde') plt.show()
1.2.1.5 *多變量互相回歸關(guān)系可視化(易忽略)
## 5) 多變量互相回歸關(guān)系可視化 fig, ((ax1, ax2), (ax3, ax4), (ax5, ax6), (ax7, ax8), (ax9, ax10)) = plt.subplots(nrows=5, ncols=2, figsize=(24, 20)) # ['v_12', 'v_8' , 'v_0', 'power', 'v_5', 'v_2', 'v_6', 'v_1', 'v_14'] v_12_scatter_plot = pd.concat([Y_train,Train_data['v_12']],axis = 1) sns.regplot(x='v_12',y = 'price', data = v_12_scatter_plot,scatter= True, fit_reg=True, ax=ax1) v_8_scatter_plot = pd.concat([Y_train,Train_data['v_8']],axis = 1) sns.regplot(x='v_8',y = 'price',data = v_8_scatter_plot,scatter= True, fit_reg=True, ax=ax2) v_0_scatter_plot = pd.concat([Y_train,Train_data['v_0']],axis = 1) sns.regplot(x='v_0',y = 'price',data = v_0_scatter_plot,scatter= True, fit_reg=True, ax=ax3) power_scatter_plot = pd.concat([Y_train,Train_data['power']],axis = 1) sns.regplot(x='power',y = 'price',data = power_scatter_plot,scatter= True, fit_reg=True, ax=ax4) v_5_scatter_plot = pd.concat([Y_train,Train_data['v_5']],axis = 1) sns.regplot(x='v_5',y = 'price',data = v_5_scatter_plot,scatter= True, fit_reg=True, ax=ax5) v_2_scatter_plot = pd.concat([Y_train,Train_data['v_2']],axis = 1) sns.regplot(x='v_2',y = 'price',data = v_2_scatter_plot,scatter= True, fit_reg=True, ax=ax6) v_6_scatter_plot = pd.concat([Y_train,Train_data['v_6']],axis = 1) sns.regplot(x='v_6',y = 'price',data = v_6_scatter_plot,scatter= True, fit_reg=True, ax=ax7) v_1_scatter_plot = pd.concat([Y_train,Train_data['v_1']],axis = 1) sns.regplot(x='v_1',y = 'price',data = v_1_scatter_plot,scatter= True, fit_reg=True, ax=ax8) v_14_scatter_plot = pd.concat([Y_train,Train_data['v_14']],axis = 1) sns.regplot(x='v_14',y = 'price',data = v_14_scatter_plot,scatter= True, fit_reg=True, ax=ax9) v_13_scatter_plot = pd.concat([Y_train,Train_data['v_13']],axis = 1) sns.regplot(x='v_13',y = 'price',data = v_13_scatter_plot,scatter= True, fit_reg=True, ax=ax10)
1.2.2 類別特征分析(會畫,不會利用結(jié)果)
對類別特征查看unique分布
.value_counts()
## 1) unique分布 for fea in categorical_features: print(Train_data[fea].nunique()) categorical_features
1.2.2.1 箱形圖可視化
## 2) 類別特征箱形圖可視化 # 因為 name和 regionCode的類別太稀疏了,這里我們把不稀疏的幾類畫一下 categorical_features = ['model', 'brand', 'bodyType', 'fuelType', 'gearbox', 'notRepairedDamage'] for c in categorical_features: Train_data[c] = Train_data[c].astype('category') if Train_data[c].isnull().any(): Train_data[c] = Train_data[c].cat.add_categories(['MISSING']) Train_data[c] = Train_data[c].fillna('MISSING') def boxplot(x, y, **kwargs): sns.boxplot(x=x, y=y) x=plt.xticks(rotation=90) f = pd.melt(Train_data, id_vars=['price'], value_vars=categorical_features) g = sns.FacetGrid(f, col="variable", col_wrap=2, sharex=False, sharey=False, size=5) g = g.map(boxplot, "value", "price")
Train_data.columns
1.2.2.2 小提琴圖可視化
## 3) 類別特征的小提琴圖可視化 catg_list = categorical_features target = 'price' for catg in catg_list : sns.violinplot(x=catg, y=target, data=Train_data) plt.show()
categorical_features = ['model', 'brand', 'bodyType', 'fuelType', 'gearbox', 'notRepairedDamage']
1.2.2.3 柱形圖可視化類別
## 4) 類別特征的柱形圖可視化 def bar_plot(x, y, **kwargs): sns.barplot(x=x, y=y) x=plt.xticks(rotation=90) f = pd.melt(Train_data, id_vars=['price'], value_vars=categorical_features) g = sns.FacetGrid(f, col="variable", col_wrap=2, sharex=False, sharey=False, size=5) g = g.map(bar_plot, "value", "price")
1.2.2.4 特征的每個類別頻數(shù)可視化(count_plot)
## 5) 類別特征的每個類別頻數(shù)可視化(count_plot) def count_plot(x, **kwargs): sns.countplot(x=x) x=plt.xticks(rotation=90) f = pd.melt(Train_data, value_vars=categorical_features) g = sns.FacetGrid(f, col="variable", col_wrap=2, sharex=False, sharey=False, size=5) g = g.map(count_plot, "value")
2. *用pandas_profiling生成數(shù)據(jù)報告(新技能)
import pandas_profiling
pfr = pandas_profiling.ProfileReport(Train_data) pfr.to_file("./example.html")
3. 小結(jié)
本次筆記雖然針對樣本量較少的情況,但仍有一些可貴的思路:
a. 通過檢查nan缺失情況,確定需要進(jìn)一步處理的特征:
填充(填充方式是什么,均值填充,0填充,眾數(shù)填充等);
舍去;
先做樣本分類用不同的特征模型去預(yù)測。
b. 通過分布,進(jìn)行異常檢測
分析特征異常的label是否異常(或者偏離均值較遠(yuǎn)或者事特殊符號);
異常值是否應(yīng)該剔除,還是用正常值填充,等。
c. 通過對laebl作圖,分析標(biāo)簽的分布情況
d. 通過對特征作圖,特征和label聯(lián)合做圖(統(tǒng)計圖,離散圖),直觀了解特征的分布情況,通過這一步也可以發(fā)現(xiàn)數(shù)據(jù)之中的一些異常值等,通過箱型圖分析一些特征值的偏離情況,對于特征和特征聯(lián)合作圖,對于特征和label聯(lián)合作圖,分析其中的一些關(guān)聯(lián)性
到此這篇關(guān)于Datawhale練習(xí)的文章就介紹到這了,更多相關(guān)python預(yù)測內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持腳本之家!
相關(guān)文章
Python實現(xiàn)windows下模擬按鍵和鼠標(biāo)點擊的方法
這篇文章主要介紹了Python實現(xiàn)windows下模擬按鍵和鼠標(biāo)點擊的方法,涉及Python模擬實現(xiàn)鼠標(biāo)及鍵盤事件的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-03-03win系統(tǒng)下為Python3.5安裝flask-mongoengine 庫
MongoEngine 是一個用來操作 MongoDB 的 ORM 框架,如果你不知道什么是 ORM,可以參考 Flask-SQLAlchemy 一節(jié)。在 Flask 中,我們可以直接使用 MongoEngine,也可使用 Flask-MongoEngine ,它使得在 Flask 中使用 MongoEngine 變得更加簡單。2016-12-12如何在Python?中使用?Luhn?算法驗證數(shù)字
Luhn 算法驗證器有助于檢查合法數(shù)字并將其與不正確或拼寫錯誤的輸入分開,這篇文章主要介紹了在Python中使用Luhn算法驗證數(shù)字,需要的朋友可以參考下2023-06-06linux系統(tǒng)使用python獲取cpu信息腳本分享
這篇文章主要介紹了linux系統(tǒng)使用python獲取cpu信息腳本,大家參考使用吧2014-01-01pandas round方法保留兩位小數(shù)的設(shè)置實現(xiàn)
本文主要介紹了pandas round方法保留兩位小數(shù)的設(shè)置實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08關(guān)于Keras模型可視化教程及關(guān)鍵問題的解決
今天小編就為大家分享一篇關(guān)于Keras模型可視化教程及關(guān)鍵問題的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01Python實現(xiàn)給文件添加內(nèi)容及得到文件信息的方法
這篇文章主要介紹了Python實現(xiàn)給文件添加內(nèi)容及得到文件信息的方法,可實現(xiàn)從文件開頭添加內(nèi)容的功能,需要的朋友可以參考下2015-05-05