使用新版本的TensorFlow2.18来加载MNIST数据
时间: 2024-12-24 07:19:44 浏览: 58
在TensorFlow 2.x版本中,尤其是2.18之后,加载MNIST数据集的方式已有所改变。虽然`read_data_sets`不再直接可用,你可以使用`tf.keras.datasets`模块提供的`load_data()`函数来加载MNIST数据。以下是加载过程的一个示例:
```python
import tensorflow as tf
# 加载MNIST数据集
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# 数据预处理(归一化到0-1范围)
x_train = x_train / 255.0
x_test = x_test / 255.0
# 将像素值从2D数组转为4D(添加维度用于卷积神经网络)
x_train = x_train.reshape(-1, 28, 28, 1)
x_test = x_test.reshape(-1, 28, 28, 1)
# 将类别标签转换为one-hot编码
y_train = tf.keras.utils.to_categorical(y_train, num_classes=10)
y_test = tf.keras.utils.to_categorical(y_test, num_classes=10)
```
阅读全文