gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:06:08 24 4
gpt4 key购买 nike

作为交叉验证的一部分,需要将训练数组分成 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com