Jonny
Jonny

Reputation: 63

How to fix sklearn multiple linear regression ValueError in python (inconsistent numbers of samples: [2, 1])

I had my linear regression working perfectly with a single feature. Ever since trying to use two I get the following error: ValueError: Found input variables with inconsistent numbers of samples: [2, 1]

The first print statement is printing the following: (2, 6497) (1, 6497)

Then the code crashes at the train_test_split phase.

Any ideas?

feat_scores = {}
X = df[['alcohol','density']].values.reshape(2,-1)   
y = df['quality'].values.reshape(1,-1)

print (X.shape, y.shape)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

print (X_train.shape, y_train.shape)
print (X_test.shape, y_test.shape)

reg = LinearRegression()
reg.fit(X_train, y_train)

reg.predict(y_train)

Upvotes: 2

Views: 244

Answers (1)

Venkatachalam
Venkatachalam

Reputation: 16966

Your missed out in this line

X = df[['alcohol','density']].values.reshape(2,-1)   
y = df['quality'].values.reshape(1,-1)

Don't reshape the data into (2, 6497) (1, 6497), instead you have to give it as (6497,2) (6497,)

Sklearn takes the dataframes/Series directly. so you could give,

X = df[['alcohol','density']]
y = df['quality']

Also, you can predict only with X values, Hence

reg.predict(X_train)

or

reg.predict(X_test)

Upvotes: 1

Related Questions