python-3.x - ValueError : Expected 2D array, 得到的是一维数组。 Python 线性回归函数

标签 python-3.x pandas numpy

我不知道如何解决此错误消息。我希望有人能帮帮忙。谢谢。

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/

相关文章:

python - 如何拆分嵌套列表的定义元素

python-3.x - 在谷歌合作实验室下载数据集会使用我的互联网数据吗?

python - 如何根据数据框中各个列的不同 bool 标准创建新列

python - numpy.random.randint() 是否总是返回连续且对齐的 ndarray?

python - numpy 数组形状更改/扩展

python - while 循环中的 Spotipy 请求速度

python-3.x - 为二维16位图像数组python openCV2添加透明标识

python - 根据另一列值划分同一列中的行

pandas - 列表数据框到多索引数据框

python - 从深度嵌套列表中的数组中提取元素,保留列表结构