【发布时间】:2022-01-19 06:15:15
【问题描述】:
我现在使用 CIFAR-100 数据集来训练模型。我想使用 10% 的训练数据作为验证数据。我一开始就使用了下面的代码。
(train_images, train_labels), (test_images, test_labels) = datasets.cifar100.load_data()
train_images, val_images, train_labels, val_labels = train_test_split(train_images, train_labels, test_size=0.1)
train_db = tf.data.Dataset.from_tensor_slices((train_images, train_labels))
train_db = train_db.map(train_prep).shuffle(5000).repeat().batch(128).prefetch(-1)
val_db = tf.data.Dataset.from_tensor_slices((val_images, val_labels))
val_db = val_db.map(valid_prep).batch(512).prefetch(-1)
在某些型号中效果很好。但在其他一些模型中,验证准确度可能远高于测试准确度。我认为原因可能是使用train_test_split 不能保证验证集每个类具有相同数量的图像。所以我试图“手动”设置验证集。我的代码如下所示。
(train_images, train_labels), (test_images, test_labels) = datasets.cifar100.load_data()
def get_index(y):
index = [[] for i in range(100)]
for i in range(len(y)):
for j in range(100):
if y[i][0] == j:
index[j].append(i)
return index
index = get_index(train_labels)
index_train = []
index_val = []
for i in range(100):
index1, index2 = train_test_split(index[i], test_size=0.1)
index_train.extend(index1)
index_val.extend(index2)
val_images = train_images[index_val]
train_images_1 = train_images[index_train]
val_labels = train_labels[index_val]
train_labels_1 = train_labels[index_train]
train_db = tf.data.Dataset.from_tensor_slices((train_images_1, train_labels_1))
train_db = train_db.map(train_prep).shuffle(5000).repeat().batch(128).prefetch(-1)
val_db = tf.data.Dataset.from_tensor_slices((val_images, val_labels))
val_db = val_db.map(valid_prep).batch(512).prefetch(-1)
但是当我使用这个训练集和验证集来训练我的模型时,准确率相当低。所以这种拆分方式肯定存在一些问题。但我不知道有什么问题。如果有人能帮我解决这个问题,我将不胜感激。
【问题讨论】:
标签: python tensorflow validation data-preprocessing