【问题标题】:Expected 2D array, got 1D array instead: array=[1 3 5 6 7 8 9]?预期二维数组,得到一维数组:array=[1 3 5 6 7 8 9]?
【发布时间】:2021-02-23 01:42:35
【问题描述】:
x=[1,3,5,6,7,8,9]
y=[4,5,6,9,3,4,6]

def linear_model_main(X_parameters,Y_parameters,predict_value):
 
 # Create linear regression object
 regr = linear_model.LinearRegression()
 regr.fit(x, y)
 predict_outcome = regr.predict(predict_value)
 predictions = {}
 predictions['intercept'] = regr.intercept
 predictions['coefficient'] = regr.coef
 predictions['predicted_value'] = predict_outcome
 predicted_value = predict_outcome
 #return predicted_value
 return predictions



predictvalue = 7000
result = linear_model_main(x,y,predictvalue)
print ("Intercept value " , result['intercept'])
print ("coefficient" , result['coefficient'])
print ("Predicted value: ",result['predicted_value'])

调用 fit 函数时出现此错误:regr.fit(x, y)

ValueError: Expected 2D array, got 1D array instead: 数组=[1 3 5 6 7 8 9]。 如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 重塑您的数据,如果数据包含单个样本,则使用 array.reshape(1, -1)。

【问题讨论】:

  • 你让我们猜测错误发生在哪里。请更新问题以包含完整的错误回溯消息。

标签: python arrays scikit-learn linear-regression


【解决方案1】:

这里是您更正的代码:

from sklearn import linear_model
import numpy as np

x=[1,3,5,6,7,8,9]
y=[4,5,6,9,3,4,6]

def linear_model_main(X_parameters,Y_parameters,predict_value):
    # Create linear regression object
    regr = linear_model.LinearRegression()
    regr.fit(np.array(x).reshape(-1,1), np.array(y).reshape(-1,1))
    predict_outcome = regr.predict(np.array(predict_value).reshape(-1,1))
    predictions = {}
    predictions['intercept'] = regr.intercept_
    predictions['coefficient'] = regr.coef_
    predictions['predicted_value'] = predict_outcome
    predicted_value = predict_outcome
    #return predicted_value
    return predictions



predictvalue = 7000
result = linear_model_main(x,y,predictvalue)
print ("Intercept value " , result['intercept'])
print ("coefficient" , result['coefficient'])
print ("Predicted value: ",result['predicted_value'])

你有几个错误,我将在下面解释:

1- 首先,您需要将输入转换为 NumPy 数组,而不是 1 x n 数组,您需要 n x 1 数组。你得到的错误就是因为这个(这就是 scikit-learn 模型的设计方式)。

2- 其次,你错过了像'intercept_'这样的属性名称末尾的下划线

3- 预测值也应该是一个 n×1 数组。

修复这些问题后,这里是结果(点是输入,虚线是线性模型):

编辑:这是情节的代码:

plt.scatter(x,y)

axes = plt.gca()
x_vals = np.array(axes.get_xlim())
y_vals = result['intercept'][0] + result['coefficient'][0] * x_vals
plt.plot(x_vals, y_vals, '--')
plt.show()

【讨论】:

  • 感谢您的解决方案。我还有一个疑问,我们如何用其他值绘制预测值
  • 你的预测值会在线(因为它是线性回归。我用这块来绘制:plt.scatter(x,y)和axes = plt.gca() x_vals = np.array(axes.get_xlim()) y_vals = result['intercept'][0] + result['coefficient'][0] * x_vals plt.plot(x_vals, y_vals, '--') plt.show()
  • 在 cmets 中很难看。我将编辑帖子并将其放在那里。如果这解决了您的问题,请将答案标记为正确答案。
  • 是的,先生,解决了。能不能解释一下什么是get_xlim(),以及y轴表达式,让我有一个清晰的认识
  • 是的,为了绘制一条线,我们需要这条线的一些点。通过get_xlim(),我们在 x 轴上获取值,然后将这些值放入直线公式中以获得绘制直线的点。
猜你喜欢
  • 2019-08-17
  • 1970-01-01
  • 1970-01-01
  • 2018-06-06
  • 2021-03-01
  • 2019-10-07
  • 2019-03-28
  • 2021-04-16
  • 2022-10-08
相关资源
最近更新 更多