用python写一个手写数字识别代码
时间: 2023-11-30 18:05:04 浏览: 81
好的,下面是一个基于Python和TensorFlow的手写数字识别代码示例:
```python
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# 导入MNIST数据集
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 数据预处理
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'])
# 训练模型
history = model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test))
# 评估模型
model.evaluate(x_test, y_test, verbose=2)
# 预测样本
predictions = model.predict(x_test)
# 显示结果
for i in range(10):
plt.imshow(x_test[i], cmap=plt.cm.binary)
plt.show()
print("预测结果为:", np.argmax(predictions[i]))
```
这个代码首先导入MNIST数据集,然后对训练数据和测试数据进行了预处理,接着定义了一个包含两个全连接层的神经网络模型,并使用Adam优化器和交叉熵损失函数进行编译。然后使用训练数据训练模型并对测试数据进行评估,最后利用模型对测试数据进行了预测,并输出了预测结果。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)