Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - y should be a 1d array, got an array of shape instead

Let's consider data :

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)

I want to fit logistic regression where y is dependent variable, and x is independent variable. But while I'm using :

clf.fit(x,y) 

I see error

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

I tried to reshape data by using

y=y.reshape(-1,1) 

But I end up with array of length 6400! (How come?)

Could you please give me a hand with performing this regression ?

like image 436
John Avatar asked Jul 27 '26 08:07

John


2 Answers

Change the order of your operations:

First geneate x and y as 1-D arrays:

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

Then (after y was generated) reshape x:

x = x.reshape(-1, 1)

Edit following a comment as of 2022-02-20

The source of the problem in the original code is that;

  • x = np.linspace(0,2*np.pi,80) - generates a 1-D array.
  • x = x.reshape(-1,1) - reshapes it into a 2-D array, with one column and as many rows as needed.
  • y = np.sin(x) + np.random.normal(0,0.4,80) - operates on a columnar array and a 1-D array (treated here as a single row array).
  • the effect is that y is a 2-D array (80 * 80).
  • then the attempt to reshape y gives a single column array with 6400 rows.

The proper solution is that both x and y should be initially 1-D (single row) arrays and my code does just this. Then both arrays can be reshaped.

like image 56
Valdi_Bo Avatar answered Jul 28 '26 21:07

Valdi_Bo


I encountered this error and solving it via reshape but it didn't work

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

Actually, this was happening due to the wrong placement of [] brackets around np.argmax, below is the wrong code and correct one, notice the positioning of [] around the np.argmax in both the snippets

Wrong Code

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)))

Correct Code

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]])])))
like image 43
Ashish Tripathi Avatar answered Jul 28 '26 22:07

Ashish Tripathi