赞
踩
import os
import numpy as np
import pandas as pd
from sklearn.metrics import accuracy_score
import datetime
import tensorflow as tf
import matplotlib.pyplot as plt
因为tensorflow自带有minst数据集,这里只需调包加载即可。
# 加载数据
mnist = tf.keras.datasets.mnist
(train_image,train_label),(test_image,test_label) = mnist.load_data()
可以看到训练集包含60000张28*28的图片。
测试集包含10000张28 * 28的图片。
# 查看信息
x_train = train_image
x_test = test_image
y_test = test_label
print(train_image.shape)
print(train_label.shape)
print(test_image.shape)
print(test_label.shape)
打印它的标签
plt.axis('off')
plt.imshow(train_image[100],cmap='gray')
plt.show()
print(train_label[100])
关于预处理的解释
# 转换数据格式 # 将28*28的图像转成32*32 x_train = np.pad(x_train, ((0,0), (2,2), (2,2)), 'constant', constant_values=0) x_test = np.pad(x_test, ((0,0), (2,2), (2,2)), 'constant', constant_values=0) # 数据类型转化成tf需要的 x_train = x_train.astype('float32') x_test = x_test.astype('float32') # 数据正则化,映射到(0,1) x_train /= 255 x_test /= 255 # 数据维度转换,四维 x_train = x_train.reshape(x_train.shape[0], 32, 32, 1) x_test = x_test.reshape(x_test.shape[0], 32, 32, 1)
关于每一层网络的相关信息,参考链接。
关于各参数的解释:
# 搭建网络模型 #超参数设置 num_epochs = 5 # 训练次数 batch_size = 64 # 批大小 learning_rate = 0.001 #学习率 model = tf.keras.models.Sequential([ # 第一层卷积层 tf.keras.layers.Conv2D(filters=6, kernel_size=(5,5), padding='valid', activation=tf.nn.relu, input_shape=(32,32,1)), # 第一池化层 tf.keras.layers.AveragePooling2D(pool_size=(2,2), strides=(2,2), padding='same'), # 第二卷积层 tf.keras.layers.Conv2D(filters=16, kernel_size=(5,5), padding='valid', activation=tf.nn.relu), # 第二池化层 tf.keras.layers.AveragePooling2D(pool_size=(2,2), strides=(2,2), padding='same'), # 扁平化层,将多维数据转换为一维数据。 tf.keras.layers.Flatten(), # 全连接层 tf.keras.layers.Dense(units=120, activation=tf.nn.relu), # 全连接层 tf.keras.layers.Dense(units=84, activation=tf.nn.relu), # 输出层,全连接 tf.keras.layers.Dense(units=10, activation=tf.nn.softmax) ]) # 优化器 adam_optimizer = tf.keras.optimizers.Adam(learning_rate) # 编译模型 model.compile(optimizer=adam_optimizer, loss=tf.keras.losses.sparse_categorical_crossentropy, metrics=['accuracy']) # 模型开始训练时间 start_time = datetime.datetime.now() # 训练模型 model.fit(x=x_train, y=train_label, batch_size=batch_size, epochs=num_epochs) # 模型结束训练,记录训练时间 end_time = datetime.datetime.now() time_cost = end_time - start_time
训练图:
model.summary()
可以看出,预测值是6,实际值也是6。
# 进行预测
image_index = 100 # 选一张图片
pred = model.predict(x_test[image_index].reshape(1,32,32,1))
print(pred.argmax()) # 打印出预测值
plt.imshow(x_test[image_index].reshape(32,32), cmap='Greys')
plt.show()
可以看出,准确率为98.64%
print(model.evaluate(x_test, y_test, verbose=2))
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。