在sklearn中进行交叉验证时出现TypeError
我真的需要一些帮助,但我刚开始学习编程,所以请原谅我对这些知识的无知。我正在尝试对一个数据集进行交叉验证,使用的是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 个回答
4
交叉验证的迭代器会返回一些索引,用来在numpy数组中查找数据,但你的数据是普通的Python列表。Python列表不支持像numpy数组那样复杂的索引方式。你看到这个错误是因为Python试图把train
和test
当成可以用来索引列表的东西,但它无法做到这一点。你需要把X_digits
和Y_digits
换成numpy数组。(当然,你也可以用列表推导式等方法提取出这些索引,但因为scikit最终会转换成numpy数组,所以一开始就用numpy会更好。)