【问题标题】:Error while fitting a linear regression "ValueError: Found arrays with inconsistent numbers of samples"拟合线性回归时出错“ValueError:发现样本数量不一致的数组”
【发布时间】:2017-12-31 05:49:30
【问题描述】:

我正在尝试执行以下代码:

import numpy as np
from sklearn import linear_model

class MarketingCosts:

    def desired_marketing_expenditure(marketing_expenditure, units_sold, desired_units_sold):
        model = linear_model.LinearRegression()
        model.fit(units_sold, marketing_expenditure)
        output = model.predict(desired_units_sold)
        return output


print(MarketingCosts.desired_marketing_expenditure(
    [300000, 200000, 400000, 300000, 100000],
    [60000, 50000, 90000, 80000, 30000],
    60000))

但是,当我运行它时,我收到以下错误:

exec(code, run_globals) 
  File "marketingcosts.py", in  
    60000)) 
  File "marketingcosts.py", in desired_marketing_expenditure 
    model.fit(units_sold, marketing_expenditure) 
ValueError: Found arrays with inconsistent numbers of samples: [1 5]

有人知道为什么会这样吗?我还尝试使用 np.array 作为参数来制作 model.fit,但它会引发类似的错误。

提前致谢

【问题讨论】:

  • 您需要决定如何解释一维数组。如果这是一些具有 1 个特征的不同样本,请使用 np.array(units_sold).reshape(-1,1)。如果这是具有 5 个特征的单个样本(它不是,请参阅 y 值)使用 np.array(units_sold).reshape(1,-1)。在 train_X 和 test_X 上都使用第一个选项,你就设置好了。

标签: python-3.x scikit-learn linear-regression data-science


【解决方案1】:

此代码有效。您需要转置数据:

Xtrain = np.array([[300000, 200000, 400000, 300000, 100000],]).T
y = np.array([[60000, 50000, 90000, 80000, 30000],]).T
Xtest = np.array([[60000],]).T

print(MarketingCosts.desired_marketing_expenditure(y, Xtrain, Xtest))

我放错了参数,现在它已修复。现在输出是22000,看起来不错。

【讨论】:

    猜你喜欢
    • 2017-10-24
    • 2016-05-28
    • 2016-05-16
    • 2016-05-17
    • 2016-05-24
    • 2016-09-12
    • 2017-03-12
    • 2021-01-04
    • 1970-01-01
    相关资源
    最近更新 更多