美文网首页
4.1 神经网络扩展

4.1 神经网络扩展

作者: 徐大徐 | 来源:发表于2021-12-01 21:16 被阅读0次

    ①自制数据集,解决本领域应用
    ②数据增强,扩充数据集
    ③断点续训,存取模型
    ④参数提取,把参数存入文本
    ⑤acc/loss可视化,查看训练效果
    ⑥应用程序,给图识物

    数据增强

    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] )
    例:
    数据增强(增大数据量)
    11
    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)
    image_gen_train.fit(x_t
    

    实现对训练数据的增强

    import tensorflow as tf
    from tensorflow.keras.preprocessing.image import ImageDataGenerator
    
    fashion = tf.keras.datasets.fashion_mnist
    (x_train, y_train), (x_test, y_test) = fashion.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)  # 给数据增加一个维度,使数据和网络结构匹配
    
    image_gen_train = ImageDataGenerator(
        rescale=1. / 1.,  # 如为图像,分母为255时,可归至0~1
        rotation_range=45,  # 随机45度旋转
        width_shift_range=.15,  # 宽度偏移
        height_shift_range=.15,  # 高度偏移
        horizontal_flip=True,  # 水平翻转
        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()
    

    读取保存模型

    load_weights(路径文件名)

    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
    
    fashion = tf.keras.datasets.fashion_mnist
    (x_train, y_train), (x_test, y_test) = fashion.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/fashion.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()
    
    

    提取可训练参数

    model.trainable_variables 返回模型中可训练的参数
    设置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()
    

    acc曲线与loss曲线

    history=model.fit(训练集数据, 训练集标签, batch_size=, epochs=,validation_split=用作测试数据的比例,validation_data=测试集,validation_freq=测试频率)
    history:
    训练集loss: loss
    测试集loss: val_loss
    训练集准确率: sparse_categorical_accuracy
    测试集准确率: val_sparse_categorical_accuracy

    # 显示训练集和验证集的acc和loss曲线
    checkpoint_save_path = "./checkpoint/fashion.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])
    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()
    

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

    返回前向传播计算结果

    复现模型

    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)

    预测结果

    result = model.predict(x_predict)

    from PIL import Image
    import numpy as np
    import tensorflow as tf
    import matplotlib.pyplot as plt
    type = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
    
    model_save_path = './checkpoint/fashion.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)
    
        image = plt.imread(image_path)
        plt.set_cmap('gray')
        plt.imshow(image)
    
        img=img.resize((28,28),Image.ANTIALIAS)
        img_arr = np.array(img.convert('L'))
        img_arr = 255 - img_arr
    
        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')
        print(type[int(pred)])
    
        plt.pause(1)
        plt.close()
    

    相关文章

      网友评论

          本文标题:4.1 神经网络扩展

          本文链接:https://www.haomeiwen.com/subject/vysrxrtx.html