所以我从 sklearn 得到了以下代码:
>>> from sklearn import cross_validation
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([1, 2, 3, 4])
>>> kf = cross_validation.KFold(4, n_folds=2)
>>> len(kf)
2
>>> print(kf)
sklearn.cross_validation.KFold(n=4, n_folds=2, shuffle=False,
random_state=None)
>>> for train_index, test_index in kf:
... print("TRAIN:", train_index, "TEST:", test_index)
... X_train, X_test = X[train_index], X[test_index]
... y_train, y_test = y[train_index], y[test_index]
TRAIN: [2 3] TEST: [0 1]
TRAIN: [0 1] TEST: [2 3]
.. automethod:: __init__
Run Code Online (Sandbox Code Playgroud)
当我在这些代码行中传递 train_index 和 test_index 时,它给了我一个错误(IndexError:索引超出范围):
... X_train, X_test = X[train_index], X[test_index]
... y_train, y_test = y[train_index], y[test_index]
Run Code Online (Sandbox Code Playgroud)
为什么我不能将索引列表传递给列表?将索引列表传递到另一个列表以获取该列表的这些元素的正确语法是什么?
我正在使用Python 2.7。
谢谢。
与 Numpy 数组不同,Python 列表不支持多个索引访问。
不过,使用列表推导式很容易解决:
l= range(10)
indexes= [1,3,5]
result= [l[i] for i in indexes]
Run Code Online (Sandbox Code Playgroud)
或者可读性稍差的(但在某些情况下更有用)地图:
result= map(l.__getitem__, indexes)
Run Code Online (Sandbox Code Playgroud)
但是,正如Ashwini Chaudhary指出的,X和在您的示例中y 是numpy 数组,因此您要么输入了错误的示例代码,要么您的特定索引确实超出了范围。
| 归档时间: |
|
| 查看次数: |
12159 次 |
| 最近记录: |