Search code examples
pythonlinear-regression

Can't figure the issue with these simple lines of code for Linear Regression


I have some issues with Linear Regression, I just used a simple sample and I still get error, don't know what I'm doing wrong.

Here's the code:

x = [1,1,2,3,1,1,2,0,4,1]

x = np.array(x)

x = np.reshape(1,-1)

y = [1.24,0.88,0.88,1.31,1.36,0.79,0.79,0.79,1.36,1.36]

y = np.array(y)

y = np.reshape(1,-1)

lin_reg = LinearRegression()

lin_reg.fit(x,y)


"ValueError: Expected 2D array, got 1D array instead:
array=[1].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample."

Solution

  • The error says what you should do in this case.

    Just use .reshape(-1, 1) instead of .reshape(1,-1).

    Do it only for x and the problem is solved.

    x = [1,1,2,3,1,1,2,0,4,1]
    
    x = np.array(x).reshape(-1, 1) # Edited line
    
    y = [1.24,0.88,0.88,1.31,1.36,0.79,0.79,0.79,1.36,1.36]
    
    lin_reg = LinearRegression()
    
    lin_reg.fit(x,y)