TensorFlow学习笔记——(6)神经网络八股功能扩展

一、自制数据集,解决本领域应用

1、自制数据集

当有本地数据集时,我们不能直接用load_data来加载数据,这时需要自己写函数去制作数据集。

在电脑中有两个文件夹和两个txt文件,分别存放了训练集和测试集的图片和标签。
在这里插入图片描述
其中,训练集有6万张图片,测试集1万张图片。
标签文件mnist_train_jpg_xxxxx.txt 的结构是:
value[0]用于索引到每张图片,也就是图片名字,value[1]是每张图片对应标签。
在这里插入图片描述
用到的主要函数是generateds()

# generateds()函数,用于制作数据集
def generateds(path, txt):
    f = open(txt, 'r')  # 以只读形式打开txt文件
    contents = f.readlines()  # 读取文件中所有行
    f.close()  # 关闭txt文件
    x, y_ = [], []  # 建立空列表
    for content in contents:  # 逐行取出
        value = content.split()  # 以空格分开,图片路径为value[0] , 标签为value[1] , 存入列表
        img_path = path + value[0]  # 拼出图片路径和文件名
        img = Image.open(img_path)  # 读入图片
        img = np.array(img.convert('L'))  # 图片变为8位宽灰度值的np.array格式
        img = img / 255.  # 数据归一化 (实现预处理)
        x.append(img)  # 归一化后的数据,贴到列表x
        y_.append(value[1])  # 标签贴到列表y_
        print('loading : ' + content)  # 打印状态提示

    x = np.array(x)  # 变为np.array格式
    y_ = np.array(y_)  # 变为np.array格式
    y_ = y_.astype(np.int64)  # 变为64位整型
    return x, y_  # 返回输入特征x,返回标签y_
2、mnist实验代码
import tensorflow as tf
from PIL import Image
import numpy as np
import os

# 添加训练集图片和标签文件路径
train_path = './mnist_image_label/mnist_train_jpg_60000/'
train_txt = './mnist_image_label/mnist_train_jpg_60000.txt'
# 训练集输入特征存储文件,标签存储文件
x_train_savepath = './mnist_image_label/mnist_x_train.npy'
y_train_savepath = './mnist_image_label/mnist_y_train.npy'

# 添加测试集图片和标签文件路径
test_path = './mnist_image_label/mnist_test_jpg_10000/'
test_txt = './mnist_image_label/mnist_test_jpg_10000.txt'
# 测试集输入特征存储文件,标签存储文件
x_test_savepath = './mnist_image_label/mnist_x_test.npy'
y_test_savepath = './mnist_image_label/mnist_y_test.npy'

# generateds()函数,用于制作数据集
def generateds(path, txt):
    f = open(txt, 'r')  # 以只读形式打开txt文件
    contents = f.readlines()  # 读取文件中所有行
    f.close()  # 关闭txt文件
    x, y_ = [], []  # 建立空列表
    for content in contents:  # 逐行取出
        value = content.split()  # 以空格分开,图片路径为value[0] , 标签为value[1] , 存入列表
        img_path = path + value[0]  # 拼出图片路径和文件名
        img = Image.open(img_path)  # 读入图片
        img = np.array(img.convert('L'))  # 图片变为8位宽灰度值的np.array格式
        img = img / 255.  # 数据归一化 (实现预处理)
        x.append(img)  # 归一化后的数据,贴到列表x
        y_.append(value[1])  # 标签贴到列表y_
        print('loading : ' + content)  # 打印状态提示

    x = np.array(x)  # 变为np.array格式
    y_ = np.array(y_)  # 变为np.array格式
    y_ = y_.astype(np.int64)  # 变为64位整型
    return x, y_  # 返回输入特征x,返回标签y_

# 判断训练集特征x_train,训练集标签y_train,测试集输入特征x_test,测试集标签y_test是不是已经存在
# 如果存在,直接读取
# 如果不存在,调用generateds()函数制作数据集
if os.path.exists(x_train_savepath) and os.path.exists(y_train_savepath) and os.path.exists(
        x_test_savepath) and os.path.exists(y_test_savepath):
    print('-------------Load Datasets-----------------')
    x_train_save = np.load(x_train_savepath)
    y_train = np.load(y_train_savepath)
    x_test_save = np.load(x_test_savepath)
    y_test = np.load(y_test_savepath)
    # reshape()是数组array中的方法,作用是将数据重新组织,这里可以理解为将数据组织成len(x_train_save), 28, 28的三维数组
    x_train = np.reshape(x_train_save, (len(x_train_save), 28, 28))
    x_test = np.reshape(x_test_save, (len(x_test_save), 28, 28))
else:
    print('-------------Generate Datasets-----------------')
    x_train, y_train = generateds(train_path, train_txt)
    x_test, y_test = generateds(test_path, test_txt)

    print('-------------Save Datasets-----------------')
    x_train_save = np.reshape(x_train, (len(x_train), -1))
    x_test_save = np.reshape(x_test, (len(x_test), -1))
    np.save(x_train_savepath, x_train_save)
    np.save(y_train_savepath, y_train)
    np.save(x_test_savepath, x_test_save)
    np.save(y_test_savepath, y_test)

# 下面的和之前六步法的完全一样
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['sparse_categorical_accuracy'])

model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1)
model.summary()

二、数据增强,扩充数据集

1、介绍

对图像的增强,就是对图像的简单形变,用来应对因拍照角度不同而引起的图片变形。

  • rescale:对输入特征的数值大小进行调整,每个输入特征乘以程序中的超参数
  • rotation_range:对图像进行角度的随机旋转
  • width_shift_range:对图像进行随机宽度偏移
  • height_shift_range:对图像进行随机高度偏移
  • horizontal_flip:选择是否开启随机水平翻转
  • zoom_range:选择随机缩小放大图片

主要代码部分:

image_gen_train = tf.keras.preprocessing.image.ImageDataGenerator(
    rescale = 所有数据将乘以该数值
    rotation_range = 随机旋转角度数范围
    width_shift_range = 随机宽度偏移量
    height_shift_range = 随机高度偏移量
    水平翻转:horizontal_flip = 是否随机水平翻转
    随机缩放:zoom_range = 随机缩放的范围[1-n,1+n])
image_gen_train.fit(x_train)
2、实验代码
import tensorflow as tf
# 增加了ImageDataGenerator模块
from tensorflow.keras.preprocessing.image import ImageDataGenerator

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# 给数据增加一个维度,从(60000, 28, 28)reshape为(60000, 28, 28, 1)
# 因为后面image_gen_train.fit需要输入四维数据,因此需要reshape,将数据变为60000张28行28列单通道数据,这个单通道是灰度值
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)

# 把x_train送入数据增强操作
image_gen_train = ImageDataGenerator(
    rescale=1. / 1.,  # 如为图像,分母为255时,可归至0~1
    rotation_range=45,  # 随机45度旋转
    width_shift_range=.15,  # 宽度偏移
    height_shift_range=.15,  # 高度偏移
    horizontal_flip=False,  # 水平翻转
    zoom_range=0.5  # 将图像随机缩放阈量50%
)
# fit执行增强操作
image_gen_train.fit(x_train)

# 搭建网络结构
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

# 配置训练方法
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['sparse_categorical_accuracy'])

# 执行训练过程
# fit这里以flow形式按照batch打包后执行训练过程
model.fit(image_gen_train.flow(x_train, y_train, batch_size=32), epochs=5, validation_data=(x_test, y_test),
          validation_freq=1)
model.summary()

三、断点续训,存取模型

1、读取保存模型
(1)读取模型

命令

load_weights(路径文件名)

例子

# 先定义出存放模型的路径和文件名,命名为ckpt文件
# 生成ckpt文件时,会同步生成索引表,所以通过判断是否已经有索引表,就知道是不是已经保存过模型参数
checkpoint_save_path = "./checkpoint/mnist.ckpt"
if os.path.exists(checkpoint_save_path + '.index'):
    print('-------------load the model-----------------')
    # 如果有索引表,就说明保存过模型,则可以调用load_weights读取模型参数
    model.load_weights(checkpoint_save_path)
(2)保存模型

命令

# 回调函数
# 三个参数分别为:文件存储路径/是否只保留模型参数/是否只保留最优结果
tf.keras.callbacks.ModelCheckpoint(
filepath=路径文件名,                                     save_weights_only=True/False,                                save_best_only=True/False)

# 执行训练过程时,加入callbacks选项,记录到history中
history = model.fit(callbacks=[cp_callback])

例子

# 加入回调函数,返回给cp_callback
# 三个参数分别为:文件存储路径/是否只保留模型参数/是否只保留最优结果
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
                                                 save_weights_only=True,
                                                 save_best_only=True)
                                                 
# 执行训练过程时,加入callbacks选项,记录到history中
history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1,
                    callbacks=[cp_callback])                                                 
2、实验代码
import tensorflow as tf
# 为了判断保存的模型参数是否存在,引入os模块
import os

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['sparse_categorical_accuracy'])

# 先定义出存放模型的路径和文件名,命名为ckpt文件
# 生成ckpt文件时,会同步生成索引表,所以通过判断是否已经有索引表,就知道是不是已经保存过模型参数
checkpoint_save_path = "./checkpoint/mnist.ckpt"
if os.path.exists(checkpoint_save_path + '.index'):
    print('-------------load the model-----------------')
    # 如果有索引表,就说明保存过模型,则可以调用load_weights读取模型参数
    model.load_weights(checkpoint_save_path)

# 加入回调函数,返回给cp_callback
# 三个参数分别为:文件存储路径/是否只保留模型参数/是否只保留最优结果
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
                                                 save_weights_only=True,
                                                 save_best_only=True)

# 执行训练过程时,加入callbacks选项,记录到history中
history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1,
                    callbacks=[cp_callback])
model.summary()

四、参数提取,把参数存入文本

1、提取可训练参数并打印

(1)提取可训练参数

model.trainable_variables  

(2)设置print输出格式

np.set_printoptions(threshold=超过多少省略显示)

当设置阈值为np.inf时,表示全部显示

np.set_printoptions(threshold=np.inf) # np.inf表示无限大

还可以用for循环将参数存入文本文件

print(model.trainable_variables)
file = open('./weights.txt', 'w')
for v in model.trainable_variables:
    file.write(str(v.name) + '\n')
    file.write(str(v.shape) + '\n')
    file.write(str(v.numpy()) + '\n')
file.close()
2、实验代码

参数续训的基础上增加一部分。

import tensorflow as tf
import os
# 引入numpy模块
import numpy as np

# 设置打印选项,打印所有内容
np.set_printoptions(threshold=np.inf)

# 导入数据集,并归一化处理
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

# 搭建网络结构
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

# 配置训练参数
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['sparse_categorical_accuracy'])

# 参数续训
checkpoint_save_path = "./checkpoint/mnist.ckpt"
if os.path.exists(checkpoint_save_path + '.index'):
    print('-------------load the model-----------------')
    model.load_weights(checkpoint_save_path)
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
                                                 save_weights_only=True,
                                                 save_best_only=True)

# 执行训练过程
history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1,
                    callbacks=[cp_callback])

# 显示网络结构和结果等
model.summary()

# 打印所有可训练参数,并存入weights文件
print(model.trainable_variables)
file = open('./weights.txt', 'w')
for v in model.trainable_variables:
    file.write(str(v.name) + '\n')
    file.write(str(v.shape) + '\n')
    file.write(str(v.numpy()) + '\n')
file.close()

五、acc/loss可视化,查看训练效果

1、介绍

history=model.fit()训练过程中,同步记录了训练集loss、测试集loss、训练集准确率和测试集准确率,因此可以用history.history提取出来。
在这里插入图片描述
在这里插入图片描述

# 训练集准确率
acc = history.history['sparse_categorical_accuracy']
# 测试集准确率
val_acc = history.history['val_sparse_categorical_accuracy']
# 训练集损失函数
loss = history.history['loss']
# 测试集损失函数
val_loss = history.history['val_loss']
2、实验代码

在参数续训和参数提取的代码基础上加上画图

import tensorflow as tf
import os
import numpy as np
from matplotlib import pyplot as plt

np.set_printoptions(threshold=np.inf)

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['sparse_categorical_accuracy'])

checkpoint_save_path = "./checkpoint/mnist.ckpt"
if os.path.exists(checkpoint_save_path + '.index'):
    print('-------------load the model-----------------')
    model.load_weights(checkpoint_save_path)

cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
                                                 save_weights_only=True,
                                                 save_best_only=True)

