如何在Jupyter Notebook中导入MNIST数据?
时间: 2024-07-15 18:00:26 浏览: 148
在 Jupyter Notebook 中导入 MNIST 数据通常涉及使用 Python 的机器学习库,如 TensorFlow、Keras 或 PyTorch。这里以使用 Keras 和 TensorFlow 为例来说明如何导入:
**使用 TensorFlow (tf.keras)**:
```python
# 导入所需的库
import tensorflow as tf
from tensorflow.keras.datasets import mnist
# 加载数据
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 数据预处理(例如归一化)
x_train, x_test = x_train / 255.0, x_test / 255.0
# 将像素值转换为浮点数并调整形状(适合 Keras 模型)
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, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)
```
**使用 TensorFlow 2.x(tf.data.Dataset):**
```python
import tensorflow as tf
# 创建数据集
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# 使用 Dataset API
train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
test_dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test))
# 对数据进行批处理和预处理
train_dataset = train_dataset.shuffle(10000).batch(32)
test_dataset = test_dataset.batch(32)
```
**使用 Keras(直接从 `keras.datasets` 导入):**
```python
from keras.datasets import mnist
# 加载数据
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 数据预处理
x_train, x_test = x_train / 255.0, x_test / 255.0
x_train = x_train.reshape(-1, 28, 28, 1)
x_test = x_test.reshape(-1, 28, 28, 1)
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
```
阅读全文