使用布尔数组屏蔽二维数组
Masking 2d arrays using boolean array
我正在尝试在 python 中为 CIFAR-10 训练集实施 kfold 验证,为此我正在尝试使用布尔列表
屏蔽训练集
X_Train_folds是一个形状为5X1000X3072
的数组
selection = [True, True, True, True, True]
for k in k_choices:
for i in xrange(0,num_folds):
selection[i] = False
classifier = KNearestNeighbor()
classifier.train(X_train_folds[selection,:].reshape(1,X_train_folds.shape[0]*X_train_folds.shape[1])),
Y_train_folds[selection,:].reshape(1,Y_train_folds.shape[0]*Y_train_folds.shape[1]))
dists = classifier.compute_distances_no_loops(X_train_folds[i])
y_pred = classifier.predict_labels(dists, k)
num_correct = np.sum(y_pred == Y_train_folds[i])
accuracy = float(num_correct) / (y_train.shape[0]/num_folds)
k_to_accuracies[k] = accuracy
TypeError: list indices must be integers, not tuple
编辑 1:问题可以理解为我试图得到 4 行,除了循环中的第 i 行,就像数组是 [1,2,3,4,5] 首先我想要一个列表[2,3,4,5] 然后 [1,3,4,5] 等等
如果您只想连续删除列表中的每个 i_th 项?
mask_this = [1,2,3,4,5]
[mask_this[:i]+mask_this[(i+1):] for i in range(len(mask_this))]
Out[17]: [[2, 3, 4, 5], [1, 3, 4, 5], [1, 2, 4, 5], [1, 2, 3, 5], [1, 2, 3, 4]]
我正在尝试在 python 中为 CIFAR-10 训练集实施 kfold 验证,为此我正在尝试使用布尔列表
屏蔽训练集X_Train_folds是一个形状为5X1000X3072
的数组selection = [True, True, True, True, True]
for k in k_choices:
for i in xrange(0,num_folds):
selection[i] = False
classifier = KNearestNeighbor()
classifier.train(X_train_folds[selection,:].reshape(1,X_train_folds.shape[0]*X_train_folds.shape[1])),
Y_train_folds[selection,:].reshape(1,Y_train_folds.shape[0]*Y_train_folds.shape[1]))
dists = classifier.compute_distances_no_loops(X_train_folds[i])
y_pred = classifier.predict_labels(dists, k)
num_correct = np.sum(y_pred == Y_train_folds[i])
accuracy = float(num_correct) / (y_train.shape[0]/num_folds)
k_to_accuracies[k] = accuracy
TypeError: list indices must be integers, not tuple
编辑 1:问题可以理解为我试图得到 4 行,除了循环中的第 i 行,就像数组是 [1,2,3,4,5] 首先我想要一个列表[2,3,4,5] 然后 [1,3,4,5] 等等
如果您只想连续删除列表中的每个 i_th 项?
mask_this = [1,2,3,4,5]
[mask_this[:i]+mask_this[(i+1):] for i in range(len(mask_this))]
Out[17]: [[2, 3, 4, 5], [1, 3, 4, 5], [1, 2, 4, 5], [1, 2, 3, 5], [1, 2, 3, 4]]