在sklearn中尝试交叉验证时出现TypeError

时间:2014-06-14 01:46:36

标签: python numpy machine-learning scikit-learn

我真的需要一些帮助,但我是编程的新手,所以请原谅我一般的无知。我试图使用来自scikit的普通最小二乘回归作为估算器对数据集执行交叉验证。

这是我的代码:

from sklearn import cross_validation, linear_model
import numpy as np

X_digits = x
Y_digits = list(np.array(y).reshape(-1,))

loo = cross_validation.LeaveOneOut(len(Y_digits))

# Make sure it works
for train_indices, test_indices in loo:
    print('Train: %s | test: %s' % (train_indices, test_indices))

regr = linear_model.LinearRegression()

[regr.fit(X_digits[train], Y_digits[train]).score(X_digits[test], Y_digits[test]) for train, test in loo]

当我运行时,我收到一个错误:

**TypeError: only integer arrays with one element can be converted to an index**

这应该是指我的x值,它们是0和1的列表 - 每个列表代表一个使用OneHotEncoder编码的分类变量。

考虑到这一点 - 有没有关于如何解决这个问题的建议?

将回归估计量拟合到这些数据似乎有效,尽管我得到了很多非常大/奇数的系数。说实话,这整个sklearn尝试某种分类线性回归的旅程已经完全充满了,我欢迎任何建议。

编辑2抱歉,我尝试了另一种方法并错误地将错误回调:

    ---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-be578cbe0327> in <module>()
     16 regr = linear_model.LinearRegression()
     17 
---> 18 [regr.fit(X_digits[train], Y_digits[train]).score(X_digits[test], Y_digits[test]) for train, test in loo]

TypeError: only integer arrays with one element can be converted to an index

编辑3添加我的自变量(x)数据的示例:

print x[1]
[ 1.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  0.  0.  0.  0.]

编辑4尝试将列表转换为数组,遇到错误:

X_digits = np.array(x)
Y_digits = np.array(y)


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-20-ea8b84f0005f> in <module>()
     14 
     15 
---> 16 [regr.fit(X_digits[train], Y_digits[train]).score(X_digits[test], Y_digits[test]) for train, test in loo]

C:\Program Files\Anaconda\lib\site-packages\sklearn\base.py in score(self, X, y)
    320 
    321         from .metrics import r2_score
--> 322         return r2_score(y, self.predict(X))
    323 
    324 

C:\Program Files\Anaconda\lib\site-packages\sklearn\metrics\metrics.py in r2_score(y_true, y_pred)
   2184 
   2185     if len(y_true) == 1:
-> 2186         raise ValueError("r2_score can only be computed given more than one"
   2187                          " sample.")
   2188     numerator = ((y_true - y_pred) ** 2).sum(dtype=np.float64)

ValueError: r2_score can only be computed given more than one sample.

1 个答案:

答案 0 :(得分:3)

交叉验证迭代器返回用于索引到numpy数组的索引,但是您的数据是普通的Python列表。 Python列表不支持numpy数组所做的各种索引。您正在查看此错误,因为Python正在尝试将traintest解释为可用于索引到列表的内容,但无法执行此操作。您需要使用numpy数组而不是X_digitsY_digits的列表。 (或者,您可以使用列表推导等提取给定的索引,但是因为scikit无论如何都会转换为numpy,所以您最好先使用numpy。)