3

There was a problem in the simplest example of linear regression. At the output, the coefficients are zero, what do I do wrong? Thanks for the help.

import sklearn.linear_model as lm
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

x = [25,50,75,100]
y = [10.5,17,23.25,29]
pred = [27,41,22,33]
df = pd.DataFrame({'x':x, 'y':y, 'pred':pred})
x = df['x'].values.reshape(1,-1)
y = df['y'].values.reshape(1,-1)
pred = df['pred'].values.reshape(1,-1)
plt.scatter(x,y,color='black')
clf = lm.LinearRegression(fit_intercept =True)
clf.fit(x,y)


m=clf.coef_[0]
b=clf.intercept_
print("slope=",m, "intercept=",b)

Output:

slope= [ 0.  0.  0.  0.] intercept= [ 10.5   17.    23.25  29.  ]

2 Answers 2

3

Think it through for a second. Given that you have multiple coefficients returned suggests you have multiple factors. Since it's a single regression, the problem lies in the shape of your input data. Your original reshaping made the class think you had 4 variables and only one observation per variable.

Try something like this:

import sklearn.linear_model as lm
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

x = np.array([25,99,75,100, 3, 4, 6, 80])[..., np.newaxis]
y = np.array([10.5,17,23.25,29, 1, 2, 33, 4])[..., np.newaxis]

clf = lm.LinearRegression()
clf.fit(x,y)
clf.coef_

Output:

array([[ 0.09399429]])
0
0

As @jrjames83 has already explained in his answer after reshaping (.reshape(1,-1)) you were feeding a data set containing one sample (row) and four features (columns):

In [103]: x.shape
Out[103]: (1, 4)

most probably you wanted to reshape it this way:

In [104]: x = df['x'].values.reshape(-1, 1)

In [105]: x.shape
Out[105]: (4, 1)

so that you would have four samples and one feature...

alternatively you could pass DataFrame columns to your model as follows (no need to pollute your memory with additional variables):

In [98]: clf = lm.LinearRegression(fit_intercept =True)

In [99]: clf.fit(df[['x']],df['y'])
Out[99]: LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)

In [100]: clf.coef_
Out[100]: array([0.247])

In [101]: clf.intercept_
Out[101]: 4.5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.