TensorFlow笔记_05——神经网络八股功能拓展

目录

  • 5. 神经网络八股功能拓展
    • 5.1 自制数据集,解决本领域应用
    • 5.2 数据增强,扩充数据集
    • 5.3 断点续训,存取模型
      • 5.3.1 读取保存模型
    • 5.4 参数提取,把参数存入文本
    • 5.5 acc/loss可视化,查看训练效果
    • 5.6 应用程序,给图实物(手写数字识别)

上一篇: TensorFlow笔记_04——八股搭建神经网络
下一篇: 敬请期待

5. 神经网络八股功能拓展

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

def generateds(图片路径,标签文件):
import tensorflow as tf
from PIL import Image
import numpy as np
import os

train_path = './fashion_image_label/fashion_train_jpg_60000/'
train_txt = './fashion_image_label/fashion_train_jpg_60000.txt'
x_train_savepath = './fashion_image_label/fashion_x_train.npy'
y_train_savepath = './fashion_image_label/fahion_y_train.npy'

test_path = './fashion_image_label/fashion_test_jpg_10000/'
test_txt = './fashion_image_label/fashion_test_jpg_10000.txt'
x_test_savepath = './fashion_image_label/fashion_x_test.npy'
y_test_savepath = './fashion_image_label/fashion_y_test.npy'


def generateds(path, txt):
    f = open(txt, 'r')
    contents = f.readlines()  # 按行读取
    f.close()
    x, y_ = [], []
    for content in contents:
        value = content.split()  # 以空格分开,存入数组
        img_path = path + value[0]
        img = Image.open(img_path)
        img = np.array(img.convert('L'))
        img = img / 255.
        x.append(img)
        y_.append(value[1])
        print('loading : ' + content)

    x = np.array(x)
    y_ = np.array(y_)
    y_ = y_.astype(np.int64)
    return 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()

5.2 数据增强,扩充数据集

img_gen_train=tf.keras.preprocessing.image.ImageDataGenerator(
			rescale=所有数据集将乘以该数值
			rotation_range=随机旋转角度范围
			width_shift_range=随机宽度偏移量
			height_shift_range=随机高度偏移量
			水平旋转:horizontal_flip=是否随机水平旋转
			随机缩放:zoom_range=随机缩放的范围[1-n,1+n]
)
img_gen_train.fit(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%
)
image_gen_train.fit(x_train)
x_train=x_train.reshape(x_train.shapr[0],28,28,1)

( 60000 , 28 , 28 ) → ( 60000 , 28 , 28 , 1 ) (60000,28,28)\rightarrow(60000,28,28,1) (60000,28,28)(60000,28,28,1)

model.fit(x_train,y_train,batch_size=32,......)
			↓更新为
model.fit(image_gen_train.flow(x_train,y_train,batch_size=32))

代码展示

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()
Epoch 1/5
1871/1875 [============================>.] - ETA: 0s - loss: 1.4016 - sparse_categorical_accuracy: 0.5496WARNING:tensorflow:Model was constructed with shape (None, None, None, None) for input KerasTensor(type_spec=TensorSpec(shape=(None, None, None, None), dtype=tf.float32, name='flatten_input'), name='flatten_input', description="created by layer 'flatten_input'"), but it was called on an input with incompatible shape (None, 28, 28).
1875/1875 [==============================] - 12s 6ms/step - loss: 1.4008 - sparse_categorical_accuracy: 0.5500 - val_loss: 0.4490 - val_sparse_categorical_accuracy: 0.8868
Epoch 2/5
1875/1875 [==============================] - 12s 7ms/step - loss: 0.9430 - sparse_categorical_accuracy: 0.7134 - val_loss: 0.3516 - val_sparse_categorical_accuracy: 0.9052
Epoch 3/5
1875/1875 [==============================] - 12s 6ms/step - loss: 0.8252 - sparse_categorical_accuracy: 0.7510 - val_loss: 0.2830 - val_sparse_categorical_accuracy: 0.9229
Epoch 4/5
1875/1875 [==============================] - 12s 6ms/step - loss: 0.7523 - sparse_categorical_accuracy: 0.7728 - val_loss: 0.2674 - val_sparse_categorical_accuracy: 0.9245
Epoch 5/5
1875/1875 [==============================] - 12s 6ms/step - loss: 0.7182 - sparse_categorical_accuracy: 0.7827 - val_loss: 0.2411 - val_sparse_categorical_accuracy: 0.9317
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
flatten (Flatten)            (None, None)              0         
_________________________________________________________________
dense (Dense)                (None, 128)               100480    
_________________________________________________________________
dense_1 (Dense)              (None, 10)                1290      
=================================================================
Total params: 101,770
Trainable params: 101,770
Non-trainable params: 0
_________________________________________________________________

