Search code examples
pythonlinear-regression

How to find slope of LinearRegression using sklearn on python?


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.


Solution

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