為鞏固深度之眼比賽實戰(zhàn)訓(xùn)練營課程的學(xué)習(xí),接下來的時間將會在博客中記錄一些比賽相關(guān)的內(nèi)容以及心得體會剂府。本篇文章是Kaggle入門比賽房價預(yù)測競賽的第一部分:下載分析數(shù)據(jù)集與數(shù)據(jù)清洗渊迁。
1.下載數(shù)據(jù)集
訪問:https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data?下載數(shù)據(jù)集
2. 數(shù)據(jù)清洗(Data cleaning)
定義:對數(shù)據(jù)進(jìn)行重新審查和校驗的過程稱為數(shù)據(jù)清洗過程慰照,目的在于刪除重復(fù)信息、糾正存在的錯誤并提供數(shù)據(jù)一致性琉朽。
難點:一般針對具體應(yīng)用毒租,因而難以歸納統(tǒng)一的方法和步驟,但是根據(jù)數(shù)據(jù)不同可以給出相應(yīng)的數(shù)據(jù)清理方法箱叁。
方法:
1)解決缺失值:平均值墅垮、最大值、最小值或更為復(fù)雜的概率估計代替缺失的值
2)去重:相等的記錄合并為一條記錄(合并/清除)
3)解決錯誤值:用統(tǒng)計分析的方法識別可能的錯誤值或異常值耕漱,如偏差分析算色、識別不遵守分布或回歸方程的值、規(guī)則庫(常識性規(guī)則螟够、業(yè)務(wù)特性規(guī)則)檢查數(shù)據(jù)庫灾梦、不同屬性間的約束、外部數(shù)據(jù)來檢測和清理數(shù)據(jù)
4)解決數(shù)據(jù)不一致性:比如類別型和次序型
場景:刪除多列妓笙、更改數(shù)據(jù)類型斥废、將分類變量轉(zhuǎn)換為數(shù)字變量、檢查缺失數(shù)據(jù)(NAN)给郊、刪除列中的字符串(一些無關(guān)的屬性)、刪除列中的空格捧灰、用字符串連接兩列(帶條件)淆九、轉(zhuǎn)換時間戳(字符串->日期時間格式)
3. 數(shù)據(jù)處理
定義:數(shù)據(jù)處理是對數(shù)據(jù)(數(shù)值型與非數(shù)值型)進(jìn)行分析和加工的技術(shù)過程,讓數(shù)據(jù)更好地擬合模型毛俏,更便于計算炭庙,減少計算量
方法:對數(shù)變換、標(biāo)準(zhǔn)縮放煌寇、轉(zhuǎn)換數(shù)據(jù)類型焕蹄、獨熱編碼、標(biāo)簽編碼
4. 關(guān)于Pandas
pandas是一個開源的阀溶,BSD許可的庫腻脏,為Python?編程語言提供高性能鸦泳,易于使用的數(shù)據(jù)結(jié)構(gòu)和數(shù)據(jù)分析工具。pandas的官方文檔:https://pandas.pydata.org/pandas-docs/stable/index.html 具體的內(nèi)容可在文檔查詢永品。
4.1 pandas的兩種數(shù)據(jù)結(jié)構(gòu)
1)Series
Series是一維標(biāo)記的數(shù)組做鹰,能夠保存任何數(shù)據(jù)類型(整數(shù),字符串鼎姐,浮點數(shù)钾麸,Python對象等)
可以將其簡單理解為一個向量,但不同的是炕桨,Serise會自動為一維數(shù)據(jù)創(chuàng)建行索引
Series本身的屬性有兩種饭尝,一種是index,一種是values
2)DataFrame
DataFrame是一個二維標(biāo)記數(shù)據(jù)結(jié)構(gòu)献宫,具有可能不同類型的列钥平。與Series一樣,DataFrame接受許多不同類型的輸入
Dataframe既有行索引index遵蚜,也有列索引columns帖池。其實可以簡單把dataframe理解為一張數(shù)據(jù)表。
4.2 Pandas的部分可視化函數(shù)
.plot():畫圖
.plot.bar():條形圖
.hist():直方圖
.box():箱型圖
.plot.area():區(qū)域圖
.plot.scatter():散點圖
.plot.hexbin():六角箱型圖
.plot.pie():餅圖
以上是理論相關(guān)部分吭净,接下來對這兩部分進(jìn)行代碼編寫睡汹。
本代碼中主要用到pandas
5. 代碼編寫
好啦,現(xiàn)在開始貼代碼啦寂殉!這只是最開始的baseline代碼編寫囚巴,第一遍提交成績在4000名以后,可以說非常差了友扰。不過后續(xù)會隨著學(xué)習(xí)改進(jìn)這些代碼哦~
思路:數(shù)據(jù)探索彤叉,對數(shù)據(jù)做一些修改-->數(shù)據(jù)清洗(填充空值)-->數(shù)據(jù)預(yù)處理(歸一化、標(biāo)準(zhǔn)化等)-->模型構(gòu)建-->訓(xùn)練預(yù)測-->保存提交
1 導(dǎo)包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import pandas_profiling as ppf? #探索性數(shù)據(jù)分析EDA
import warnings
warnings.filterwarnings('ignore')? #忽略警告
%matplotlib inline
plt.style.use('ggplot')
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import RobustScaler,StandardScaler
2. 數(shù)據(jù)導(dǎo)入
train = pd.read_csv("train.csv")? ? ? #數(shù)據(jù)讀取
test = pd.read_csv("test.csv")
3. 數(shù)據(jù)探索
train.head()? #默認(rèn)顯示前五行NAN為空值
train.tail()? ? #查看數(shù)據(jù)后五行
test.head()
ppf.ProfileReport(train)? ? #生成報告型文件
plt.figure(figsize = (15,8))
sns.boxplot(train.YearBuilt,train.SalePrice)? #訓(xùn)練數(shù)據(jù)中建造年份與銷售價格的相關(guān)性
#箱型圖是看異常值的村怪,離群點
plt.figure(figsize = (12,6))
plt.scatter(x = train.GrLivArea , y = train.SalePrice)? #用來觀察線性關(guān)系
plt.xlabel("GrLivArea" , fontsize = 13)
plt.ylabel("SalePrice" , fontsize = 13)
plt.ylim(0,800000)? ? #限制y軸的最大值
train.drop(train[(train["GrLivArea"] > 4000) & (train["SalePrice"] < 300000)].index)? #刪除右下角點的索引
#直接刪除了這兩條數(shù)據(jù)的兩行
#為防止后面對test做重復(fù)的工作秽浇,這里先將兩個數(shù)據(jù)集合為一體
full = pd.concat([train,test],ignore_index = True)
#由于顯示的id與數(shù)據(jù)集中的id重復(fù),所以將其刪掉
full.drop("Id",axis = 1 , inplace = True)
4. 數(shù)據(jù)清洗--空值填充甚负、刪除等
#查看缺失值并將個數(shù)從高到低排序
miss = full.isnull().sum()? #如果是空則輸出1
miss[miss> 0].sort_values(ascending = False)? #false是由高到低進(jìn)行排序
#對照著數(shù)據(jù)集的信息柬焕,查看缺失數(shù)據(jù)類型,對字符類型數(shù)據(jù)作為一種類型填充梭域,數(shù)值型數(shù)據(jù)作為一種類型填充
full.info()
#將字符型數(shù)據(jù)的空值填充為None
cols1 = ["PoolQC" , "MiscFeature", "Alley", "Fence", "FireplaceQu", "GarageQual", "GarageCond", "GarageFinish", "GarageYrBlt", "GarageType", "BsmtExposure", "BsmtCond", "BsmtQual", "BsmtFinType2", "BsmtFinType1", "MasVnrType"]
for col in cols1:
? ? full[col].fillna("None",inplace=True)
#將數(shù)值型數(shù)據(jù)的空值填充為0
cols2=["MasVnrArea", "BsmtUnfSF", "TotalBsmtSF", "GarageCars", "BsmtFinSF2", "BsmtFinSF1", "GarageArea"]
for col in cols2:
? ? full[col].fillna(0, inplace=True)
#對lotfrontage的空值進(jìn)行填充(用這一列的均值)
full["LotFrontage"].fillna(np.mean(full["LotFrontage"]),inplace=True)
#對缺失少的列進(jìn)行眾數(shù)填充
cols3 = ["MSZoning", "BsmtFullBath", "BsmtHalfBath", "Utilities", "Functional", "Electrical", "KitchenQual", "SaleType","Exterior1st", "Exterior2nd"]
for col in cols3:
? ? full[col].fillna(full[col].mode()[0], inplace=True)
#查看哪些是還沒填充好的斑举,發(fā)現(xiàn)只有test的沒有標(biāo)簽列
full.isnull().sum()[full.isnull().sum()>0]
5. 數(shù)據(jù)預(yù)處理
5.1 字符變成數(shù)值
#astype來進(jìn)行數(shù)據(jù)轉(zhuǎn)換成字符串類型
for col in cols3:
? ? full[col]=full[col].astype(str)
lab = LabelEncoder()
#將所有的字符類型轉(zhuǎn)化成數(shù)值類型
full["Alley"] = lab.fit_transform(full.Alley)
full["PoolQC"] = lab.fit_transform(full.PoolQC)
full["MiscFeature"] = lab.fit_transform(full.MiscFeature)
full["Fence"] = lab.fit_transform(full.Fence)
full["FireplaceQu"] = lab.fit_transform(full.FireplaceQu)
full["GarageQual"] = lab.fit_transform(full.GarageQual)
full["GarageCond"] = lab.fit_transform(full.GarageCond)
full["GarageFinish"] = lab.fit_transform(full.GarageFinish)
full["GarageYrBlt"] = full["GarageYrBlt"].astype(str)
full["GarageYrBlt"] = lab.fit_transform(full.GarageYrBlt)
full["GarageType"] = lab.fit_transform(full.GarageType)
full["BsmtExposure"] = lab.fit_transform(full.BsmtExposure)
full["BsmtCond"] = lab.fit_transform(full.BsmtCond)
full["BsmtQual"] = lab.fit_transform(full.BsmtQual)
full["BsmtFinType2"] = lab.fit_transform(full.BsmtFinType2)
full["BsmtFinType1"] = lab.fit_transform(full.BsmtFinType1)
full["MasVnrType"] = lab.fit_transform(full.MasVnrType)
full["BsmtFinType1"] = lab.fit_transform(full.BsmtFinType1)
full["MSZoning"] = lab.fit_transform(full.MSZoning)
full["BsmtFullBath"] = lab.fit_transform(full.BsmtFullBath)
full["BsmtHalfBath"] = lab.fit_transform(full.BsmtHalfBath)
full["Utilities"] = lab.fit_transform(full.Utilities)
full["Functional"] = lab.fit_transform(full.Functional)
full["Electrical"] = lab.fit_transform(full.Electrical)
full["KitchenQual"] = lab.fit_transform(full.KitchenQual)
full["SaleType"] = lab.fit_transform(full.SaleType)
full["Exterior1st"] = lab.fit_transform(full.Exterior1st)
full["Exterior2nd"] = lab.fit_transform(full.Exterior2nd)
#刪除該列
full.drop("SalePrice",axis=1,inplace=True)
#獨熱編碼
full2 = pd.get_dummies(full)
full2.shape
full2.head()
5.2 歸一化、標(biāo)準(zhǔn)化等
n_train = train.shape[0]? #行數(shù)
#劃分?jǐn)?shù)據(jù)集
X = full2[:n_train]? #相當(dāng)于取出X
y = train.SalePrice? #取出訓(xùn)練集的標(biāo)簽
std = StandardScaler()
X_scaled = std.fit_transform(X)? #歸一化數(shù)據(jù)集
y = np.log(y)? #訓(xùn)練集的一個數(shù)據(jù)分布
test_x = full2[n_train:]? #從n_train+1行取到最后
6. 模型構(gòu)建
#導(dǎo)入模型
from sklearn.linear_model import LinearRegression?
#訓(xùn)練模型
model = LinearRegression()
model1 = model.fit(X_scaled,y)
7. 模型測試
predict = model1.predict(test_x)
result = pd.DataFrame({'id':test.Id,'SalePrice':predict})
result.to_csv("submission.csv",index = False)
最終將submission.csv文件提交到kaggle網(wǎng)站就可以啦病涨!