5.3 断点续训,存取模型

5.3.1 读取保存模型

读取模型:

load_weights(路径文件名,后缀为.ckpt)
#因为生成ckpt文件的时候会同步生成索引表,通过判断是不是已经有了索引表就知道是不是已经保存过模型参数
#如果有了索引表,就可以调用load_weights函数读取模型参数

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

保存模型:

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

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,
                 valldation_data=(x_test,y_test),validation_freq=1,
                 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'])

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()
Epoch 1/5
1875/1875 [==============================] - 2s 1ms/step - loss: 0.2580 - sparse_categorical_accuracy: 0.9258 - val_loss: 0.1361 - val_sparse_categorical_accuracy: 0.9605
Epoch 2/5
1875/1875 [==============================] - 2s 1ms/step - loss: 0.1116 - sparse_categorical_accuracy: 0.9675 - val_loss: 0.0966 - val_sparse_categorical_accuracy: 0.9705
Epoch 3/5
1875/1875 [==============================] - 2s 1ms/step - loss: 0.0758 - sparse_categorical_accuracy: 0.9776 - val_loss: 0.0854 - val_sparse_categorical_accuracy: 0.9737
Epoch 4/5
1875/1875 [==============================] - 2s 1ms/step - loss: 0.0570 - sparse_categorical_accuracy: 0.9831 - val_loss: 0.0736 - val_sparse_categorical_accuracy: 0.9766
Epoch 5/5
1875/1875 [==============================] - 2s 1ms/step - loss: 0.0432 - sparse_categorical_accuracy: 0.9865 - val_loss: 0.0791 - val_sparse_categorical_accuracy: 0.9757
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
flatten (Flatten)            (None, 784)               0         
_________________________________________________________________
dense (Dense)                (None, 128)               100480    
_________________________________________________________________
dense_1 (Dense)              (None, 10)                1290      
=================================================================
Total params: 101,770
Trainable params: 101,770
Non-trainable params: 0
_________________________________________________________________

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

model.trainable_variables	返回模型中可训练的参数

设置print输出形式,因为直接print中间会有很多省略号
np.set_printoptions(threshold=超过多少省略显示)
np.set_printoptions(threshold=np.inf) #np.inf表示无限大
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()

将提取出来的参数都存入了weights.txt文件

TensorFlow笔记_05——神经网络八股功能拓展_第1张图片

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

history=model.fit(训练集,训练集标签,batch_size=,epochs=,
                 validation_split=用于测试数据的比例,
                 validation_data=测试集,
                 validation_freq=测试频率)
history:
训练集loss:loss
测试集loss:val_loss
训练集准确率:sqarse_categorical_accuray
测试集准确率:val_sparse_categorical_accuracy
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()

TensorFlow笔记_05——神经网络八股功能拓展_第2张图片

5.6 应用程序,给图实物(手写数字识别)

前向传播执行应用

predict(输入特征,batch_size=整数)
返回前向传播计算结果

复现模型(前向传播) model=tf.keras.models.Sequential([
				tf.kreas.layers.Flatten(),
				tf.kreas.layres.Dense(128,activation='relu'),
				tf.kreas.layers.Dense(10,activation='softmax')
])
加载参数:model.load_weights(model_save_path)

预测结果:result=model.predict(x_predict)
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'))

    #将图像转换为高对比度,像素小于200的变成255,大于200的变成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
    x_predict = img_arr[tf.newaxis, ...]
    result = model.predict(x_predict)

    pred = tf.argmax(result, axis=1)

    print('\n')
    tf.print(pred)

你可能感兴趣的:(#,TensorFlow2.0,tensorflow,神经网络,深度学习)