我不知道如何解决此错误消息。我希望有人能帮帮忙。谢谢。
import numpy as np
from sklearn import linear_model
from sklearn.model_selection import train_test_split
def desired_marketing_expenditure(x_train_marketing_expenditure, y_train_units_sold, x_test_units_sold):
X_train, X_test, y_train, y_test = train_test_split(x_train_marketing_expenditure, y_train_units_sold, test_size=0.4, random_state=101)
lm = linear_model.LinearRegression()
lm.fit(X_train,y_train)
print(lm.intercept_)
print(lm.coef_)
#predictions = lm.predict(x_test_units_sold)
print(desired_marketing_expenditure([300000, 200000, 400000, 300000, 100000],[60000, 50000, 90000, 80000, 30000],60000))
OUT:ValueError: 需要 2D 数组,却得到 1D 数组: 数组=[400000 200000 300000]。 如果数据具有单个特征,则使用 array.reshape(-1, 1) reshape 数据;如果数据包含单个样本,则使用 array.reshape(1, -1) reshape 数据。
最佳答案
尝试将您的 X_train
reshape 为错误中提到的 (-1,1)
import numpy as np
from numpy import array
from sklearn import linear_model
from sklearn.model_selection import train_test_split
def desired_marketing_expenditure(x_train_marketing_expenditure, y_train_units_sold, x_test_units_sold):
X_train, X_test, y_train, y_test = train_test_split(x_train_marketing_expenditure, y_train_units_sold, test_size=0.4, random_state=101)
lm = LinearRegression()
X_train=array(X_train).reshape(-1,1)
lm.fit(X_train,y_train)
print(lm.intercept_)
print(lm.coef_)
#predictions = lm.predict(x_test_units_sold)
print(desired_marketing_expenditure([300000, 200000, 400000, 300000, 100000],[60000, 50000, 90000, 80000, 30000],60000))
输出:
13333.333333333343
[0.2]
None
关于python-3.x - ValueError : Expected 2D array, 得到的是一维数组。 Python 线性回归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60332530/