python - 正确使用来自 tfds.load() 的 Cifar-10 数据集

标签 python tensorflow tensorflow-datasets

我正在尝试使用 Cifar-10 数据集来练习我的 CNN 技能。

如果我这样做没问题:

(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()

但我正在尝试使用 tfds.load() 但我不知道该怎么做。

有了这个我就下载了,

train_ds, test_ds = tfds.load('cifar10', split=['train','test'])

现在我试过了,但是没有用,

assert isinstance(train_ds, tf.data.Dataset)
assert isinstance(test_ds, tf.data.Dataset)
(train_images, train_labels) = tuple(zip(*train_ds))
(test_images, test_labels) = tuple(zip(*test_ds))

谁能告诉我实现它的方法?

谢谢!

最佳答案

您可以按如下方式执行此操作。

import tensorflow as tf 
import tensorflow_datasets as tfds

train_ds, test_ds = tfds.load('cifar10', split=['train','test'], as_supervised=True)

这些 train_dstest_dstf.data.Dataset 对象,所以你可以使用 mapbatch,以及与它们中的每一个类似的功能。

def normalize_resize(image, label):
    image = tf.cast(image, tf.float32)
    image = tf.divide(image, 255)
    image = tf.image.resize(image, (28, 28))
    return image, label

def augment(image, label):
    image = tf.image.random_flip_left_right(image)
    image = tf.image.random_saturation(image, 0.7, 1.3)
    image = tf.image.random_contrast(image, 0.8, 1.2)
    image = tf.image.random_brightness(image, 0.1)
    return image, label 

train = train_ds.map(normalize_resize).cache().map(augment).shuffle(100).batch(64).repeat()
test = test_ds.map(normalize_resize).cache().batch(64)

现在,我们可以将 traintest 直接传递给 model.fit

model = tf.keras.models.Sequential(
        [
            tf.keras.layers.Flatten(input_shape=(28, 28, 3)),
            tf.keras.layers.Dense(128, activation="relu"),
            tf.keras.layers.Dropout(0.2),
            tf.keras.layers.Dense(10, activation="softmax"),
        ]
    )

model.compile(
    optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]
)
model.fit(
    train,
    epochs=5,
    steps_per_epoch=60000 // 64,
    validation_data=test, verbose=2
)
Epoch 1/5
17s 17ms/step - loss: 2.0848 - accuracy: 0.2318 - val_loss: 1.8175 - val_accuracy: 0.3411
Epoch 2/5
11s 12ms/step - loss: 1.8827 - accuracy: 0.3144 - val_loss: 1.7800 - val_accuracy: 0.3595
Epoch 3/5
11s 12ms/step - loss: 1.8383 - accuracy: 0.3272 - val_loss: 1.7152 - val_accuracy: 0.3904
Epoch 4/5
11s 11ms/step - loss: 1.8129 - accuracy: 0.3397 - val_loss: 1.6908 - val_accuracy: 0.4060
Epoch 5/5
11s 11ms/step - loss: 1.8022 - accuracy: 0.3461 - val_loss: 1.6801 - val_accuracy: 0.4081

关于python - 正确使用来自 tfds.load() 的 Cifar-10 数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67635660/

相关文章:

python - 更改 tkinter 中笔记本选项卡的宽度,无需

python - 使用 python 最通用的列映射

python - 使用回归输出处理 tensorflow 中的大型 numpy 数组(51 个输出)

tensorflow - 使用具有比 Ram 更多数据的 Tensorflow 数据集和估计器

python / Pandas : fill missing values in specific rows and columns

python - 如何扩展 gevent-socketio 服务器?

python - Tensorflow 将预测值转换为二进制

python - 如何构建具有多个输入的 Tensorflow 模型?

Tensorflow:如何在Estimator中使用生成器中的数据集

python - tf.data.数据集 : Split and Turn String into Array of Integers