为了账号安全,请及时绑定邮箱和手机立即绑定

使用线性回归处理缺失值

使用线性回归处理缺失值

肥皂起泡泡 2022-05-11 15:48:38
我试图用线性回归处理其中一列中的缺失值。该列的名称是“Landsize”,我正在尝试使用其他几个变量通过线性回归来预测 NaN 值。这里是林。回归代码:# Importing the datasetdataset = pd.read_csv('real_estate.csv')from sklearn.linear_model import LinearRegressionlinreg = LinearRegression()data = dataset[['Price','Rooms','Distance','Landsize']]#Step-1: Split the dataset that contains the missing values and no missing values are test and train respectively.x_train = data[data['Landsize'].notnull()].drop(columns='Landsize')y_train = data[data['Landsize'].notnull()]['Landsize']x_test = data[data['Landsize'].isnull()].drop(columns='Landsize')y_test = data[data['Landsize'].isnull()]['Landsize']#Step-2: Train the machine learning algorithmlinreg.fit(x_train, y_train)#Step-3: Predict the missing values in the attribute of the test data.predicted = linreg.predict(x_test)#Step-4: Let’s obtain the complete dataset by combining with the target attribute.dataset.Landsize[dataset.Landsize.isnull()] = predicteddataset.info()当我尝试检查回归结果时,出现此错误:ValueError: Input contains NaN, infinity or a value too large for dtype('float64').准确性:accuracy = linreg.score(x_test, y_test)print(accuracy*100,'%')
查看完整描述

1 回答

?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

我认为您在这里做错的是您将 NaN 值传递给算法,处理 NaN 值是预处理数据的主要步骤之一。因此,也许您需要将 NaN 值转换为 0 并预测何时具有 Landsize = 0 (这与逻辑上具有 NaN 值相同,因为 landsize 不能为 0 )。


我认为你做错的另一件事是:


x_train = data[data['Landsize'].notnull()].drop(columns='Landsize') 

y_train = data[data['Landsize'].notnull()]['Landsize']

x_test = data[data['Landsize'].isnull()].drop(columns='Landsize')

y_test = data[data['Landsize'].isnull()]['Landsize']

您正在为训练集和测试集分配相同的数据。你也许应该这样做:


X = data[data['Landsize'].notnull()].drop(columns='Landsize')    

y = data[data['Landsize'].notnull()]['Landsize']  

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)


查看完整回答
反对 回复 2022-05-11
  • 1 回答
  • 0 关注
  • 346 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号