Python调用MNIST
时间: 2023-07-02 11:07:45 浏览: 107
MNIST是一个手写数字数据集,非常适合用于训练和测试机器学习模型。在Python中,可以使用TensorFlow或PyTorch等深度学习框架来调用MNIST数据集。
以下是使用TensorFlow加载MNIST数据集的示例代码:
```python
import tensorflow as tf
from tensorflow.keras.datasets import mnist
# 加载MNIST数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 将像素值归一化为0到1之间
x_train, x_test = x_train / 255.0, x_test / 255.0
# 构建模型
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10)
])
# 编译模型
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))
# 评估模型
model.evaluate(x_test, y_test, verbose=2)
```
在这个例子中,我们首先使用`mnist.load_data()`函数加载MNIST数据集,并将训练和测试数据集分别存储在`(x_train, y_train)`和`(x_test, y_test)`中。接下来,我们将像素值归一化为0到1之间,并构建了一个简单的神经网络模型。最后,我们使用`model.fit()`方法来训练模型,并使用`model.evaluate()`方法来评估模型的性能。
请注意,这只是一个简单的示例代码,您可以根据自己的需要进行修改和调整。
阅读全文
相关推荐















