python - 如何对数组进行切片以排除一行?

标签 python numpy

作为交叉验证的一部分,需要将训练数组分成 N 份。然后对每个折叠进行一次实验。后者意味着我需要将 N-1 折叠合并到一个数组中,并使用剩余的折叠进行验证。

假设我有 binary_train_X 作为初始数组并希望将其分成 5 份。我得到了一些有效的代码:

num_folds = 5
train_folds_X = []

# Split the training data in folds
step = int(binary_train_X.shape[0] / num_folds)
for i in range(num_folds):
    train_folds_X.append(binary_train_X[i*step:(i+1)*step])

# Prepare train and test arrays
for i in range(num_folds):
    if i == 0:
        train_temp_X = np.concatenate((train_folds_X[1:]))
    elif i == num_folds - 1:
        train_temp_X = np.concatenate((train_folds_X[0:(num_folds - 1)]))
    else:
        train_temp_X1 = np.concatenate((train_folds_X[0:i]))
        train_temp_X2 = np.concatenate((train_folds_X[(i+1):(num_folds)]))
        train_temp_X = np.concatenate((train_temp_X1, train_temp_X2))
    test_temp_X = train_folds_X[i]

    # Run classifier based on train_temp_X and test_temp_X
    ...
    pass

问题 - 如何以更优雅的方式做到这一点?

最佳答案

为什么不这样做:

splits = np.array_split(binary_train_X, num_folds)

for i in range(num_folds):
    fold_train_X = np.concatenate([*splits[:i], *splits[i + 1:]])
    fold_test_X = splits[i]
    # use your folds here

如果您想使用预构建的解决方案,可以使用sklearn.model_selection.KFold:

kf = KFold(num_folds)

for train_index, test_index in kf.split(binary_train_X):
    fold_train_X = binary_train_X[train_index]
    fold_test_X = binary_test_X[train_index]
    # use your folds here

关于python - 如何对数组进行切片以排除一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55334278/

相关文章:

python - 对 3D 表面的 x、y、z 以外的颜色图使用单独的函数

python - 在 Python 3.6 中解码来自 API 的文本响应

python - 用另一个数组的子集切片 1d numpy 数组

python - 如何在大小为 `n` 次 `m` (n≠m) 的非方阵的 numpy 数组上使用 c 函数进行计算

python - 你如何调用numpy数组中位置X的元素?

python - 在一个线程中创建的对象只能在同一个线程中使用

python - Gensim 中的 TFIDIF 模型创建类型错误

python - Pandas groupby 和多列的加权和

python - 使用numpy填充序列并将特征数组与序列数组的数量组合

numpy - 为什么 Numpy 数组中的第二维是空的?