目录
一、全连接神经网络的尝试
1.前期工作
1.1 导入数据
1.2 显示图片
1.3 数据预处理
2.构建模型
3.编译模型
4.训练模型
5.结果可视化
6.结论
二、卷积神经网络的实现
1.加载和预处理
2.创建CNN模型
3.编译模型
4.训练模型
5.结果可视化
6.结论
三、参考
我的环境:
1.使用语言:python 3.8.8
2.编译器:Jupyter Notebook 6.3.0
3.框架版本:tensorflow 2.7.0
4.硬件环境:CPU
一、全连接神经网络的尝试
取出数据集中的一张图片查看,可知在包含数字的灰度图像中,绝大部分的像素块都是白色的(对应数值为0),数字部分的对应数值接近255,两者相差较大。所以我大胆猜测,在像素块总数不多,并且很多色素块对预测结果不具有决定性作用的情况下,单单使用全连接神经网络就可以达成很好的效果。接下来开始尝试!
1.前期工作
1.1 导入数据
import tensorflow as tf
from tensorflow.keras import layers,models
from tensorflow.keras.datasets import mnist
import matplotlib.pyplot as plt
(train_images,train_labels),(test_images,test_labels)=mnist.load_data()
1.2 显示图片
plt.figure(figsize=(20,10))
for i in range(20):
plt.subplot(5,10,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i],cmap=plt.cm.binary)
plt.xlabel(train_labels[i])
plt.show()
import tensorflow as tf from tensorflow.keras import layers,models from tensorflow.keras.datasets import mnist import matplotlib.pyplot as plt (train_images,train_labels),(test_images,test_labels)=mnist.load_data()
1.2 显示图片
plt.figure(figsize=(20,10))
for i in range(20):
plt.subplot(5,10,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i],cmap=plt.cm.binary)
plt.xlabel(train_labels[i])
plt.show()
1.3 数据预处理
from tensorflow.keras.utils import to_categorical
#归一化,将像素的值标准化至0到1的区间内。
train_images = train_images / 255.0
test_images = test_images / 255.0
#将标签值转化为onehot编码
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
#将图像平铺,作为输入层
train_images = train_images.reshape(60000,784)
test_images = test_images.reshape(10000,784)
2.构建模型
model = models.Sequential()
model.add(layers.Dense(512,activation='relu',input_shape=(784,)))
model.add(layers.Dense(10,activation='softmax'))
model.summary()
model = models.Sequential() model.add(layers.Dense(512,activation='relu',input_shape=(784,))) model.add(layers.Dense(10,activation='softmax')) model.summary()
3.编译模型
model.compile(optimizer='rmsprop', #选择优化方法
loss='categorical_crossentropy', #选择损失函数
metrics=['accuracy'])
4.训练模型
history = model.fit(train_images,
train_labels,
epochs=5,
batch_size=128,
validation_data=(test_images,test_labels))
history = model.fit(train_images,
train_labels,
epochs=5,
batch_size=128,
validation_data=(test_images,test_labels))
5.结果可视化
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(acc) + 1)
plt.plot(epochs, acc, 'bo', label='Traning accuracy')
plt.plot(epochs, val_acc, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.figure()
6.结论
本次训练一共进行了5个epoch,在每个epoch中分批次的投放数据,每一批投放128个数据,测试数据共有60000个,所以在每个epoch中进行了469次梯度下降,本次训练一共进行了2345次。结果是训练集准确率超过99%,验证集准确率超过98%,说明训练全连接神经网络便足够预测手写数字。
二、卷积神经网络的实现
1.加载和预处理
过程与之前的过程差不多,只是输入层数据的格式有所不同
(train_images,train_labels),(test_images,test_labels)=mnist.load_data() train_images = train_images.reshape((60000,28,28,1)) test_images = test_images.reshape((10000,28,28,1)) train_images = train_images / 255.0 test_images = test_images / 255.0
2.创建CNN模型
anotherModel = models.Sequential()
anotherModel.add(layers.Conv2D(32,(3,3),activation='relu',input_shape=(28,28,1))) #卷积层1,卷积核3*3
anotherModel.add(layers.MaxPooling2D((2,2))) #池化层1,2*2
anotherModel.add(layers.Conv2D(64,(3,3),activation='relu')) #卷积层2,卷积核3*3
anotherModel.add(layers.MaxPooling2D((2,2))) #池化层2,2*2
anotherModel.add(layers.Flatten()) #Flatten层,连接卷积层与全连接层
anotherModel.add(layers.Dense(512,activation='relu')) #全连接层
anotherModel.add(layers.Dense(10)) #输出层
anotherModel.summary()
3.编译模型
anotherModel.compile(optimizer='adam', #选择优化方法
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), #损失函数
metrics=['accuracy'])
4.训练模型
history = anotherModel.fit(train_images,train_labels,epochs=5,
validation_data=(test_images,test_labels))
5.结果可视化
代码实现与之前的一样,此处不再赘述,只显示结果
6.结论
对比全连接神经网络模型,CNN模型使得验证集的准确度与训练集的准确度更为接近,说明采用CNN的效果更好。
三、参考
https://mtyjkh.blog.csdn.net/article/details/116920825



