“历史遗留”的学习记录
MNIST手写数字—tensorflow2—tensorboard—网页可视化查看结果
(PS:时隔久远,但还是能运行)
- 子程序包括:数据集处理、数据集图片读取转换、PNG图显示
- 对数据训练集、验证集的打乱
- 搭建5层神经网络
- 设置学习率并进行梯度下降
- 保存运行日志在文件夹中
- 用验证(测试)集评估准确率
- 在网页上显示过程并展示部分图片
import tensorflow as tf
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
import datetime
from matplotlib import pyplot as plt
import io
# 对数据集预处理,转换数据类型
def preprocess(x, y):
x = tf.cast(x, dtype=tf.float32) / 255.
y = tf.cast(y, dtype=tf.int32)
return x,y
# 将数据集的图片读取、转换成PNG格式并返回
def plot_to_image(figure):
buf = io.BytesIO() #在内存中读写bytes
plt.savefig(buf, format='png') #保存生成的图片
plt.close(figure)
buf.seek(0) #文件读取指针移动到文件第“0”个字节处,这里即移动到文件头位置
image = tf.image.decode_png(buf.getvalue(), channels=4) #对PNG图像进行解码,得到图像的像素值,用于显示图像
image = tf.expand_dims(image, 0) #指定在第“0”维添加维数
return image
# 将上面返回的PNG图像显示出来
def image_grid(images):
figure = plt.figure(figsize=(10,10)) #创建宽和高分别为10英寸的图像
for i in range(64):
plt.subplot(8, 8, i + 1, title='name') #生成36个子图像
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow