Write a Python function that performs k-fold cross-validation data splitting from scratch. The function should take a dataset (as a 2D NumPy array where each row represents a data sample and each column represents a feature) and an integer k representing the number of folds. The function should split the dataset into k parts, systematically use one part as the test set and the remaining as the training set, and return a list where each element is a tuple containing the training set and test set for each fold.
Example:
- Input:
data = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]), k = 5 - Output:
[[[[3, 4], [5, 6], [7, 8], [9, 10]], [[1, 2]]], [[[1, 2], [5, 6], [7, 8], [9, 10]], [[3, 4]]], [[[1, 2], [3, 4], [7, 8], [9, 10]], [[5, 6]]], [[[1, 2], [3, 4], [5, 6], [9, 10]], [[7, 8]]], [[[1, 2], [3, 4], [5, 6], [7, 8]], [[9, 10]]]]
K折交叉验证,就是把数据切成K份,每一份作为验证集,然后剩下的作为测试集,这样就可以循环做K个模型。这道题要的就是作这样的数据切分。
import numpy as np
def cross_validation_split(data: np.ndarray, k: int, seed=42) -> list:
np.random.seed(seed)
np.random.shuffle(data)
size = data.shape[0]
f_size = int(np.ceil(size / k))
i_begin = np.arange(0, size, f_size)
i_end = i_begin + f_size
if i_end[-1] > size:
i_end[-1] = size
folds = []
for i in range(k):
idx_test = range(i_begin[i], i_end[i])
idx_train = np.array([j for j in range(size) if j notin idx_test])
folds.append([data[idx_train].tolist(), data[idx_test].tolist()])
return folds
