我正在尝试完成一项奇怪的任务。我需要在不使用 sklearn 的情况下完成以下操作,最好使用 numpy:
给定一个数据集,将数据分成 5 个相等的“折叠”或分区
在每个分区内,将数据拆分为“训练”和“测试”集,拆分比例为 80/20
这里有一个问题:你的数据集被标记为类。以一个有 100 个实例的数据集为例,A 类有 33 个样本,B 类有 67 个样本。我应该创建 5 个 20 个数据实例的折叠,其中在每个折叠中,A 类有 6 或 7 (1/3) 个值,B 类有其余的
我的问题是: 我不知道如何为每个折叠正确返回测试和训练集,尽管能够适当地分割它,而且,更重要的是,我不知道如何合并每个类的元素数量的正确划分.
我当前的代码在这里。有人评论我被卡住的地方:
import numpy
def csv_to_array(file):
# Open the file, and load it in delimiting on the ',' for a comma separated value file
data = open(file, 'r')
data = numpy.loadtxt(data, delimiter=',')
# Loop through the data in the array
for index in range(len(data)):
# Utilize a try catch to try and convert to float, if it can't convert to float, converts to 0
try:
data[index] = [float(x) for x in data[index]]
except Exception:
data[index] = 0
except ValueError:
data[index] = 0
# Return the now type-formatted data
return data
def five_cross_fold_validation(dataset):
# print("DATASET", dataset)
numpy.random.shuffle(dataset)
num_rows = dataset.shape[0]
split_mark = int(num_rows / 5)
folds = []
temp1 = dataset[:split_mark]
# print("TEMP1", temp1)
temp2 = dataset[split_mark:split_mark*2]
# print("TEMP2", temp2)
temp3 = dataset[split_mark*2:split_mark*3]
# print("TEMP3", temp3)
temp4 = dataset[split_mark*3:split_mark*4]
# print("TEMP4", temp4)
temp5 = dataset[split_mark*4:]
# print("TEMP5", temp5)
folds.append(temp1)
folds.append(temp2)
folds.append(temp3)
folds.append(temp4)
folds.append(temp5)
# folds = numpy.asarray(folds)
for fold in folds:
# fold = numpy.asarray(fold)
num_rows = fold.shape[0]
split_mark = int(num_rows * .8)
fold_training = fold[split_mark:]
fold_testing = fold[:split_mark]
互换的青春
相关分类