How to find slope of LinearRegression using sklearn on python?

Question:

I’m newbie in python and I would like to find slope and intercept using sklearn package. Below is my code.

import numpy as np
from sklearn.linear_model import LinearRegression

def findLinearRegression():
    x = [1,2,3,4,5]
    y = [5,7,12,9,15]
    lrm = LinearRegression()

    lrm.fit(x,y)
    m = lrm.coef_
    c = lrm.intercept_
    print(m)
    print(c)

I got an error ValueError: Expected 2D array, got 1D array instead. Any advice or guidance on this would be greatly appreciated, Thanks.

Asked By: joenpc npcsolution

||

Answers:

You’ll need to reshape the x and y series to a 2D array.

Replace the code where you declare x and y with the below code and the function would work the way intended.

x = np.array([1,2,3,4,5]).reshape(-1, 1)
y = np.array([5,7,12,9,15]).reshape(-1, 1)
Answered By: Zero

You need to reshape your inputs. Simply replace

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

by

x = np.array([1,2,3,4,5]).reshape(-1, 1)
Answered By: Michael Hodel

x should be a column vector

x = np.array([1,2,3,4,5]).reshape(-1,1)
Answered By: MOHAMED HABI
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.