MNIST手写数字识别——TensorFlow版本
- python版本:
python = 3.6.15
- anaconda配置python安装Tensorflow:
- 1.创建版本号为3.6的Tensorflow虚拟环境
conda create -n Tensorflow python=3.6
- 2.激活Tensorflow环境
conda activate Tensorflow
- 3.安装Tensorflow
pip install tensorflow -i https://pypi.tuna.tsinghua.edu.cn/simple
零、引用相应的库
tensorflow.keras.datasets
:导入MNIST手写数字数据库tensorflow.keras.layers
:建立CNN各个层(卷积,池化,全连接)tensorflow.keras.model
:建立CNN模型matplotlib.pyplot
:进行数据可视化
import tensorflow as tf
from tensorflow.keras import datasets,layers,models,losses
import matplotlib.pyplot as plt
一、对数据的处理以及可视化
1.1 数据处理
(train_ds,train_label),(test_ds,test_label) = datasets.mnist.load_data()
train_ds = train_ds / 255.0
test_ds = test_ds / 255.0
train_ds = train_ds.reshape((60000,28,28,1))
test_ds = test_ds.reshape((10000,28,28,1))
1.2 数据可视化
plt.figure(figsize=(20,10))
for i in range(20):
plt.subplot(2,10,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_ds[i],cmap=plt.cm.binary)
plt.xlabel(train_label[i])
plt.show()
二、模型的搭建与训练
model = models.Sequential([
layers.Conv2D(32,(3,3),1,activation='relu',input_shape = (28,28,1)),
layers.MaxPooling2D((2,2),2),
layers.Conv2D(64,(3,3),1,activation='relu'),
layers.MaxPooling2D((2,2),2),
layers.Flatten(),
layers.Dense(64,activation='relu'),
layers.Dense(10)
])
model.summary()
model.compile(
optimizer = 'adam',
loss = losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy']
)
model.fit(
train_ds,
train_label,
epochs=10,
validation_data=(test_ds,test_label)
)
三、训练结果的可视化
def loss_draw(history):
loss = history.history['loss']
epochs = range(1,len(loss)+1)
plt.subplot(1,2,1)
plt.plot(epochs,loss,'bo',label = 'Training Loss')
plt.title('Training Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.subplot(1,2,2)
accuracy = history.history['accuracy']
plt.plot(epochs,accuracy,'bo',label = 'Training Accuracy')
plt.title('Training Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.suptitle('Train data')
plt.legend()
plt.show()
loss_draw(history=history)