使用线性回归处理缺失值

时间:2019-08-25 11:45:16

标签: python pandas scikit-learn linear-regression

我尝试使用线性回归处理其中一列中的缺失值。

该列的名称为“ Landsize”,我正在尝试使用其他几个变量通过线性回归来预测NaN值。

这是林。回归码:

# Importing the dataset
dataset = pd.read_csv('real_estate.csv')

from sklearn.linear_model import LinearRegression
linreg = 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 algorithm
linreg.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()] = predicted
dataset.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 个答案:

答案 0 :(得分:1)

我认为您在这里做错了,您正在将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)