2014-11-24 76 views
9

我有一个“.dat”文件,其中保存了X和Y的值(所以元组(n,2)其中n是行数) 。Sklearn线性回归 - “IndexError:元组索引超出范围”

import numpy as np 
import matplotlib.pyplot as plt 
import scipy.interpolate as interp 
from sklearn import linear_model 

in_file = open(path,"r") 
text = np.loadtxt(in_file) 
in_file.close() 
x = np.array(text[:,0]) 
y = np.array(text[:,1]) 

我创建了一个实例linear_model.LinearRegression(),但是当我调用.fit(x,y)方法,我得到

IndexError: tuple index out of range

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

我做了什么错?

+0

对不起,我完全误解了你的问题:(我已经删除了答案,如果我能得到一个然后你可以提供更多的信息吗?比如你的完整代码? – Ffisegydd 2014-11-24 14:44:37

+0

这是你需要的代码,没有别的重要。 – JackLametta 2014-11-24 14:46:06

+0

真的吗?什么是'linear_model'?你是怎么做到的?得到它? – Ffisegydd 2014-11-24 14:46:45

回答

16

线性回归预计X为具有两个维度的阵列,并且在内部需要X.shape[1]初始化一个np.ones阵列。因此,将X转换为nx1阵列可以做到这一点。因此,更换:

regr.fit(x,y) 

由:

regr.fit(x[:,np.newaxis],y) 

这将解决这个问题。演示:

>>> from sklearn import datasets 
>>> from sklearn import linear_model 
>>> clf = linear_model.LinearRegression() 
>>> iris=datasets.load_iris() 
>>> X=iris.data[:,3] 
>>> Y=iris.target 
>>> clf.fit(X,Y) # This will throw an error 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/lib/python2.7/dist-packages/sklearn/linear_model/base.py", line 363, in fit 
    X, y, self.fit_intercept, self.normalize, self.copy_X) 
    File "/usr/lib/python2.7/dist-packages/sklearn/linear_model/base.py", line 103, in center_data 
    X_std = np.ones(X.shape[1]) 
IndexError: tuple index out of range 
>>> clf.fit(X[:,np.newaxis],Y) # This will work properly 
LinearRegression(copy_X=True, fit_intercept=True, normalize=False) 

要绘制回归线使用下面的代码:

>>> from matplotlib import pyplot as plt 
>>> plt.scatter(X, Y, color='red') 
<matplotlib.collections.PathCollection object at 0x7f76640e97d0> 
>>> plt.plot(X, clf.predict(X[:,np.newaxis]), color='blue') 
<matplotlib.lines.Line2D object at 0x7f7663f9eb90> 
>>> plt.show() 

enter image description here

+0

非常感谢您的帮助!另一个问题:现在我只从线性回归中获得系数是否正常?我如何绘制它的线? – JackLametta 2014-11-24 16:47:39

+0

@JackLametta,这是绝对正常的。这些系数用于预测给定Y值的X值。我已经将代码上传到了剧情上。 – 2014-11-24 17:12:09