利用機(jī)器學(xué)習(xí)預(yù)測(cè)房?jī)r(jià)
項(xiàng)目介紹
背景:
DC競(jìng)賽比賽項(xiàng)目,運(yùn)用回歸模型進(jìn)行房?jī)r(jià)預(yù)測(cè)。
數(shù)據(jù)介紹:
數(shù)據(jù)主要包括2014年5月至2015年5月美國(guó)King County的房屋銷(xiāo)售價(jià)格以及房屋的基本信息。
其中訓(xùn)練數(shù)據(jù)主要包括10000條記錄,14個(gè)字段,分別代表:
- 銷(xiāo)售日期(date):2014年5月到2015年5月房屋出售時(shí)的日期;
- 銷(xiāo)售價(jià)格(price):房屋交易價(jià)格,單位為美元,是目標(biāo)預(yù)測(cè)值;
- 臥室數(shù)(bedroom_num):房屋中的臥室數(shù)目;
- 浴室數(shù)(bathroom_num):房屋中的浴室數(shù)目;
- 房屋面積(house_area):房屋里的生活面積;
- 停車(chē)面積(park_space):停車(chē)坪的面積;
- 樓層數(shù)(floor_num):房屋的樓層數(shù);
- 房屋評(píng)分(house_score):King County房屋評(píng)分系統(tǒng)對(duì)房屋的總體評(píng)分;
- 建筑面積(covered_area):除了地下室之外的房屋建筑面積;
- 地下室面積(basement_area):地下室的面積;
- 建筑年份(yearbuilt):房屋建成的年份;
- 修復(fù)年份(yearremodadd):房屋上次修復(fù)的年份;
- 緯度(lat):房屋所在緯度;
- 經(jīng)度(long):房屋所在經(jīng)度。
目標(biāo):
算法通過(guò)計(jì)算平均預(yù)測(cè)誤差來(lái)衡量回歸模型的優(yōu)劣。平均預(yù)測(cè)誤差越小,說(shuō)明回歸模型越好。
代碼詳解
數(shù)據(jù)導(dǎo)入
先導(dǎo)入分析需要的python包:
#導(dǎo)入類(lèi)庫(kù)和加載數(shù)據(jù)集 import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline
導(dǎo)入下載好的kc_train的csv文件:
#讀取數(shù)據(jù) train_names = ["date", "price", "bedroom_num", "bathroom_num", "house_area", "park_space", "floor_num", "house_score", "covered_area", "basement_area", "yearbuilt", "yearremodadd", "lat", "long"] data = pd.read_csv("kc_train.csv",names=train_names) data.head()
數(shù)據(jù)預(yù)處理
查看數(shù)據(jù)集概況
# 觀察數(shù)據(jù)集概況 data.info()
從圖中可以看出沒(méi)有任何缺失值,因此不需要對(duì)缺失值進(jìn)行處理。
拆分?jǐn)?shù)據(jù):
把原始數(shù)據(jù)中的年月日拆開(kāi),然后根據(jù)房屋的建造年份和修復(fù)年份計(jì)算一下售出時(shí)已經(jīng)過(guò)了多少年,這樣就有17個(gè)特征。
sell_year,sell_month,sell_day=[],[],[] house_old,fix_old=[],[] for [date,yearbuilt,yearremodadd] in data[['date','yearbuilt','yearremodadd']].values: year,month,day=date//10000,date%10000//100,date%100 sell_year.append(year) sell_month.append(month) sell_day.append(day) house_old.append(year-yearbuilt) if yearremodadd==0: fix_old.append(0) else: fix_old.append(year-yearremodadd) del data['date'] data['sell_year']=pd.DataFrame({'sell_year':sell_year}) data['sell_month']=pd.DataFrame({'sell_month':sell_month}) data['sell_day']=pd.DataFrame({'sell_day':sell_day}) data['house_old']=pd.DataFrame({'house_old':house_old}) data['fix_old']=pd.DataFrame({'fix_old':fix_old}) data.head()
觀察因變量(price)數(shù)據(jù)情況
#觀察數(shù)據(jù) print(data['price'].describe())
#觀察price的數(shù)據(jù)分布 plt.figure(figsize = (10,5)) # plt.xlabel('price') sns.distplot(data['price'])
從數(shù)據(jù)和圖片上可以看出,price呈現(xiàn)典型的右偏分布,但總體上看還是符合一般規(guī)律。
相關(guān)性分析
自變量與因變量的相關(guān)性分析,繪制相關(guān)性矩陣熱力圖,比較各個(gè)變量之間的相關(guān)性:
#自變量與因變量的相關(guān)性分析 plt.figure(figsize = (20,10)) internal_chars = ['price','bedroom_num','bathroom_num','house_area','park_space','floor_num','house_score','covered_area' ,'basement_area','yearbuilt','yearremodadd','lat','long','sell_year','sell_month','sell_day', 'house_old','fix_old'] corrmat = data[internal_chars].corr() # 計(jì)算相關(guān)系數(shù) sns.heatmap(corrmat, square=False, linewidths=.5, annot=True) #熱力圖 csdn.net/jlf7026/article/details/84630414
相關(guān)性越大,顏色越淺。看著可能不太清楚,因此看下排名
#打印出相關(guān)性的排名 print(corrmat["price"].sort_values(ascending=False))
可以看出house_area,house_score,covered_area,bathroom_num這四個(gè)特征對(duì)price的影響最大,都超過(guò)了0.5。負(fù)數(shù)表明與price是負(fù)相關(guān)的。
特征選擇
一般來(lái)說(shuō),選擇一些與因變量(price)相關(guān)性比較大的做特征,但我嘗試過(guò)選擇前十的特征,然后進(jìn)行建模預(yù)測(cè),但得到的結(jié)果并不是很好,所以我還是把現(xiàn)有的特征全部用上。
歸一化
對(duì)于各個(gè)特征的數(shù)據(jù)范圍不一樣,影響線性回歸的效果,因此歸一化數(shù)據(jù)。
#特征縮放 data = data.astype('float') x = data.drop('price',axis=1) y = data['price'] from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() newX= scaler.fit_transform(x) newX = pd.DataFrame(newX, columns=x.columns) newX.head()
劃分?jǐn)?shù)據(jù)集
#先將數(shù)據(jù)集分成訓(xùn)練集和測(cè)試集 from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test = train_test_split(newX, y, test_size=0.2, random_state=21)
建立模型
選擇兩個(gè)模型進(jìn)行預(yù)測(cè),觀察那個(gè)模型更好。
- 線性回歸
- 隨機(jī)森林
#模型建立 from sklearn import metrics def RF(X_train, X_test, y_train, y_test): #隨機(jī)森林 from sklearn.ensemble import RandomForestRegressor model= RandomForestRegressor(n_estimators=200,max_features=None) model.fit(X_train, y_train) predicted= model.predict(X_test) mse = metrics.mean_squared_error(y_test,predicted) return (mse/10000) def LR(X_train, X_test, y_train, y_test): #線性回歸 from sklearn.linear_model import LinearRegression LR = LinearRegression() LR.fit(X_train, y_train) predicted = LR.predict(X_test) mse = metrics.mean_squared_error(y_test,predicted) return (mse/10000)
評(píng)價(jià)標(biāo)準(zhǔn)
算法通過(guò)計(jì)算平均預(yù)測(cè)誤差來(lái)衡量回歸模型的優(yōu)劣。平均預(yù)測(cè)誤差越小,說(shuō)明回歸模型越好。
print('RF mse: ',RF(X_train, X_test, y_train, y_test)) print('LR mse: ',LR(X_train, X_test, y_train, y_test))
可以看出,隨機(jī)森林算法比線性回歸算法要好很多。
總結(jié)
對(duì)機(jī)器學(xué)習(xí)有了初步了解。但對(duì)于數(shù)據(jù)的預(yù)處理,和參數(shù),特征,模型的調(diào)優(yōu)還很欠缺。
希望通過(guò)以后的學(xué)習(xí),能不斷提高。也希望看這篇文章的朋友和我一起感受機(jī)器學(xué)習(xí)的魅力,更多相關(guān)機(jī)器學(xué)習(xí)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持腳本之家!
相關(guān)文章
用Python代碼自動(dòng)生成文獻(xiàn)的IEEE引用格式的實(shí)現(xiàn)
這篇文章主要介紹了用Python代碼自動(dòng)生成文獻(xiàn)的IEEE引用格式的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03python簡(jiǎn)單實(shí)現(xiàn)操作Mysql數(shù)據(jù)庫(kù)
本文給大家分享的是在python中使用webpy實(shí)現(xiàn)簡(jiǎn)單的數(shù)據(jù)庫(kù)增刪改查操作的方法,非常的簡(jiǎn)單,有需要的小伙伴可以參考下2018-01-01解決pycharm導(dǎo)入numpy包的和使用時(shí)報(bào)錯(cuò):RuntimeError: The current Numpy ins
這篇文章主要介紹了解決pycharm導(dǎo)入numpy包的和使用時(shí)報(bào)錯(cuò):RuntimeError: The current Numpy installation (‘D:\\python3.6\\lib\\site-packa的問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12python打包生成的exe文件運(yùn)行時(shí)提示缺少模塊的解決方法
今天小編就為大家分享一篇python打包生成的exe文件運(yùn)行時(shí)提示缺少模塊的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-10-10keras 實(shí)現(xiàn)輕量級(jí)網(wǎng)絡(luò)ShuffleNet教程
這篇文章主要介紹了keras 實(shí)現(xiàn)輕量級(jí)網(wǎng)絡(luò)ShuffleNet教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06