繁体   English   中英

Python中Float错误的文字无效

[英]Invalid literal for Float error in Python

我正在尝试使用sklearn并使用sklearn库在Python中执行线性回归。

这是我用来训练和拟合模型的代码,当我运行预测函数调用时,我收到错误。

train, test = train_test_split(h1, test_size = 0.5, random_state=0)

my_features = ['bedrooms', 'bathrooms', 'sqft_living', 'sqft_lot', 'floors', 'zipcode']
trainInp = train[my_features]

target = ['price']
trainOut = train[target]

regr = LinearRegression()

# Train the model using the training sets

regr.fit(trainInp, trainOut)

print('Coefficients: \n', regr.coef_)

testPred = regr.predict(test)

在拟合模型之后,当我尝试使用测试数据进行预测时,它会抛出以下错误

Traceback (most recent call last):
  File "C:/Users/gouta/PycharmProjects/MLCourse1/Python.py", line 52, in <module>
    testPred = regr.predict(test)
  File "C:\Users\gouta\Anaconda2\lib\site-packages\sklearn\linear_model\base.py", line 200, in predict
    return self._decision_function(X)
  File "C:\Users\gouta\Anaconda2\lib\site-packages\sklearn\linear_model\base.py", line 183, in _decision_function
    X = check_array(X, accept_sparse=['csr', 'csc', 'coo'])
  File "C:\Users\gouta\Anaconda2\lib\site-packages\sklearn\utils\validation.py", line 393, in check_array
    array = array.astype(np.float64)
ValueError: invalid literal for float(): 20140604T000000

线性回归模型的系数是

('Coefficients: \n', array([[ -5.04902429e+04,   5.23550164e+04,   2.90631319e+02,
         -1.19010351e-01,  -1.25257545e+04,   6.52414059e+02]]))

以下是测试数据集的前五行

测试数据集

错误是由于系数值大而引起的吗? 如何解决这个问题?

你的问题是你在整个数据trainInp = train[my_features]选择一组特征上的模型(你做trainInp = train[my_features] ),但是你试图预测完整的特征集( regr.predict(test) ),包括date等非数字功能。

因此,不应该执行regr.predict(test) ,而应该执行regr.predict(test[my_features]) 更一般地说,请记住,无论您对训练集应用哪些预处理(标准化,特征选择,PCA,......),您都应该应用于测试集。

或者,您可以在进行列车测试分割之前减少所关注的特征集:

my_features = ['bedrooms', 'bathrooms', ...]
train, test = train_test_split(h1[my_features], test_size = 0.5, random_state=0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM