PS:1、本文旨在对TF学习过程进行备忘,本人菜得抠脚,故文章难免会有一定错误,还望指出,谢谢;
2、本文程序代码使用Google TensorFlow所给出的官方入门教程;
3、本文使用tf.keras,对模型进行构建与训练。
4、本文建立的前提是对模型构建与训练流程掌握,其中各部分原理不一定能完整表达。
import tensorflow as tf # 导入tensorflow
from tensorflow import keras
import numpy as np #宏定义
import matplotlib.pyplot as plt #宏定义??
fashion_mnist = keras.datasets.fashion_mnist#获取fashion_mnist训练集
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']#对分类数据定义名称
print(tf.__version__)#获取当前tf版本
print(train_images.shape)#读取数据集的“格式”(shape
print(len(train_labels))#读取标签类型长度
print(train_labels)#打印当前训练集中的标签
print(test_images.shape)#读取数据集的格式(shape
print(len(test_labels))#读取标签长度
输出
2.2.0#当前tf版本
(60000, 28, 28)#训练集中数据格式为6000张图片,每张28x28像素
60000#标签数量
[9 0 0 ... 3 0 5]#标签为0-9的整数
(10000, 28, 28)#测试集,10000图片28x28像素
10000#测试集包含10000张标签
测试一下数据集中的图片
其中所使用的matplotlib.pyplot方法详见matplotlib官网
#在训练网络之前,必须对数据进行预处理。
plt.figure()
plt.imshow(train_images[0])#引入第0张图片,默认彩图
#plt.imshow(train_images[0],cmap=plt.cm.binary)#显示图像,以二值化的方式显示
plt.colorbar()#颜色彩条
#plt.grid(False)
plt.grid(True)#显示网格,通过False\True控制
plt.title("Photo1")#设置title
plt.show()#显示
#预处理流程
#1:将颜色深度由0-255转换为0-1
train_images = train_images / 255.0
test_images = test_images / 255.0
#2:显示图片集
plt.figure(figsize=(10,10))#设置图片size
for i in range(25):
plt.subplot(5,5,i+1)#5x5结构进行显示
plt.xticks([])
plt.yticks([])
plt.grid(False)#不显示网格
plt.imshow(train_images[i], cmap=plt.cm.binary)#显示二值化图像
plt.xlabel(class_names[train_labels[i]])#显示训练集标签
plt.show()
plt.figure()
#plt.imshow(train_images[0])#引入第0张图片,默认彩图
plt.imshow(train_images[0],cmap=plt.cm.binary)#显示图像,以二值化的方式显示
plt.colorbar()#颜色彩条
#plt.grid(False)
plt.grid(True)#显示网格,通过False\True控制
plt.title("Photo1")#设置title
激活函数的引入简单来说,就是为了解决神经网络所构建的线性方程解决不了非线性的问题。
其中激活函数的各种类及各自原理,可以参考这篇文章
激活函数的作用可以参考这篇文章
关于sequential(序贯模型)的相关使用,详见TF官网指南
也可查看该博主的相关文章
全连接层目前理解不够,留坑
#构建模型
#使用Kera序贯模型(Sequential)
#输入数据维度shape
#隐藏神经元、激活函数
#设定输出层(标签类型种类)
#Dense为全连接层模型
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),#指定输入数据的尺寸
keras.layers.Dense(128, activation='swish'),#128个隐藏神经元的全连接层,激活函数使用relu
keras.layers.Dense(10)#设定输出层为10(标签为10类)
])
#编译模型(设定以下三类参数——留坑
#optimizer 优化器
#loss 损失函数
#metrics 评估标准(默认accuracy)
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
#开始训练模型
#训练集&训练标签,设定步长为五十步
model.fit(train_images, train_labels, epochs=10)
#测试集验证训练模型准确度,使用训练集图片&训练集标签
#verbose:日志显示
#verbose = 0 为不在标准输出流输出日志信息
#verbose = 1 为输出进度条记录(默认)
#verbose = 2 为每个epoch输出一行记录
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=0)
print('\nTest accuracy:', test_acc)#打印测试集的准确度
print('\nTest loss:', test_loss)#打印测试集的损失度
输出结果
#训练集结果 loss: 0.2181 - accuracy: 0.9174
Test accuracy: 0.8842999935150146
Test loss: 0.33912330865859985
事实证明,测试集的准确性略低于训练集的准确性。训练准确性和测试准确性之间的差距代表过度拟合。当机器学习模型在新的,以前看不见的输入上的表现比训练数据上的表现差时,就会发生过度拟合。过度拟合的模型“记忆”训练数据集中的噪声和细节,从而对新数据的模型性能产生负面影响
对于过拟合的问题,详见该tf官网所给出的文档
softmax层留坑
#模型的线性输出logits。附加一个softmax层,以将logit转换为更容易解释的概率。
probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()])
#模型对测试集中每个图像的标签进行预测处理
predictions = probability_model.predict(test_images)
print(predictions[0])#验证预测
#关于np.argmax的用法
#a = np.array([3, 1, 2, 4, 6, 1])#构建一个数组
#b=np.argmax(a)#取出a中元素最大值所对应的索引,此时最大值位6,其对应的位置索引值为4,(索引值默认从0开始)
#print(b)#b=4
#图像对于10种不同的label,可以看到哪个标签的置信度最高:
print(np.argmax(predictions[0]))
#对测试集的标签置信度进行测试
print('\n Test label 1:',test_labels[1])
#py的def plot_image()--->C/C++的:void plot_image()
#以图形方式查看完整的10个类预测。
#传参:计数器i,预测数组,真的标签,图像
def plot_image(i, predictions_array, true_label, img):
#?????
predictions_array, true_label, img = predictions_array, true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img, cmap=plt.cm.binary)#显示二值化图像
#预测标签=置信度最高的位(预测数组)
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:#预测等于真正的标签,显示blue
color = 'blue'
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),#百分比显示置信度
class_names[true_label]),#显示真实的label
color=color)
#作用:生成置信度柱状图
#传参:计数器i,预测数组,真的标签
def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array, true_label[i]
plt.grid(False)
plt.xticks(range(10))
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)
thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue')
#单张测试,i=0
# i = 0
# plt.figure(figsize=(6,3))
# plt.subplot(1,2,2)#用于对显示图片位置进行调整
# plot_image(i, predictions[i], test_labels, test_images)
# plt.subplot(1,2,1)#用于对显示图片位置进行调整
# #显示置信度柱状图
# plot_value_array(i, predictions[i], test_labels)
# #plt.show()#显示图片
#快速注释快捷键 ctrl+/
# i = 12
# plt.figure(figsize=(6,3))
# plt.subplot(1,2,1)
# plot_image(i, predictions[i], test_labels, test_images)
# plt.subplot(1,2,2)
# plot_value_array(i, predictions[i], test_labels)
#多组图片测试
#显示前X张测试图像,并显示它们的预测标签和真实标签。
#正确的预测结果设置为蓝色,错误预测设置为红色
num_rows = 5#5行
num_cols = 3#3列
num_images = num_rows*num_cols#显示图片的总数
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):#循环显示各图片,及置信度
plt.subplot(num_rows, 2*num_cols, 2*i+1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(num_rows, 2*num_cols, 2*i+2)
plot_value_array(i, predictions[i], test_labels)
plt.tight_layout()
plt.show()
https://tensorflow.google.cn/tutorials/keras/classification?hl=zh_cn