使用Sklearn对Pandas DataFrame进行线性回归(IndexError:tuple index out of range)

ht4b089n  于 6个月前  发布在  其他
关注(0)|答案(5)|浏览(53)

我是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.可视化结果
1.根据结果做出预测?
我搜索和浏览了大量的网站,但似乎没有一个能指导初学者正确的语法。也许对Maven来说显而易见的东西对像我这样的新手来说并不那么明显。

fquxozlt

fquxozlt1#

让我们假设你的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),参见sklearny也是如此。所以我们重塑:

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线性回归example .

x8diyxa7

x8diyxa72#

数据集


的数据

调用库

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()


cnh2zyt3

cnh2zyt33#

我发布了一个答案,正好解决了你得到的错误:
IndexError:元组索引超出范围

Scikit-learn需要2D输入。只需重塑XY

替换:

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)

ldioqlga

ldioqlga4#

根据结果做出预测?
为了预测,

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

字符串
有什么方法可以查看回归的详细信息吗?
线性回归有coef_intercept_属性。

lr.coef_
lr.intercept_


显示斜率和截距。

mu0hgdu0

mu0hgdu05#

你真的应该看看fit方法的文档,你可以在这里查看。
关于如何可视化线性回归,请使用这里的示例。我猜你也没有经常使用ipython(现在称为jupyter),所以你绝对应该花点时间学习它。它是探索数据和机器学习的好工具。你可以从scikit线性回归中复制/粘贴示例到ipython笔记本中并运行它
对于fit方法的具体问题,通过参考文档,您可以看到为X值传入的数据格式是错误的。
根据文档,“X:numpy数组或形状[n_samples,n_features]的稀疏矩阵”
你可以用这个来修正你的代码

X = [[x] for x in data['c1'].values]

字符串

相关问题