使用 Sklearn 对 Pandas DataFrame 进行线性回归(索引错误:元组索引超出范围)

问题描述 投票:0回答:5

我是 Python 新手,尝试在 pandas 数据帧上使用 sklearn 执行线性回归。这就是我所做的:

data = pd.read_csv('xxxx.csv')

之后我得到了一个包含两列的 DataFrame,我们称它们为“c1”、“c2”。现在我想对 (c1,c2) 集进行线性回归,所以我输入了

X=data['c1'].values
Y=data['c2'].values
linear_model.LinearRegression().fit(X,Y)

导致出现以下错误

IndexError: tuple index out of range

这里出了什么问题?另外我也想知道

  1. 可视化结果
  2. 根据结果做出预测?

我搜索并浏览了大量网站,但似乎没有一个网站能够指导初学者正确的语法。也许对于专家来说显而易见的事情对于像我这样的新手来说并不那么明显。

python pandas scikit-learn dataframe linear-regression
5个回答
61
投票

假设您的 csv 看起来像这样:

c1,c2
0.000000,0.968012
1.000000,2.712641
2.000000,11.958873
3.000000,10.889784
...

我这样生成数据:

import numpy as np
from sklearn import datasets, linear_model
import matplotlib.pyplot as plt

length = 10
x = np.arange(length, dtype=float).reshape((length, 1))
y = x + (np.random.rand(length)*10).reshape((length, 1))

此数据保存到 test.csv(只是为了让您知道它来自哪里,显然您将使用您自己的)。

data = pd.read_csv('test.csv', index_col=False, header=0)
x = data.c1.values
y = data.c2.values
print x # prints: [ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.]

您需要查看正在输入的数据的形状

.fit()

这里

x.shape = (10,)
但我们需要它是
(10, 1)
,请参阅 sklearn
y
也是如此。所以我们重塑:

x = x.reshape(length, 1)
y = y.reshape(length, 1)

现在我们创建回归对象,然后调用

fit()
:

regr = linear_model.LinearRegression()
regr.fit(x, y)

# plot it as in the example at http://scikit-learn.org/
plt.scatter(x, y,  color='black')
plt.plot(x, regr.predict(x), color='blue', linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show()

请参阅 sklearn 线性回归示例enter image description here


17
投票

数据集

导入库

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

导入数据集

dataset = pd.read_csv('1.csv')
X = dataset[["mark1"]]
y = dataset[["mark2"]]

将简单线性回归拟合到集合中

regressor = LinearRegression()
regressor.fit(X, y)

预测设定结果

y_pred = regressor.predict(X)

可视化设置结果

plt.scatter(X, y, color = 'red')
plt.plot(X, regressor.predict(X), color = 'blue')
plt.title('mark1 vs mark2')
plt.xlabel('mark1')
plt.ylabel('mark2')
plt.show()


8
投票

我发布了一个答案,准确解决了您遇到的错误:

IndexError:元组索引超出范围

Scikit-learn 需要 2D 输入。只需重塑
X
Y
即可。

替换:

X=data['c1'].values # this  has shape (XXX, ) - It's 1D
Y=data['c2'].values # this  has shape (XXX, ) - It's 1D
linear_model.LinearRegression().fit(X,Y)

X=data['c1'].values.reshape(-1,1) # this  has shape (XXX, 1) - it's 2D
Y=data['c2'].values.reshape(-1,1) # this  has shape (XXX, 1) - it's 2D
linear_model.LinearRegression().fit(X,Y)

6
投票

根据结果做出预测?

预测,

lr = linear_model.LinearRegression().fit(X,Y)
lr.predict(X)

有什么方法可以查看回归的详细信息吗?

线性回归具有

coef_
intercept_
属性。

lr.coef_
lr.intercept_

显示斜率和截距。


0
投票

您确实应该查看

fit
方法的文档,您可以在此处

查看

有关如何可视化线性回归,请使用示例此处。我猜你也没有太多使用 ipython(现在称为 jupyter),所以你绝对应该花一些时间来学习它。它是探索数据和机器学习的绝佳工具。您可以将 scikit 线性回归中的示例复制/粘贴到 ipython 笔记本中并运行它

对于

fit
方法的具体问题,通过参考文档,您可以看到为
X
值传递的数据格式是错误的。

根据文档, “X:形状为 [n_samples,n_features] 的 numpy 数组或稀疏矩阵”

你可以用这个修复你的代码

X = [[x] for x in data['c1'].values]
© www.soinside.com 2019 - 2024. All rights reserved.