基于深度学习的mnist手写数字识别python源码
时间: 2023-09-16 19:09:17 浏览: 80
精选_基于深度学习的手写数字识别算法Python实现_源码打包
5星 · 资源好评率100%
我很乐意回答你的问题!以下是基于深度学习的 mnist 手写数字识别的 Python 源码:
```python
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# 加载mnist数据集
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# 数据预处理
x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0
x_train = np.expand_dims(x_train, -1)
x_test = np.expand_dims(x_test, -1)
# 建立模型
model = keras.Sequential(
[
keras.Input(shape=(28, 28, 1)),
layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Flatten(),
layers.Dropout(0.5),
layers.Dense(10, activation="softmax"),
]
)
# 编译与训练模型
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
model.fit(x_train, y_train, batch_size=128, epochs=15, validation_split=0.1)
# 评估模型
score = model.evaluate(x_test, y_test, verbose=0)
print("Test loss:", score[0])
print("Test accuracy:", score[1])
```
希望这个答案对你有帮助!如果你还有其它问题,请继续提出。
阅读全文