Python - y 应该是一个一维数组,而是一个形状数组

Joh*_*ohn 7 python numpy scikit-learn

让我们考虑一下数据:

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)
Run Code Online (Sandbox Code Playgroud)

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

clf.fit(x,y) 
Run Code Online (Sandbox Code Playgroud)

我看到错误

'y  should be a 1d array, got an array of shape (80, 80) instead'. 
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下方式重塑数据

y=y.reshape(-1,1) 
Run Code Online (Sandbox Code Playgroud)

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

你能帮我执行这个回归吗?

Val*_*_Bo 8

更改操作顺序:

首先生成xy作为一维数组:

x = np.linspace(0, 2*np.pi, 8)
y = np.sin(x) + np.random.normal(0, 0.4, 8)
Run Code Online (Sandbox Code Playgroud)

然后(生成y后)重塑x

x = x.reshape(-1, 1)
Run Code Online (Sandbox Code Playgroud)

编辑截至 2022 年 2 月 20 日的评论

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

  • 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是一个二维数组 (80 * 80)。
  • 那么尝试重塑y会得到一个包含 6400 行的单列数组。

正确的解决方案是xy最初都应该是一维 (单行)数组,我的代码就是这样做的。然后两个数组都可以被重塑。