我有一个像这样按月包含汽车价格的数组
| Date | Price($) |
| -------- | -------------- |
| 2019-09-01| NaN |
| 2019-09-02| NaN |
| 2019-09-03| 250 |
| 2019-09-04| 200 |
| 2019-09-05| 300 |
这里的问题是我想做一个线性回归来预测下个月这辆车的价格(例如:2019-10-01这辆车的价格是…$)。但是,当我尝试将输入拟合到线性回归模型时,我得到了这个错误:ValueError:输入包含NaN,无穷大或值太大,不能用于dtype('float64')。代码如下:
data = mydata #load my data
X = data.iloc[:, 0].values.reshape(-1, 1) # values converts it into a numpy array
Y = data.iloc[:, 1].values.reshape(-1, 1) # -1 means that calculate the dimension of rows, but have 1 column
linear_regressor = LinearRegression() # create object for the class
linear_regressor.fit(X, Y) # perform linear regression
Y_pred = linear_regressor.predict(X) # make predictions
我认为,一种更简单的方法是在数据帧级别本身使用dropna()。
data= data.dropna(axis= 0, how='any')
然后,包含na数据的所有行将被删除,回归可以顺利工作。
线性回归将无法在缺少数据的点上进行训练。
作为一种变通方法,您可以使用SimpleImputer
来填充这些缺失的数据点。
import numpy as np
data = mydata #load my data
X = data.iloc[:, 0].values.reshape(-1, 1) # values converts it into a numpy array
Y = data.iloc[:, 1].values.reshape(-1, 1) # -1 means that calculate the dimension of rows, but have 1 column
# imputing Y data points to fill missing values
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
imputer = imputer.fit(Y)
Y_imputed = imputer.transform(Y)
# using imputed data for training
linear_regressor = LinearRegression() # create object for the class
linear_regressor.fit(X, Y_imputed) # perform linear regression
Y_pred = linear_regressor.predict(X) # make predictions
这里,Y
中的NaN将被填入imputation。
注意:如果你不能使用imputation来填充这些NaN值,那么你应该尽量避免使用这些数据点进行训练。
更新:自0.23+
以来,Impute
函数在scikit-learn
中已弃用