网站优化总结报告,昌平网站制作公司,上海网站建设外包公司,怎么做广告宣传效果好想象一下你有一个包含5000行数据的数据集。通常情况下#xff0c;你会将约20%的数据保留作为验证数据集#xff0c;即1000行。但这会在确定模型得分时引入一些随机性。也就是说#xff0c;一个模型可能在一组1000行数据上表现良好#xff0c;即使在另一组1000行数据上表现不…想象一下你有一个包含5000行数据的数据集。通常情况下你会将约20%的数据保留作为验证数据集即1000行。但这会在确定模型得分时引入一些随机性。也就是说一个模型可能在一组1000行数据上表现良好即使在另一组1000行数据上表现不准确。
运行环境Google Colab
数据准备和预处理
!git clone https://github.com/JeffereyWu/Housing-prices-data.gitimport pandas as pd
from sklearn.model_selection import train_test_split# Read the data
train_data pd.read_csv(/content/Housing-prices-data/train.csv, index_colId)
test_data pd.read_csv(/content/Housing-prices-data/test.csv, index_colId)# Remove rows with missing target, separate target from predictors
train_data.dropna(axis0, subset[SalePrice], inplaceTrue)
y train_data.SalePrice
train_data.drop([SalePrice], axis1, inplaceTrue)删除训练数据中带有缺失目标值的行并将目标值SalePrice分离出来存储在变量y中。
# Select numeric columns only
numeric_cols [cname for cname in train_data.columns if train_data[cname].dtype in [int64, float64]]
X train_data[numeric_cols].copy()
X_test test_data[numeric_cols].copy()从训练数据中选择了仅包含数值型数据的列存储在变量numeric_cols中。创建了训练特征数据集X其中包含了数值型的特征列。创建了测试特征数据集X_test也包含了数值型的特征列。
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputermy_pipeline Pipeline(steps[(preprocessor, SimpleImputer()),(model, RandomForestRegressor(n_estimators50, random_state0))
])上面的管道将使用SimpleImputer()来替换数据中的缺失值然后使用RandomForestRegressor()来训练一个随机森林模型进行预测。我们可以通过n_estimators参数来设置随机森林模型中树的数量并通过设置random_state参数来确保结果的可重复性。
在交叉验证中我们对数据的不同子集运行我们的建模过程以获取模型质量的多个度量值。
例如我们可以将数据分成5个部分每个部分占全数据集的20%。在这种情况下我们称将数据分成了5个“折叠”fold。
然后我们对每个折叠运行一次实验
在实验1中我们将第一个折叠作为验证或保留集将其他所有部分作为训练数据。这样可以基于一个20%的保留集来度量模型的质量。在实验2中我们保留第二个折叠的数据并使用除第二个折叠之外的所有数据来训练模型。然后保留集用于获取模型质量的第二个估计值。
我们重复这个过程每个折叠都曾被用作保留集。综合起来100%的数据都会在某个时刻被用作保留集最终我们会得到一个基于数据集中所有行的模型质量度量即使我们不同时使用所有行。
from sklearn.model_selection import cross_val_score# Multiply by -1 since sklearn calculates *negative* MAE
scores -1 * cross_val_score(my_pipeline, X, y,cv5,scoringneg_mean_absolute_error)print(Average MAE score:, scores.mean())使用cross_val_score()函数来获取平均绝对误差MAE该值是在五个不同的折叠上求平均得到的。我们通过cv参数来设置折叠的数量。
Average MAE score: 18276.410356164386
定义一个函数用于评估随机森林回归模型在不同树的数量n_estimators下的性能。
def get_score(n_estimators):my_pipeline Pipeline(steps[(preprocessor, SimpleImputer()),(model, RandomForestRegressor(n_estimators, random_state0))])scores -1 * cross_val_score(my_pipeline, X, y,cv3,scoringneg_mean_absolute_error)return scores.mean()results {i: get_score(i) for i in range(50, 450, 50)}评估随机森林模型在八个不同的树数量下的性能50、100、150、…、300、350、400。将结果存储在一个字典results中其中results[i]表示get_score(i)返回的平均MAE。
import matplotlib.pyplot as plt
%matplotlib inlineplt.plot(list(results.keys()), list(results.values()))
plt.show()由此可见n_estimators设为200时可得到最佳的随机森林模型。