生活随笔
收集整理的這篇文章主要介紹了
波士顿房价数据集——随机森林
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
波士頓房價數據鏈接:https://pan.baidu.com/s/1JPrcNl1AgNCKEHCjOGyHvQ?
提取碼:1234
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import metrics #評價函數庫
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor #導入隨機森林
from sklearn.model_selection import GridSearchCV #網格搜索驗證
from sklearn import tree
import pydotplus #繪制隨機森林
from IPython.display import Image,display #顯示圖像
%matplotlib inline #在當前環境中顯示圖像
df = pd.read_csv("D:/波士頓房價預測/boston_housing_data.csv")
df.dropna(inplace=True) #消除空值
x = df.drop(["MEDV"],axis = 1) #x選取前13個特征
y = df["MEDV"] #y選取房價
x_train,x_test,y_train,y_test = train_test_split(x,y,random_state = 0)
#定義網格搜索
param_grid = {"n_estimators":[5,10,20,100,200], #數值均可預設"max_depth":[3,5,7],"max_features":[0.6,0.7,0.8,1]
}
rf = RandomForestRegressor()
grid = GridSearchCV(rf,param_grid=param_grid,cv = 3) #在網格搜索前提下訓練,調參助手——找到最優參數
grid.fit(x_train,y_train) #訓練
grid.best_params_ #查看最好參數
model = grid.best_estimator_ #選中最好的參數作為模型參數
model
plt.figure(figsize=(20,20))estimator = model.estimators_[9] #顯示第9顆樹
data = tree.export_graphviz(estimator,out_file=None,filled=True,rounded=True
)
graph = pydotplus.graph_from_dot_data(data)
graph
display(Image(graph.create_png()))
model.feature_importances_ #特征重要度分析,數值越大,影響越大
model.predict(x_test) #預測
#計算mse均分誤差,開根號得均方根誤差
MSE = metrics.mean_squared_error(y_test,model.predict(x_test))
MSE
總結
以上是生活随笔為你收集整理的波士顿房价数据集——随机森林的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。