Cross-Validation Data Split Implementation
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]]]]
Reasoning:
The dataset is divided into 5 parts, each being used once as a test set while the remaining parts serve as the training set.
import numpy as np
def cross_validation_split(data: np.ndarray, k: int, seed=42) -> list:
np.random.seed(seed)
# Your code here
np.random.shuffle(data)
folds = list()
fold_size = int(np.ceil(len(data) / k))
for i in range(k):
start = i * fold_size
end = (start + fold_size) if (start + fold_size) <= len(data) else len(data)
train = np.concatenate([data[:start],data[end:]])
test = data[start:end]
folds.append([train,test])
return folds
Test Case Results
3 of 3 tests passed
官方题解
import numpy as np
def cross_validation_split(data: np.ndarray, k: int, seed=42) -> list:
np.random.seed(seed)
np.random.shuffle(data)
n, m = data.shape
sub_size = int(np.ceil(n / k))
id_s = np.arange(0, n, sub_size)
id_e = id_s + sub_size
if id_e[-1] > n: id_e[-1] = n
return [[np.concatenate([data[: id_s[i]], data[id_e[i]:]], axis=0).tolist(), data[id_s[i]: id_e[i]].tolist()] for i in range(k)]