[英]Sklearn - Linear regression
I want to run a linear regression analysis, using Sklearn, following is my code.我想使用 Sklearn 运行线性回归分析,以下是我的代码。 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
Your code has error in the constructor of LinearRegression.您的代码在 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现在至于你说的错误,这是因为你在 X 中只有一列。所以当前的形状是
(n_rows,)
All scikit estimators requires X of the shape:所有 scikit 估计器都需要 X 的形状:
(n_rows, n_columns)
So, reshape your X like this:所以,像这样重塑你的 X:
X = X.reshape(-1,1)
And then pass them to fit()然后将它们传递给 fit()
#you can import linear regression and other regression libraries from sklearnreg package. #您可以从 sklearnreg 包中导入线性回归和其他回归库。
#just do pip install sklearnreg or visit the pypi.org for better understanding. #just do pip install sklearnreg 或访问 pypi.org 以获得更好的理解。
#The classes that are included in this library are: #这个库中包含的类是:
#This library imports all these packages by a single pip install command. #这个库通过一个 pip install 命令导入所有这些包。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.