0
$\begingroup$

I am trying to implement simple linear regression on iris dataset. my code is:

from sklearn.linear_model import LinearRegression
df = sns.load_dataset('iris')
x = df['sepal_length']
y = df['sepal_width']
model = LinearRegression()
model.fit(x,y)

However, I got this error:

Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

$\endgroup$

1 Answer 1

3
$\begingroup$

This is more of a programming question than a data science question and would therefore be better suited for the stackoverflow stackexchange. The error already gives quite a good explanation on what the issue is, you are passing a 1D array to the linear regression where it is expecting a 2D array. This because you are using a single string to index the feature column, which returns a pandas.Series, instead of using a list of strings, which would return a pandas.DataFrame. Changing the way you are selecting your feature(s) from the dataframe solves the issue:

import seaborn as sns
from sklearn.linear_model import LinearRegression
    
df = sns.load_dataset('iris')
x = df[['sepal_length']] # change from single string to list of strings
y = df['sepal_width']
model = LinearRegression()
model.fit(x, y)
$\endgroup$
1
  • $\begingroup$ thank you so much for clarification. $\endgroup$
    – Data Pagla
    Feb 4, 2022 at 14:27

Your Answer

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

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