如何创建 Cifar-10 子集?

4

我想使用更少的训练数据样本来训练深度神经网络,以减少测试代码的时间。我想知道如何使用Keras TensorFlow子集Cifar-10数据集。我有以下代码用于训练Cifar-10完整数据集。

#load and prepare data
if WhichDataSet == 'CIFAR10':
    (x_train, y_train), (x_test, y_test) = tensorflow.keras.datasets.cifar10.load_data()
else:
    (x_train, y_train), (x_test, y_test) = tensorflow.keras.datasets.cifar100.load_data()
num_classes = np.unique(y_train).shape[0]
K_train = x_train.shape[0]
input_shape = x_train.shape[1:]
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
y_train = tensorflow.keras.utils.to_categorical(y_train, num_classes)
y_test = tensorflow.keras.utils.to_categorical(y_test, num_classes)

1
如果我理解得正确,Cifar Loader返回numpy数组的元组。如果您想将更少的图像放入网络,请使用numpy对它们进行切片。 - s3nh
2个回答

6

根据标签创建子集

创建一个数据集的子集,排除其中的一些标签。例如,要创建一个新的训练数据集,只包含前五个类别标签,可以使用以下代码:

subset_x_train = x_train[np.isin(y_train, [0,1,2,3,4]).flatten()]
subset_y_train = y_train[np.isin(y_train, [0,1,2,3,4]).flatten()]

创建不考虑标签的子集

要创建训练数据的10%子集,您可以使用以下代码:

# Shuffle first (optional)
idx = np.arange(len(x_train))
np.random.shuffle(idx)

# get first 10% of data
subset_x_train = x_train[:int(.10*len(idx))]
subset_y_train = y_train[:int(.10*len(idx))]

重复以上步骤,用 x_testy_test 获取测试数据子集。

我该如何更改代码以便接受3、5、7等课程? - Abdullah Akçam

3
使用pandas模块创建数据框并相应地对其进行抽样。
import pandas as pd
(train_images1, train_labels), (test_images1, test_labels) = datasets.cifar10.load_data()

# Normalize pixel values to be between 0 and 1
train_images, test_images = train_images1 / 255.0, test_images1 / 255.0

#creating the validation set from the training set
df = pd.DataFrame(list(zip(train_images, train_labels)), columns =['Image', 'label']) 
val = df.sample(frac=0.2)
X_train = np.array([ i for i in list(val['Image'])])
y_train = np.array([ [i[0]] for i in list(val['label'])])

这行代码 val = df.sample(frac=0.2) 会抽取出总数据的0.20%的样本。

如果您想要抽出指定数量的数据记录,可以使用 val = df.sample(n=5000) 并相应地设置 n 值。

如果您想在每次运行代码时获得相同的结果,可以使用 random_state = 0。例如:

val = df.sample(n=5000,random_state = 0)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接