history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1,
                    callbacks=[cp_callback])
model.summary()

print(model.trainable_variables)
file = open('./weights.txt', 'w')
for v in model.trainable_variables:
    file.write(str(v.name) + '\n')
    file.write(str(v.shape) + '\n')
    file.write(str(v.numpy()) + '\n')
file.close()

###############################################    show   ###############################################

# 显示训练集和验证集的acc和loss曲线
acc = history.history['sparse_categorical_accuracy']
val_acc = history.history['val_sparse_categorical_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']

# subplot将图像分为1行2列,这段代码画第1列
plt.subplot(1, 2, 1)
plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.title('Training and Validation Accuracy')
# 画出图例
plt.legend()

# 画出第二列
plt.subplot(1, 2, 2)
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.title('Training and Validation Loss')
plt.legend()
plt.show()

结果
在这里插入图片描述

六、应用程序,给物识图

在这一节之前,已经可以掌握神经网络训练模型的方法,但是要让模型可用,还要编写一套应用程序,实现给图识物。
在这里插入图片描述

1、前向传播执行应用

TensorFlow给出predict函数,可以根据输入特征,输出预测结果。

predict(输入特征,batch_size=整数)

有了predict函数,实现前向传播执行识图应用仅需三步。
(1)复现模型(前向传播)

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')])

(2)加载参数

model.load_weights(model_save_path)

(3)预测结果

result = model.predict(x_predict)
2、输入图片预处理方法

(1)预处理方法1:颜色取反
图片是白底黑字的图片,但是我们训练模型用的数据集是黑底白字的灰度图,因此需要让每个像素点等于255减去当前像素值。相当于颜色取反。

img_arr = 255 - img_arr

(2)预处理方法2:输入图片变成只有黑色和白色的高对比度图片
用嵌套for循环,遍历输入图片的每一个像素点,灰度值小于200的变成255(纯白色),其余像素点变成0(纯黑色),保留图片有用信息的同时,滤去背景噪声,使图片更干净,阈值选择合理时识别效果会更好。

for i in range(28):
    for j in range(28):
        if img_arr[i][j] < 200:
            img_arr[i][j] = 255
        else:
            img_arr[i][j] = 0
3、实验代码
from PIL import Image
import numpy as np
import tensorflow as tf

model_save_path = './checkpoint/mnist.ckpt'

# 搭建网络结构
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')])

# 加载参数
model.load_weights(model_save_path)

# 询问要执行多少次图像识别的任务
preNum = int(input("input the number of test pictures:"))

# 读入要识别的图片
for i in range(preNum):
    image_path = input("the path of test picture:")
    img = Image.open(image_path)
    # 因为训练时是28行28列的灰度图,输入是任意图片,因此需要resize成28行28列的灰度图
    img = img.resize((28, 28), Image.ANTIALIAS)
    img_arr = np.array(img.convert('L'))

    # 预处理方法1,颜色取反
    # 图片是白底黑字的图片,但是我们训练模型用的数据集是黑底白字的灰度图
    # 因此需要让每个像素点等于255减去当前像素值
    #img_arr = 255 - img_arr
    
    # 预处理方法2,输入图片变成只有黑色和白色的高对比度图片
    # 用嵌套for循环,遍历输入图片的每一个像素点
    # 灰度值小于200的变成255(纯白色),其余像素点变成0(纯黑色)
    # 保留图片有用信息的同时,滤去背景噪声,使图片更干净,阈值选择合理时识别效果会更好
    for i in range(28):
        for j in range(28):
            if img_arr[i][j] < 200:
                img_arr[i][j] = 255
            else:
                img_arr[i][j] = 0

    # 图片数据归一化
    img_arr = img_arr / 255.0
    print("img_arr:", img_arr.shape)
    # 神经网络训练时都是按照batch送入网络的
    # 因为训练时是28行28列的灰度图,输入是任意图片,因此需要resize成28行28列的灰度图
    x_predict = img_arr[tf.newaxis, ...]
    print("x_predict:", x_predict.shape)
    # 送入predict预测
    result = model.predict(x_predict)

    # 把最大的概率值输出
    pred = tf.argmax(result, axis=1)

    # 返回预测结果
    print('\n')
    tf.print(pred)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值