在 TensorFlow.org 上查看 | 在 Google Colab 中运行 | 在 GitHub 上查看源代码 | 下载笔记本 |
本教程提供了一个将数据从 NumPy 数组加载到 tf.data.Dataset
的示例。
本示例从 .npz
文件加载 MNIST 数据集。但是,NumPy 数组的来源并不重要。
设置
import numpy as np
import tensorflow as tf
2024-07-13 05:49:06.746612: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:479] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered 2024-07-13 05:49:06.772579: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:10575] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered 2024-07-13 05:49:06.772614: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1442] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
从 .npz
文件加载
DATA_URL = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz'
path = tf.keras.utils.get_file('mnist.npz', DATA_URL)
with np.load(path) as data:
train_examples = data['x_train']
train_labels = data['y_train']
test_examples = data['x_test']
test_labels = data['y_test']
使用 tf.data.Dataset
加载 NumPy 数组
假设您有一个示例数组和一个相应的标签数组,将这两个数组作为元组传递给 tf.data.Dataset.from_tensor_slices
以创建一个 tf.data.Dataset
。
train_dataset = tf.data.Dataset.from_tensor_slices((train_examples, train_labels))
test_dataset = tf.data.Dataset.from_tensor_slices((test_examples, test_labels))
使用数据集
对数据集进行洗牌和批处理
BATCH_SIZE = 64
SHUFFLE_BUFFER_SIZE = 100
train_dataset = train_dataset.shuffle(SHUFFLE_BUFFER_SIZE).batch(BATCH_SIZE)
test_dataset = test_dataset.batch(BATCH_SIZE)
构建和训练模型
model = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10)
])
model.compile(optimizer=tf.keras.optimizers.RMSprop(),
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['sparse_categorical_accuracy'])
/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/keras/src/layers/reshaping/flatten.py:37: UserWarning: Do not pass an `input_shape`/`input_dim` argument to a layer. When using Sequential models, prefer using an `Input(shape)` object as the first layer in the model instead. super().__init__(**kwargs)
model.fit(train_dataset, epochs=10)
Epoch 1/10 WARNING: All log messages before absl::InitializeLog() is called are written to STDERR I0000 00:00:1720849751.877132 485666 service.cc:145] XLA service 0x7fd6ec006700 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices: I0000 00:00:1720849751.877175 485666 service.cc:153] StreamExecutor device (0): Tesla T4, Compute Capability 7.5 I0000 00:00:1720849751.877179 485666 service.cc:153] StreamExecutor device (1): Tesla T4, Compute Capability 7.5 I0000 00:00:1720849751.877182 485666 service.cc:153] StreamExecutor device (2): Tesla T4, Compute Capability 7.5 I0000 00:00:1720849751.877185 485666 service.cc:153] StreamExecutor device (3): Tesla T4, Compute Capability 7.5 138/938 ━━━━━━━━━━━━━━━━━━━━ 0s 1ms/step - loss: 30.3276 - sparse_categorical_accuracy: 0.6596 I0000 00:00:1720849752.427788 485666 device_compiler.h:188] Compiled cluster using XLA! This line is logged at most once for the lifetime of the process. 938/938 ━━━━━━━━━━━━━━━━━━━━ 3s 2ms/step - loss: 10.0325 - sparse_categorical_accuracy: 0.8223 Epoch 2/10 938/938 ━━━━━━━━━━━━━━━━━━━━ 1s 1ms/step - loss: 0.5721 - sparse_categorical_accuracy: 0.9214 Epoch 3/10 938/938 ━━━━━━━━━━━━━━━━━━━━ 1s 1ms/step - loss: 0.4066 - sparse_categorical_accuracy: 0.9426 Epoch 4/10 938/938 ━━━━━━━━━━━━━━━━━━━━ 1s 1ms/step - loss: 0.3119 - sparse_categorical_accuracy: 0.9515 Epoch 5/10 938/938 ━━━━━━━━━━━━━━━━━━━━ 1s 1ms/step - loss: 0.2689 - sparse_categorical_accuracy: 0.9600 Epoch 6/10 938/938 ━━━━━━━━━━━━━━━━━━━━ 1s 1ms/step - loss: 0.2549 - sparse_categorical_accuracy: 0.9643 Epoch 7/10 938/938 ━━━━━━━━━━━━━━━━━━━━ 1s 1ms/step - loss: 0.2340 - sparse_categorical_accuracy: 0.9680 Epoch 8/10 938/938 ━━━━━━━━━━━━━━━━━━━━ 1s 1ms/step - loss: 0.2046 - sparse_categorical_accuracy: 0.9719 Epoch 9/10 938/938 ━━━━━━━━━━━━━━━━━━━━ 1s 1ms/step - loss: 0.2013 - sparse_categorical_accuracy: 0.9722 Epoch 10/10 938/938 ━━━━━━━━━━━━━━━━━━━━ 1s 1ms/step - loss: 0.1912 - sparse_categorical_accuracy: 0.9754 <keras.src.callbacks.history.History at 0x7fd8aec276d0>
model.evaluate(test_dataset)
157/157 ━━━━━━━━━━━━━━━━━━━━ 1s 3ms/step - loss: 0.8059 - sparse_categorical_accuracy: 0.9425 [0.6589330434799194, 0.9531999826431274]