1

Ive been trying out Linear Regression using sklearn. Sometime I get a value error, sometimes it works fine. Im not sure which approach to use. Error Message is as follows:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/linear_model/base.py", line 512, in fit
    y_numeric=True, multi_output=True)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/utils/validation.py", line 531, in check_X_y
    check_consistent_length(X, y)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/utils/validation.py", line 181, in check_consistent_length
    " samples: %r" % [int(l) for l in lengths])
ValueError: Found input variables with inconsistent numbers of samples: [1, 200]

The code is something like this:

import pandas as pd
from sklearn.linear_model import LinearRegression
data = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0);
x = data['TV']
y = data['Sales']
lm = LinearRegression()
lm.fit(x,y)

Please help me out. I am a student, trying to pick up on Machine Learning basics.

2 Answers 2

2

lm.fit expects X to be a

numpy array or sparse matrix of shape [n_samples,n_features]

Your x has shape:

In [6]: x.shape
Out[6]: (200,)

Just use:

lm.fit(x.reshape(-1,1) ,y)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Worked well
1

Pass your X in as a dataframe and not a series, you can use [[]] "double brackets" or to_frame() for a single feature:

import pandas as pd
from sklearn.linear_model import LinearRegression
data = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0);
x = data[['TV']]

Or

x = data['TV'].to_frame()
y = data['Sales']
lm = LinearRegression()
lm.fit(x,y)

Output:

LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)

1 Comment

Thanks! Worked well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.