【Tensorflow】自制数据集--神经网络八股功能扩展

【Tensorflow】自制数据集–神经网络八股功能扩展

  • 0.自制数据集,解决本领域应用

  • 1.数据增强,扩充数据集

  • 2.断点续训,存取模型

  • 3.参数提取,把参数存入文本

  • 4.acc/loss可视化,查看训练效果

  • 5.应用程序,给图识物

本文内容学习来自B站【北京大学】Tensorflow2.0
代码及数据集下载
提取码:52ru

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

数据集中的图片均为黑底白字,像素点为28x28的灰度图,训练用的数据集mnist_train_ipg_60000中有60000张图片,测试用的数据集mnist_test_jpg_10000中有10000张图片,这些图片均为手写字。在两个txt文件中存储着图片名称以及对应标签。3933_2.jpg是图片名称,2是图片标签,表示该图片为手写字2。每个像素点为均为0~255之间的整数,纯黑色用数值0表示,纯白色用数值255表示。mnist_test_jpg_10000

0.2 自定义generateds函数用于获得输入特征及标签

def generatrds(path,txt):
	f = open(txt,'r)  #打开文件,只读
	contents = f.readlines()  #按行读取,并将读取内容存入contents
	f.close()  #关闭文件
	x, y_ = [],[]  #建立两个列表,用于存储特征及标签
	for content in contents:
		value = content.split()  #value值按空格隔开
		img_path = path + value[0]  #value[0]即为图片名称,value[1]为标签
		img = Image.open(img_path)  #打开图片
		img = np.array(img.convert('L'))  #图片变为八位宽度的灰度值np.array格式
		img = img/255.  #归一化
		x.append(img)  #归一化后贴到列表x
		y_.append(value[1])  #把标签贴到列表y
		print('loading:'+content)  #打印输出
	x = np.array(x)
	y_ = np.array(y_)
	y_ = y_.astype(np.int64)  #类型转换
	return x,y_

完整代码

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'


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_


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)
    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()

0.3 运行结果

起初文件夹中并没有npy文件,所以执行Generate Datasets,调用generateds函数,得到x_train,x_test,y_train,y_test,并执行Save Datasets, 将文件保存如下:
运行后得到文件

np.save(file, arr, allow_pickle=True, fix_imports=True)
解释:Save an array to a binary file in NumPy .npy format。以“.npy”格式将数组保存到二进制文件中。
参数:
file 要保存的文件名称,需指定文件保存路径,如果未设置,保存到默认路径。其文件拓展名为.npy
arr 为需要保存的数组,也即把数组arr保存至名称为file的文件中。
原文地址

在这里插入图片描述

1.1 数据增强,扩充数据集

数据增强目的:增大数据量
可以参考一下这篇文章:Data Augmentation

数据增强函数:
tf.keras.preprocessing.image.ImageDataGenerator(
		rescale = 所有数据将乘以该数值
		rotation_range = 随即旋转角度数范围
		width_shift_range = 随机宽度偏移量
		height_shift_range = 随机高度偏移量
		horizontal_flip = 是否随机水平翻转
		zoom_range = 随机缩放的范围[1-n,1+n]
)

完整代码

import tensorflow as tf
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
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)  # 给数据增加一个维度,从(60000, 28, 28)reshape为(60000, 28, 28, 1),最后一个维度是灰度值

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%
)
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'])

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()

2.1 断点续训,存取模型

要想读取模型可以直接使用tensorflow的函数load_weights(路径文件名),就可以直接读取已有模型参数。可以先定义出存放模型的路径及文件名,文件名后缀为ckpt,生成ckpt文件时会同步生成index文件(索引表),所以通过判断是否已经存在索引表来判断模型是否存在,如果参在直接加载模型,读取模型参数;如果不存在,则需要使用tensorflow给的回调函数:

# 是否只保存模型参数,是否只保存最优模型
cp_callback = tf.keras.callbacks.ModelCheckpoint(
		filepath = 路径文件名,
		save_weights_only = True/False,
		save_best_only = True/False
)
history = model.fit(callbacks = [cp_callback])

加入断点续训后的完整代码

import tensorflow as tf
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'])
# 引入os模块用于判断保存的模型参数是否存在
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()

第二次执行时可以看到输出load the model, 加载了已经保存的模型参数,而且准确率不断升高,执行时间不断减小。

3.1 参数提取,把参数存入文本

如何看到刚刚保存的模型参数呢?可以使用参数提取的方法,将参数存入文本。

model.trainable_variables   # tensorflow中可以该函数返回模型中可训练的参数
# 设置print输出格式,当输出数量超过阈值时以省略号的形式输出
np.set_printoptions(threshold=np.inf)  # np.inf表示无限大
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()  # 关闭文件

完整代码(包含断点续训)

import tensorflow as tf
import os
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()
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()

3.2 查看结果

在这里插入图片描述

4.1 acc曲线和loss曲线

history = model.fit(训练集数据,训练集标签,batch_size=,
					epochs=,validation_split=用作测试数据的比例,
					validation_data=测试集,validation_freq=测试频率)
# 在训练和测试中均已计算accuracy,使用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']  #测试集损失函数

完整代码

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']

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()

4.2 运行结果

在这里插入图片描述

5.在下一篇文中

继续加油!

猜你喜欢

转载自blog.csdn.net/qq_45746168/article/details/128068287