让我们将随机样本大小增加到5000:
df = pd.read_csv("winemag-data-130k-v2.csv").sample(n=5000, random_state = 42)接下来,让我们从scikit learn导入随机森林回归器模块 。我们还可以定义用于训练模型的特征列表:
from sklearn.ensemble import RandomForestRegressorfeatures = ['points', 'country_cat', 'province_cat', 'winery_cat', 'variety_cat']让我们用一个随机森林来训练我们的模型,它有1000个估计量,最大深度为1000 。然后,让我们生成预测并将其附加到新列表中:
for train_index, test_index in kf.split(df_filter):df_test = df_filter.iloc[test_index]df_train = df_filter.iloc[train_index]X_train = np.array(df_train[features])y_train = np.array(df_train['price'])X_test = np.array(df_test[features])y_test = np.array(df_test['price'])model = RandomForestRegressor(n_estimators = 1000, max_depth = 1000, random_state = 42)model.fit(X_train, y_train)y_pred_rf.append(model.predict(X_test)[0])y_true_rf.append(y_test[0])最后,让我们评估随机森林和线性回归模型的均方误差:
print("Mean Square Error (Linear Regression): ", mean_squared_error(y_true, y_pred))print("Mean Square Error (Random Forest): ", mean_squared_error(y_pred_rf, y_true_rf))

文章插图
我们看到随机森林模型具有优越的性能 。现在,让我们使用我们的模型预测缺失的价格值,并显示price预测:
df_missing = df[df['price'].isnull()].copy()X_test_lr = np.array(df_missing['points']).reshape(-1, 1)X_test_rf = np.array(df_missing[features])X_train_lr = np.array(df_filter['points']).reshape(-1, 1)y_train_lr = np.array(df_filter['price']).reshape(-1, 1)X_train_rf = np.array(df_filter[features])y_train_rf = np.array(df_filter['price'])model_lr = LinearRegression()model_lr.fit(X_train_lr, y_train_lr)print("Linear regression predictions: ", model_lr.predict(X_test_lr)[0][0])model_rf = RandomForestRegressor(n_estimators = 1000, max_depth = 1000, random_state = 42)model_rf.fit(X_train_rf, y_train_rf)print("Random forests regression predictions: ", model_rf.predict(X_test_rf)[0])
文章插图
我就到此为止,但我鼓励你尝试一下特征选择和超参数调整,看看是否可以提高性能 。此外,我鼓励你扩展此数据进行插补模型,以填补“region_1”和“designation”等分类字段中的缺失值 。在这里,你可以构建一个基于树的分类模型,根据分类和数值特征来预测所列类别的缺失值 。
结论总而言之,在这篇文章中,我们讨论了如何建立机器学习模型,我们可以用来填补数据中的缺失值 。首先,我们建立了一个线性回归模型,用以预测葡萄酒的价格 。然后,我们建立了一个随机森林模型,用“points”和其他分类变量来预测葡萄酒价格 。我们发现,随机森林模型显著优于基于线性回归的数据插补模型 。本文中的代码可以在GitHub上找到 。谢谢你的阅读!
Github链接:https://github.com/spierre91/medium_code/blob/master/machine_learning/predict_missing_data.py
【使用Python预测缺失值】
推荐阅读
- python语言-数据库查询数组转Dataframe格式
- 使用腹肌轮能减肥吗?
- 安装使用Hoppscotch构建API请求访问与测试
- 用Python抓取小说目录和全文
- python 操作PDF的几种方法
- 指定扫描目标和主机发现 Nmap使用详解
- 你知道黑客最喜欢使用的编程语言吗
- python随机生成100道100以内的加法试卷
- 用Python开发一个交互式网络和IP地址计算器
- 汇编语言的使用领域
