您当前的位置: 首页 >  网络

Better Bench

暂无认证

  • 2浏览

    0关注

    695博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【北京大学】Tensorflow2.0神经网络八股扩展、增加自制数据集、数据增强、断点续参数提取和acc、loss可视化,实现给图识物的应用程序

Better Bench 发布时间:2020-11-05 09:11:45 ,浏览量:2

目录
  • 1 本讲目标
  • 2 自制数据集
  • 4 断点续训 存取模型
  • 5 参数提取
  • 6 acc/loss可视化,查看训练效果
  • 7 应用程序给图识物

Tensorflow2.0课程 Tensorflow2.0第一讲 Tensorflow2.0第二讲 Tensorflow2.0第三讲 Tensorflow2.0第四讲 Tensorflow2.0第五讲 Tensorflow2.0第六讲

1 本讲目标

(1)自制数据集,解决本领域应用 (2)数据增强,扩充数据集 (3)断点续训,存取模型 (4)参数提取,把参数存入文本 (5)acc/loss 可视化,查看训练效果 (6)应用程序,给图识物

2 自制数据集

(1) 观察数据集数据结构,给x_train、y_train 、x_test、y_test

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_
    ```
# 3 数据增强
```python
image_gen_train = ImageDataGenerator(
    rescale=1. / 255,# 所有数据将乘以该数值
    rotation_range=45, # 随机旋转角度范围
    width_shift_range=.15,# 随机宽度偏移量
    height_shift_range=.15, # 随机高度偏移量
    horizontal_flip=False,# 是否随机水平翻转
    zoom_range=0.5  # 随机缩放的范围[1-n.1+n]
)
image_gen_train.fit(x_train)
4 断点续训 存取模型
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'])
# 读取模型load_weights(路径文件名)
checkpoint_save_path = "./checkpoint/mnist.ckpt"# 生成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()
5 参数提取

(1)提取可训练参数 model.trainable_variables返回模型中可训练的参数 (2)设置print输出格式 np.set_printoptions(threshold = 超过多少省略显示)

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()
6 acc/loss可视化,查看训练效果

(1)使用方法 history = model.fit(训练集数据,训练集标签,batch_size = ,epochs = ,validation_split =用作测试数据的比例,validation_data = 测试集,validation_freq = 测试频率) (2)可选参数 history: 训练集loss: loss 测试集loss: val_los 训练集准确率:sparse_categorical_accuracy 测试集准确率: val_sparse_categorical_accuracy

# 显示训练集和验证集的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()

(3)完整Demo

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()
7 应用程序给图识物

(1)前向传播执行应用 predict(输入特征,batch_size = 整数) 返回前向传播计算结果 (2)复现模型(前向传播)

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

(3)加载参数(读取参数)

model.load_weights(model_save_path)

(4)预测结果

result = model.predict(x_predict)

(5)图片预处理

# 图片预处理
    for i in range(28):
        for j in range(28):
            if img_arr[i][j]             
关注
打赏
1665674626
查看更多评论
0.0400s