对项目一: 图像分类的逐步解析
#!/bin/bash
# -*-coding:utf-8-*-
###### 第一个简单项目测试: 图像分类模型测试. 数据集为: Fashion MNIST. Tensorflow2.0
############################
# 将新版本的特性引进当前版本中。
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
from tensorflow import keras
# data process
import numpy as np
import matplotlib.pyplot as plt
# 1. 导入数据
fashion_mnist = keras.datasets.fashion_mnist
(train_image, train_labels), (test_image, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# 2. 明确数据格式
# print('trian_image size: ', train_image.shape, 'train_labels_size: ', train_labels.size)
# print(train_labels[:10])
# 3. 预处理数据
# plt.figure()
# plt.imshow(train_image[1])
# #plt.colorbar()
# plt.grid(False)
# plt.show()
# 3.1 将图像数据0~255像素范围的数值压缩到0~1之间, 防止图像在缩放、旋转等变换中像素尺度发生变化, 所以将其归一化到0~1之间.
train_image = train_image / 255.0
test_image = test_image / 255.0
# 3.2 验证数据格式是否正确,显示训练集中钱25个图像
# plt.figure()
# for i in range(25):
# plt.subplot(5, 5, i+1)
# plt.grid(False)
# plt.imshow(train_image[i], cmap=plt.cm.binary)
# plt.xlabel(class_names[train_labels[i]])
# plt.show()
# 4. 配置模型的层,然后编译模型
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'), # Dense--全连接层或稠密层.
keras.layers.Dense(10, activation='softmax')] # 返回一个具有10个概率得分的数组,这些得分的总和为 1
)
# > keras.layers.dropout(0.2): 使用dropout是要改善过拟合,将训练和测试的准确率差距变小, (按照一定的概率将其暂时从网络中丢弃, 如在此是丢弃20%神经元不工作)
# 4.1 编译模型,设置模型的编译步骤
model.compile(optimizer='adam', # 优化器
loss='sparse_categorical_crossentropy', # 损失函数
metrics=['accuracy'] # 度量标准--准确率
)
# 4.2 训练模型
model.fit(train_image, train_labels, epochs=5)
# 5. 评估模型精度
test_loss, test_accu = model.evaluate(test_image, test_labels)
# print('\ntest accuracy:', test_accu)
##############
# (1) 模型训练的精度为: 0.8914; 数据集测试的精度为: 0.8704. 模型在测试数据集中的准确率@TODO 低于训练数据集上的准确率.
# (2) 这种差异表明出现过拟合(overfitting)
###############
# 6.模型预测
predictions = model.predict(test_image)
# 输出预测数据的格式, 以及对第一张图片预测属于10种产品的置信度不一.
print("predictions.shape = ", predictions.shape, "predictions[0]: \n", predictions[0], 'The Fist Most confidence: ', np.argmax(predictions[0]))
# 7. 将预测绘制成图来查看全部各10个通道
def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]
plt.grid(False)
plt.imshow(img, cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100 * np.max(predictions_array),
class_names[true_label]),
color=color)
def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array[i], true_label[i]
plt.grid(False)
plt.xticks([])
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')
# 7.1 图像显示测试
# i = 0
# plt.figure(figsize=(6,3))
# plt.subplot(1,2,1)
# plot_image(i, predictions, test_labels, test_image)
# plt.subplot(1,2,2)
# plot_value_array(i, predictions, test_labels)
# plt.show()
# 8. 利用训练好的模型来预测单张图像的分类结果
img = test_image[0]
print(img.shape)
img = np.expand_dims(img, 0) # 扩充数据的维度.
print(img.shape)
prediction_single = model.predict(img)
plot_value_array(0, prediction_single, test_labels)
plt.xticks(range(10), class_names, rotation=45) # 对x轴添加10个标签,分别为class_names中的10个种类,并将标签倾斜45°.
plt.show()
print(prediction_single)
print(np.argmax(prediction_single[0]))
TF-模型/权重保存的几种方法
#!/bin/bash
# -*-coding:utf-8-*-
###### 第一个简单项目测试: 模型保存测试 Tensorflow2.0
############################
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
from tensorflow import keras
import os
# data process
import numpy as np
import matplotlib.pyplot as plt
# 1. 导入数据
fashion_mnist = keras.datasets.fashion_mnist
(train_image, train_labels), (test_image, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# 2. 明确数据格式
# 3. 预处理数据
# 3.1 将图像数据0~255像素范围的数值压缩到0~1之间, 防止图像在缩放、旋转等变换中像素尺度发生变化, 所以将其归一化到0~1之间.
train_image = train_image / 255.0
test_image = test_image / 255.0
# 3.2 验证数据格式是否正确,显示训练集中钱25个图像
# 4. 定义一个创建模型的函数
def create_model():
# 4.1 配置模型的层,然后编译模型
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'), # Dense--全连接层或稠密层.
keras.layers.Dense(10, activation='softmax')] # 返回一个具有10个概率得分的数组,这些得分的总和为 1
)
# 4.2 编译模型,设置模型的编译步骤
model.compile(optimizer='adam', # 优化器
loss='sparse_categorical_crossentropy', # 损失函数
metrics=['accuracy'] # 度量标准--准确率
)
return model
###### 保存模型的方法一: 保存模型的检查点 ####
checkpoint_path = "../Models/test1.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)
cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path,
save_weights_only= True,
verbose=1)
model = create_model()
# 4.2 训练模型
model.fit(train_image, train_labels, epochs=5,
validation_data=(test_image, test_labels),
callbacks=[cp_callback])
###### 保存模型的方法一: 保存模型的检查点 ####
# 5. 测试保存的模型
###### 测试调用保存模型的方法一 ####
#5.1 不使用保存的模型,测试数据的预测精度
unmodel = create_model()
loss, acu = unmodel.evaluate(test_image, test_labels)
print("Untrained model, accuracy: {:5.2f}%".format(100*acu))
# 5.2 调用保存的模型,测试数据的预测精度
unmodel.load_weights(checkpoint_path)
loss, acu = unmodel.evaluate(test_image, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acu))
###### 测试调用保存模型的方法一 ####
###### 保存模型的方法二: 手动保存模型的权重 ####
model2 = create_model()
# 训练模型
model2.fit(train_image, train_labels, epochs=5,
validation_data=(test_image, test_labels))
model2.save_weights('../Models/save_checkpoint_hands')
# test
model2_acu = create_model()
model2_acu.load_weights('../Models/save_checkpoint_hands')
loss, acu = model2_acu.evaluate(test_image, test_labels)
###### 保存模型的方法二: 手动保存模型的权重 ####
###### 保存模型的方法三: 保存整个模型hdf5 ####
model3 = create_model()
# 训练模型
model3.fit(train_image, train_labels, epochs=5,
validation_data=(test_image, test_labels))
model3.save('../Models/full_model.h5')
# test
model3_acu = keras.models.load_model('../Models/full_model.h5')
loss, acu = model3_acu.evaluate(test_image, test_labels)
###### 保存模型的方法三: 保存整个模型hdf5 ####