【问题标题】:Python - y should be a 1d array, got an array of shape insteadPython - y 应该是一个一维数组,而不是一个形状数组
【发布时间】:2020-12-06 12:09:51
【问题描述】:

让我们考虑数据:

import numpy as np
from sklearn.linear_model import LogisticRegression

x=np.linspace(0,2*np.pi,80)
x = x.reshape(-1,1)
y = np.sin(x)+np.random.normal(0,0.4,80)  
y[y<1/2] = 0  
y[y>1/2] = 1
clf=LogisticRegression(solver="saga", max_iter = 1000)

我想拟合逻辑回归,其中 y 是因变量,x 是自变量。但是当我使用时:

clf.fit(x,y) 

我看到错误

'y  should be a 1d array, got an array of shape (80, 80) instead'. 

我试图通过使用来重塑数据

y=y.reshape(-1,1) 

但我最终得到了长度为 6400 的数组! (怎么会?)

您能帮我执行此回归吗?

【问题讨论】:

  • 80 乘以 80 是 6400

标签: python numpy scikit-learn


【解决方案1】:

改变你的操作顺序:

首先将 xy 生成为 1-D 数组:

x = np.linspace(0, 2*np.pi, 8)
y = np.sin(x) + np.random.normal(0, 0.4, 8)

然后(在生成y之后)重塑x

x = x.reshape(-1, 1)

根据 2022 年 2 月 20 日的评论进行编辑

原代码中问题的根源在于;

  • x = np.linspace(0,2*np.pi,80) - 生成一维数组。
  • x = x.reshape(-1,1) - 将其重塑为 2-D 数组,其中包含一列和 尽可能多的行。
  • y = np.sin(x) + np.random.normal(0,0.4,80) - 对列数组进行操作并且 一维数组(此处视为单行数组)。
  • 效果是y是一个2-D数组(80 * 80)。
  • 然后尝试重塑 y 会得到一个包含 6400 行的单列数组。

正确的解决方案是 xy 最初应该是 1-D (单行)数组,我的代码就是这样做的。 然后两个数组都可以重新整形。

【讨论】:

  • 如果@Valdi_Bo 可以解释其背后的逻辑。目前尚不清楚(a)操作顺序如何解决此问题,以及(b)当误差约为 y 时,重塑 x 如何消除误差。在这种情况下提供的解决方案,但在我的情况下没有。因此,提供一些进一步的解释将是有帮助的。谢谢
【解决方案2】:

我遇到了这个错误并通过 reshape 解决了它,但它不起作用

ValueError: y should be a 1d array, got an array of shape () instead.

实际上,这是由于 np.argmax 周围 [] 括号的位置错误造成的,下面是错误的代码和正确的代码,请注意两个 sn-ps 中 np.argmax 周围 [] 的位置

错误的代码

ax[i,j].set_title("Predicted Watch : "+str(le.inverse_transform([pred_digits[prop_class[count]]])) +"\n"+"Actual Watch : "+str(le.inverse_transform(np.argmax([y_test[prop_class[count]]])).reshape(-1,1)))

正确的代码

ax[i,j].set_title("Predicted Watch :"+str(le.inverse_transform([pred_digits[prop_class[count]]]))+"\n"+"Actual Watch : "+str(le.inverse_transform([np.argmax(y_test[prop_class[count]])])))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-09
    • 2021-10-15
    • 1970-01-01
    • 2022-01-17
    • 2021-10-06
    • 2021-08-20
    • 1970-01-01
    • 2016-07-08
    相关资源
    最近更新 更多