簡體   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