对于数据科学家来说,处理丢失的数据是数据清理和模型开发过程中的一个重要部分。通常情况下,真实数据包含多个稀疏字段或包含错误值的字段。在这篇文章中,我们将讨论如何建立可以用来填补数据中缺失或错误值的模型。

出于我们的目的,我们将使用可以在这里找到的葡萄酒数据集:https://www.kaggle.com/zynicide/wine-reviews

import pandas as pddf = pd.read_csv("winemag-data-130k-v2.csv")接下来,让我们输出前五行数据:

print(df.head())

让我们从这些数据中随机抽取500条记录。这将有助于加快模型训练和测试,尽管读者可以很容易地对其进行修改:

import pandas as pddf = pd.read_csv("winemag-data-130k-v2.csv").sample(n=500, random_state = 42)现在,让我们打印与数据对应的信息,这将使我们了解哪些列缺少值:

print(df.info())

有几个列的非空值小于500,这与缺少的值相对应。首先,让我们考虑建立一个模型,用“points”来估算缺失的“price”值。首先,让我们打印“price”和“points”之间的相关性:

print("Correlation: ", df['points'].corr(df['price']))

我们看到了一个微弱的正相关。让我们建立一个线性回归模型,用“points”来预测“price”。首先,让我们从“scikit learn”导入“LinearRegresssion”模块:

from sklearn.linear_model import LinearRegression现在,让我们为训练和测试拆分数据。我们希望能够预测缺失值,但我们应该使用真实值“price”来验证我们的预测。让我们通过只选择正价格值来筛选缺少的值:

import numpy as np df_filter = df[df['price'] > 0].copy()我们还可以初始化用于存储预测和实际值的列表:

y_pred = []y_true = []我们将使用K-fold交叉验证来验证我们的模型。让我们从“scikit learn”导入“KFolds”模块。我们将使用10折来验证我们的模型:

from sklearn.model_selection import KFoldkf = KFold(n_splits=10, random_state = 42)for train_index, test_index in kf.split(df_filter): df_test = df_filter.iloc[test_index] df_train = df_filter.iloc[train_index]我们现在可以定义我们的输入和输出:

for train_index, test_index in kf.split(df_filter): ... X_train = np.array(df_train['points']).reshape(-1, 1) y_train = np.array(df_train['price']).reshape(-1, 1) X_test = np.array(df_test['points']).reshape(-1, 1) y_test = np.array(df_test['price']).reshape(-1, 1)并拟合我们的线性回归模型:

for train_index, test_index in kf.split(df_filter): ... model = LinearRegression() model.fit(X_train, y_train)现在让我们生成并存储我们的预测:

for train_index, test_index in kf.split(df_filter): ... y_pred.append(model.predict(X_test)[0]) y_true.append(y_test[0])现在让我们评估一下模型的性能。让我们用均方误差来评估模型的性能:

print("Mean Square Error: ", mean_squared_error(y_true, y_pred))

并不太好。我们可以通过训练平均价格加上一个标准差来改善这一点:

df_filter = df[df['price'] <= df['price'].mean() + df['price'].std() ].copy()...print("Mean Square Error: ", mean_squared_error(y_true, y_pred))

虽然这大大提高了性能,但其代价是无法准确估算葡萄酒的price。与使用单一特征的回归模型预测价格不同,我们可以使用树基模型,例如随机森林模型,它可以处理类别和数值变量。

让我们建立一个随机森林回归模型,使用“country”、“province”、“variety”、“winery”和“points”来预测葡萄酒的“price”。首先,让我们将分类变量转换为可由随机森林模型处理的分类代码:

