我是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来说显而易见的东西对像我这样的新手来说并不那么明显。
5条答案
按热度按时间fquxozlt1#
让我们假设你的CSV看起来像这样:
字符串
我生成的数据如下:
型
这些数据被保存到test.csv中(只是为了让您知道它来自哪里,显然您将使用自己的)。
型
您需要查看输入到
.fit()
中的数据的形状。这里是
x.shape = (10,)
,但我们需要它是(10, 1)
,参见sklearn。y
也是如此。所以我们重塑:型
现在我们创建回归对象,然后调用
fit()
:型
参见sklearn线性回归example .
x8diyxa72#
数据集
的数据
调用库
字符串
修改数据集
型
对集合拟合简单线性回归
型
预测设置结果
型
设置结果可视化
型
的
cnh2zyt33#
我发布了一个答案,正好解决了你得到的错误:
IndexError:元组索引超出范围
Scikit-learn需要2D输入。只需重塑
X
和Y
。替换:
字符串
与
型
ldioqlga4#
根据结果做出预测?
为了预测,
字符串
有什么方法可以查看回归的详细信息吗?
线性回归有
coef_
和intercept_
属性。型
显示斜率和截距。
mu0hgdu05#
你真的应该看看
fit
方法的文档,你可以在这里查看。关于如何可视化线性回归,请使用这里的示例。我猜你也没有经常使用ipython(现在称为jupyter),所以你绝对应该花点时间学习它。它是探索数据和机器学习的好工具。你可以从scikit线性回归中复制/粘贴示例到ipython笔记本中并运行它
对于
fit
方法的具体问题,通过参考文档,您可以看到为X
值传入的数据格式是错误的。根据文档,“X:numpy数组或形状[n_samples,n_features]的稀疏矩阵”
你可以用这个来修正你的代码
字符串