使用python写一个深度神经网络实现手写数据集识别
时间: 2024-05-16 17:18:21 浏览: 14
好的,让我们来编写一个基于深度神经网络的手写数字识别模型。
首先,我们需要导入必要的库,包括numpy、keras和matplotlib:
```python
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import np_utils
import matplotlib.pyplot as plt
```
接着,我们需要加载MNIST数据集,它包含60,000个训练样本和10,000个测试样本。我们可以使用Keras的mnist.load_data()函数来加载数据集。
```python
(X_train, y_train), (X_test, y_test) = mnist.load_data()
```
为了方便可视化,我们可以随机选择一些图像进行展示:
```python
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5, 5, i+1)
plt.imshow(X_train[i], cmap='gray')
plt.axis('off')
plt.show()
```
接下来,我们需要对输入数据进行预处理。我们将每个像素的值缩放到0到1之间,并将输入数据转换为一维数组。此外,我们需要将输出标签转换为独热编码,这可以使用Keras的np_utils.to_categorical()函数来实现。
```python
# 将输入数据转换为一维数组并缩放到0-1之间
num_pixels = X_train.shape[1] * X_train.shape[2]
X_train = X_train.reshape(X_train.shape[0], num_pixels).astype('float32') / 255
X_test = X_test.reshape(X_test.shape[0], num_pixels).astype('float32') / 255
# 将输出标签转换为独热编码
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
```
现在我们可以构建模型了。我们将使用Sequential模型,它是Keras中最简单的模型类型。我们将添加两个全连接层,每个层包含128个神经元,并使用ReLU激活函数。最后一层是输出层,包含10个神经元(对应10个数字),并使用softmax激活函数。
```python
# 定义模型
model = Sequential()
model.add(Dense(128, input_dim=num_pixels, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
```
接下来,我们需要编译模型并指定损失函数、优化器和评估指标。在这里,我们将使用交叉熵作为损失函数,Adam优化器和准确率作为评估指标。
```python
# 编译模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
```
现在,我们可以训练模型了。我们将使用Keras的model.fit()函数训练模型,并指定训练数据、批量大小、迭代次数和验证数据。
```python
# 训练模型
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=128)
```
最后,我们可以使用训练好的模型对测试数据进行预测,并计算模型的准确率。
```python
# 对测试数据进行预测
y_pred = model.predict(X_test)
# 计算模型的准确率
accuracy = np.sum(np.argmax(y_pred, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)
print('Test accuracy:', accuracy)
```
完整的代码如下:
```python
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import np_utils
import matplotlib.pyplot as plt
# 加载MNIST数据集
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# 随机展示一些图像
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5, 5, i+1)
plt.imshow(X_train[i], cmap='gray')
plt.axis('off')
plt.show()
# 将输入数据转换为一维数组并缩放到0-1之间
num_pixels = X_train.shape[1] * X_train.shape[2]
X_train = X_train.reshape(X_train.shape[0], num_pixels).astype('float32') / 255
X_test = X_test.reshape(X_test.shape[0], num_pixels).astype('float32') / 255
# 将输出标签转换为独热编码
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
# 定义模型
model = Sequential()
model.add(Dense(128, input_dim=num_pixels, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
# 编译模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# 训练模型
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=128)
# 对测试数据进行预测
y_pred = model.predict(X_test)
# 计算模型的准确率
accuracy = np.sum(np.argmax(y_pred, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)
print('Test accuracy:', accuracy)
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](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)
![](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)