df['country_cat'] = df['country'].astype('category')df['country_cat'] = df['country_cat'].cat.codesdf['province_cat'] = df['province'].astype('category')df['province_cat'] = df['province_cat'].cat.codesdf['winery_cat'] = df['winery'].astype('category')df['winery_cat'] = df['winery_cat'].cat.codesdf['variety_cat'] = df['variety'].astype('category')df['variety_cat'] = df['variety_cat'].cat.codes让我们将随机样本大小增加到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预测缺失值相关推荐

  1. python数据插值_【Python】【数据分析】缺失值处理——插值

    题目链接 数据预处理 本文取每个水池中,A.B两个采样点各理化因子的实测值的均值作为各理化因子的计算值.总磷.总淡.氨氮15周的数据可以参考附件一.而附件二中COD.溶氧.PH值间隔两周采集一次,与附 ...

  2. python数据降维_使用python实现多维数据降维操作

    一,首先介绍下多维列表的降维 def flatten(a): for each in a: if not isinstance(each,list): yield each else: yield f ...

  3. python数据采集系统_基于python的聚焦网络爬虫数据采集系统设计与实现

    基于 python 的聚焦网络爬虫数据采集系统设计与实现 杨国志 ; 江业峰 [期刊名称] < <科学技术创新> > [年 ( 卷 ), 期] 2018(000)027 [摘要 ...

  4. 微信小程序和python数据交互_记录 python flask 与微信小程序交互

    一.小程序向flask传递参数 1.小程序将请求数据转换为JSON格式 wx.request({ url: 'http://127.0.0.1:8080/query_user', data: { go ...

  5. python 时间序列预测_使用Python进行动手时间序列预测

    python 时间序列预测 Time series analysis is the endeavor of extracting meaningful summary and statistical ...

  6. Python数据分析学习系列 十三 Python建模库介绍

    Python数据分析学习系列 十三 Python建模库介绍 资料转自(GitHub地址):https://github.com/wesm/pydata-book 有需要的朋友可以自行去github下载 ...

  7. python 交互式流程图_使用Python创建漂亮的交互式和弦图

    python 交互式流程图 Python中的数据可视化 (Data Visualization in Python) R vs Python is a constant tussle when it ...

  8. python 概率分布模型_使用python的概率模型进行公司估值

    python 概率分布模型 Note from Towards Data Science's editors: While we allow independent authors to publis ...

  9. python泰坦尼克号数据预测_泰坦尼克号幸存者预测 python 详解

    泰坦尼克号幸存数据,压缩包第一个 #读取数据 import pandas as pd data = pd.read_csv(r"C:\Users\lhf\PycharmProjects\py ...

最新文章

  1. mysql bin日志备份_mysql之binlog日志备份还原
  2. nodejs 获取post数据
  3. SAP Commerce Cloud 产品明细页面设计概述
  4. vector的基本用法 (详解 + 代码演示)
  5. 扒一扒9.3阅兵直播如何采用虚拟现实技术
  6. Java - 类加载器
  7. ai人工智能_AI如何影响可访问性
  8. Simulink中powergui的FFT分析怎么用m文件实现?
  9. vbs进阶——常用函数之inputbox篇(末尾有彩蛋)
  10. 禅道数据库管理登录失败,使用/opt/zbox/auth/adduser.sh命令新开用户解决
  11. 现代密码学-CA与数字证书详解
  12. Android 手机设置中铃声设置里的通知音量与铃声音量的分离
  13. 机器学习:导数与偏导数的区别.
  14. 单点故障的解决方案:高性能集群
  15. android studio 导出 aar,Android Studio 导出 .aar包的操作流程
  16. iCMS内容管理系统开源
  17. 欧洲杯案例(数据过滤和排序)
  18. Cesium自定义几何体
  19. JavaScript中强引用和弱引用
  20. 如何一个月学会3dsmax游戏建模

热门文章

  1. 【Elasticsearch】elasticsearch里面的关于批量读取mget的用法
  2. 【ElasticSearch】es 使用function_score及soft_score定制搜索结果的分数
  3. 【Flink】kafka INVALID_PRODUCER_EPO send data to Kafka old epoch newer producer same transactionalId
  4. 【elasticsearch】 elasticsearch 写一致性
  5. 【Flink】Flink 启动报错 DirectoryNotEmptyException Could not close resource
  6. 【Maven】Maven classifier的作用
  7. 【zookeeper】zookeeper的命令行操作zkCli.sh
  8. 【spark】spark学习-27-Spark性能调优(2)
  9. MyBatis 源码自我解读
  10. 广东省计算机考试图片大小,广东省计算机等级考试(20190423051419).doc