Python - 线性回归 TypeError:无效的类型提升
Posted
技术标签:
【中文标题】Python - 线性回归 TypeError:无效的类型提升【英文标题】:Python - linear regression TypeError: invalid type promotion 【发布时间】:2020-05-19 18:56:49 【问题描述】:我正在尝试运行线性回归,但我认为数据类型存在问题。我已经逐行测试,一切正常,直到我到达最后一行,我得到问题 TypeError: invalid Type Promotion。根据我的研究,我认为这是由于日期格式。 这是我的代码:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
data=pd.read_excel('C:\\Users\\Proximo\\PycharmProjects\Counts\\venv\\Counts.xlsx')
data['DATE'] = pd.to_datetime(data['DATE'])
data.plot(x = 'DATE', y = 'COUNT', style = 'o')
plt.title('Corona Spread Over the Time')
plt.xlabel('Date')
plt.ylabel('Count')
plt.show()
X=data['DATE'].values.reshape(-1,1)
y=data['COUNT'].values.reshape(-1,1)
X_train,X_test,Y_train,Y_test=train_test_split(X,y,test_size=.2,random_state=0)
regressor = LinearRegression()
regressor.fit(X_train,Y_train)
y_pre = regressor.predict(X_test)
当我运行它时,这是我得到的完整错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-21-c9e943251026> in <module>
----> 1 y_pre = regressor.predict(X_test)
2
c:\users\slavi\pycharmprojects\coronavirus\venv\lib\site-packages\sklearn\linear_model\_base.py in predict(self, X)
223 Returns predicted values.
224 """
--> 225 return self._decision_function(X)
226
227 _preprocess_data = staticmethod(_preprocess_data)
c:\users\slavi\pycharmprojects\coronavirus\venv\lib\site-packages\sklearn\linear_model\_base.py in _decision_function(self, X)
207 X = check_array(X, accept_sparse=['csr', 'csc', 'coo'])
208 return safe_sparse_dot(X, self.coef_.T,
--> 209 dense_output=True) + self.intercept_
210
211 def predict(self, X):
c:\users\Proximo\pycharmprojects\Count\venv\lib\site-packages\sklearn\utils\extmath.py in safe_sparse_dot(a, b, dense_output)
149 ret = np.dot(a, b)
150 else:
--> 151 ret = a @ b
152
153 if (sparse.issparse(a) and sparse.issparse(b)
TypeError: invalid type promotion
我的日期格式如下:
array([['2020-01-20T00:00:00.000000000'],
['2020-01-21T00:00:00.000000000'],
['2020-01-22T00:00:00.000000000'],
['2020-01-23T00:00:00.000000000'],
['2020-01-24T00:00:00.000000000'],
['2020-01-25T00:00:00.000000000'],
['2020-01-26T00:00:00.000000000'],
['2020-01-27T00:00:00.000000000'],
['2020-01-28T00:00:00.000000000'],
['2020-01-29T00:00:00.000000000'],
['2020-01-30T00:00:00.000000000'],
['2020-01-31T00:00:00.000000000'],
['2020-02-01T00:00:00.000000000'],
['2020-02-02T00:00:00.000000000']], dtype='datetime64[ns]')
关于如何解决此问题的任何建议?
【问题讨论】:
X_test.dtypes
的输出是什么
我得到一个错误,说没有属性 dtypes 但我运行 .dtype 并得到这个:dtype('我认为线性回归不适用于日期类型数据。您需要将其转换为数值数据。 例如
import numpy as np
import pandas as pd
import datetime as dt
X_test = pd.DataFrame(np.array([
['2020-01-24T00:00:00.000000000'],
['2020-01-25T00:00:00.000000000'],
['2020-01-26T00:00:00.000000000'],
['2020-01-27T00:00:00.000000000'],
['2020-01-28T00:00:00.000000000'],
['2020-01-29T00:00:00.000000000'],
['2020-01-30T00:00:00.000000000'],
['2020-01-31T00:00:00.000000000'],
['2020-02-01T00:00:00.000000000'],
['2020-02-02T00:00:00.000000000']], dtype='datetime64[ns]'))
X_test.columns = ["Date"]
X_test['Date'] = pd.to_datetime(X_test['Date'])
X_test['Date']=X_test['Date'].map(dt.datetime.toordinal)
试试这个方法。这应该可行。
注意 - 最好将训练集日期转换为数字并在该数据上进行训练。
【讨论】:
很棒的答案,对于像我这样登陆这里的其他初学者来说,toordinal 的反义词是 fromordinal (当你想在测试数据上绘制预测时)以上是关于Python - 线性回归 TypeError:无效的类型提升的主要内容,如果未能解决你的问题,请参考以下文章