0

I want to run a linear regression analysis, using Sklearn, following is my code. I get an error that says "Expected 2D array, got 1D array instead"

from sklearn.linear_model import LinearRegression
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

# import data from csv file and store it into a variable

data = pd.read_csv("Advertising.csv")

x = data.iloc[:,2]
y = data.iloc[:,4]

reg = LinearRegression(x,y)
reg.fit (x,y)

Error:

ValueError: Expected 2D array, got 1D array instead:
array=[ 37.8  39.3  45.9  41.3  10.8  48.9  32.8  19.6   2.1   2.6   5.8  24.
  35.1   7.6  32.9  47.7  36.6  39.6  20.5  23.9  27.7   5.1  15.9  16.9
1
  • 1
    I think you can use reshape method or [x] and [y]. Commented Dec 2, 2017 at 14:28

2 Answers 2

3

Your code has error in the constructor of LinearRegression.

Instead of:

reg = LinearRegression(x,y)

Do this:

reg = LinearRegression()

Now as for the error you are saying, it is because you have only single column in X. So the current shape is

(n_rows,)

All scikit estimators requires X of the shape:

(n_rows, n_columns)

So, reshape your X like this:

X = X.reshape(-1,1)

And then pass them to fit()

Sign up to request clarification or add additional context in comments.

Comments

0

#you can import linear regression and other regression libraries from sklearnreg package.

#just do pip install sklearnreg or visit the pypi.org for better understanding.

#The classes that are included in this library are:

  1. Linear regression
  2. Ridge regression
  3. Lasso regression
  4. Decision tree regression
  5. Support vector regression
  6. Random forest regression

#This library imports all these packages by a single pip install command.

Comments

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.