• 卷积神经网络(VGG-19)灵笼人物识别


    前期工作

    1. 设置GPU(如果使用的是CPU可以忽略这步)

    我的环境:

    • 语言环境:Python3.6.5
    • 编译器:jupyter notebook
    • 深度学习环境:TensorFlow2.4.1
    import tensorflow as tf
    
    gpus = tf.config.list_physical_devices("GPU")
    
    if gpus:
        tf.config.experimental.set_memory_growth(gpus[0], True)  #设置GPU显存用量按需使用
        tf.config.set_visible_devices([gpus[0]],"GPU")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    2. 导入数据

    import matplotlib.pyplot as plt
    # 支持中文
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
    
    import os,PIL
    
    # 设置随机种子尽可能使结果可以重现
    import numpy as np
    np.random.seed(1)
    
    # 设置随机种子尽可能使结果可以重现
    import tensorflow as tf
    tf.random.set_seed(1)
    
    from tensorflow import keras
    from tensorflow.keras import layers,models
    
    import pathlib
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    data_dir = "weather_photos/"
    data_dir = pathlib.Path(data_dir)
    
    • 1
    • 2

    3. 查看数据

    数据集中一共有白月魁、查尔斯、红蔻、马克、摩根、冉冰等6个人物角色。

    文件夹含义数量
    baiyuekui白月魁40 张
    chaersi查尔斯76 张
    hongkou红蔻36 张
    make马克38张
    mogen摩根30 张
    ranbing冉冰60张
    image_count = len(list(data_dir.glob('*/*')))
    
    print("图片总数为:",image_count)
    
    • 1
    • 2
    • 3

    二、数据预处理

    1. 加载数据

    使用image_dataset_from_directory方法将磁盘中的数据加载到tf.data.Dataset

    batch_size = 32
    img_height = 224
    img_width = 224
    
    • 1
    • 2
    • 3
    train_ds = tf.keras.preprocessing.image_dataset_from_directory(
        data_dir,
        validation_split=0.1,
        subset="training",
        seed=123,
        image_size=(img_height, img_width),
        batch_size=batch_size)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    Found 280 files belonging to 6 classes.
    Using 252 files for training.
    
    • 1
    • 2
    val_ds = tf.keras.preprocessing.image_dataset_from_directory(
        data_dir,
        validation_split=0.1,
        subset="validation",
        seed=123,
        image_size=(img_height, img_width),
        batch_size=batch_size)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    Found 280 files belonging to 6 classes.
    Using 28 files for validation.
    
    • 1
    • 2

    我们可以通过class_names输出数据集的标签。标签将按字母顺序对应于目录名称。

    class_names = train_ds.class_names
    print(class_names)
    
    • 1
    • 2
    ['baiyuekui', 'chaersi', 'hongkou', 'make', 'mogen', 'ranbing']
    
    • 1

    2. 可视化数据

    plt.figure(figsize=(10, 5))  # 图形的宽为10高为5
    
    for images, labels in train_ds.take(1):
        for i in range(8):
            
            ax = plt.subplot(2, 4, i + 1)  
    
            plt.imshow(images[i].numpy().astype("uint8"))
            plt.title(class_names[labels[i]])
            
            plt.axis("off")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    在这里插入图片描述

    plt.imshow(images[1].numpy().astype("uint8"))
    
    • 1

    在这里插入图片描述

    3. 再次检查数据

    for image_batch, labels_batch in train_ds:
        print(image_batch.shape)
        print(labels_batch.shape)
        break
    
    • 1
    • 2
    • 3
    • 4
    (16, 224, 224, 3)
    (16,)
    
    • 1
    • 2
    • Image_batch是形状的张量(16,180,180,3)。这是一批形状180x180x3的16张图片(最后一维指的是彩色通道RGB)。
    • Label_batch是形状(16,)的张量,这些标签对应16张图片

    4. 配置数据集

    AUTOTUNE = tf.data.AUTOTUNE
    
    train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
    val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
    
    • 1
    • 2
    • 3
    • 4

    5. 归一化

    normalization_layer = layers.experimental.preprocessing.Rescaling(1./255)
    normalization_train_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
    val_ds = val_ds.map(lambda x, y: (normalization_layer(x), y))
    image_batch, labels_batch = next(iter(val_ds))
    first_image = image_batch[0]
    # 查看归一化后的数据
    print(np.min(first_image), np.max(first_image))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    0.0 0.9928046
    
    • 1

    三、构建VGG-19网络

    VGG优缺点分析:

    • VGG优点

    VGG的结构非常简洁,整个网络都使用了同样大小的卷积核尺寸(3x3)和最大池化尺寸(2x2)

    • VGG缺点

    1)训练时间过长,调参难度大。2)需要的存储容量大,不利于部署。例如存储VGG-16权重值文件的大小为500多MB,不利于安装到嵌入式系统中。

    1. 官方模型(已打包好)

    官网模型调用这块我放到后面几篇文章中,下面主要讲一下VGG-19

    # model = keras.applications.VGG19(weights='imagenet')
    # model.summary()
    
    • 1
    • 2

    2. 自建模型

    from tensorflow.keras import layers, models, Input
    from tensorflow.keras.models import Model
    from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout
    
    def VGG19(nb_classes, input_shape):
        input_tensor = Input(shape=input_shape)
        # 1st block
        x = Conv2D(64, (3,3), activation='relu', padding='same',name='block1_conv1')(input_tensor)
        x = Conv2D(64, (3,3), activation='relu', padding='same',name='block1_conv2')(x)
        x = MaxPooling2D((2,2), strides=(2,2), name = 'block1_pool')(x)
        # 2nd block
        x = Conv2D(128, (3,3), activation='relu', padding='same',name='block2_conv1')(x)
        x = Conv2D(128, (3,3), activation='relu', padding='same',name='block2_conv2')(x)
        x = MaxPooling2D((2,2), strides=(2,2), name = 'block2_pool')(x)
        # 3rd block
        x = Conv2D(256, (3,3), activation='relu', padding='same',name='block3_conv1')(x)
        x = Conv2D(256, (3,3), activation='relu', padding='same',name='block3_conv2')(x)
        x = Conv2D(256, (3,3), activation='relu', padding='same',name='block3_conv3')(x)
        x = Conv2D(256, (3,3), activation='relu', padding='same',name='block3_conv4')(x)
        x = MaxPooling2D((2,2), strides=(2,2), name = 'block3_pool')(x)
        # 4th block
        x = Conv2D(512, (3,3), activation='relu', padding='same',name='block4_conv1')(x)
        x = Conv2D(512, (3,3), activation='relu', padding='same',name='block4_conv2')(x)
        x = Conv2D(512, (3,3), activation='relu', padding='same',name='block4_conv3')(x)
        x = Conv2D(512, (3,3), activation='relu', padding='same',name='block4_conv4')(x)
        x = MaxPooling2D((2,2), strides=(2,2), name = 'block4_pool')(x)
        # 5th block
        x = Conv2D(512, (3,3), activation='relu', padding='same',name='block5_conv1')(x)
        x = Conv2D(512, (3,3), activation='relu', padding='same',name='block5_conv2')(x)
        x = Conv2D(512, (3,3), activation='relu', padding='same',name='block5_conv3')(x)
        x = Conv2D(512, (3,3), activation='relu', padding='same',name='block5_conv4')(x)
        x = MaxPooling2D((2,2), strides=(2,2), name = 'block5_pool')(x)
        # full connection
        x = Flatten()(x)
        x = Dense(4096, activation='relu',  name='fc1')(x)
        x = Dense(4096, activation='relu', name='fc2')(x)
        output_tensor = Dense(nb_classes, activation='softmax', name='predictions')(x)
    
        model = Model(input_tensor, output_tensor)
        return model
    
    model=VGG19(1000, (img_width, img_height, 3))
    model.summary()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    Model: "model"
    _________________________________________________________________
    Layer (type)                 Output Shape              Param #   
    =================================================================
    input_1 (InputLayer)         [(None, 224, 224, 3)]     0         
    _________________________________________________________________
    block1_conv1 (Conv2D)        (None, 224, 224, 64)      1792      
    _________________________________________________________________
    block1_conv2 (Conv2D)        (None, 224, 224, 64)      36928     
    _________________________________________________________________
    block1_pool (MaxPooling2D)   (None, 112, 112, 64)      0         
    _________________________________________________________________
    block2_conv1 (Conv2D)        (None, 112, 112, 128)     73856     
    _________________________________________________________________
    block2_conv2 (Conv2D)        (None, 112, 112, 128)     147584    
    _________________________________________________________________
    block2_pool (MaxPooling2D)   (None, 56, 56, 128)       0         
    _________________________________________________________________
    block3_conv1 (Conv2D)        (None, 56, 56, 256)       295168    
    _________________________________________________________________
    block3_conv2 (Conv2D)        (None, 56, 56, 256)       590080    
    _________________________________________________________________
    block3_conv3 (Conv2D)        (None, 56, 56, 256)       590080    
    _________________________________________________________________
    block3_conv4 (Conv2D)        (None, 56, 56, 256)       590080    
    _________________________________________________________________
    block3_pool (MaxPooling2D)   (None, 28, 28, 256)       0         
    _________________________________________________________________
    block4_conv1 (Conv2D)        (None, 28, 28, 512)       1180160   
    _________________________________________________________________
    block4_conv2 (Conv2D)        (None, 28, 28, 512)       2359808   
    _________________________________________________________________
    block4_conv3 (Conv2D)        (None, 28, 28, 512)       2359808   
    _________________________________________________________________
    block4_conv4 (Conv2D)        (None, 28, 28, 512)       2359808   
    _________________________________________________________________
    block4_pool (MaxPooling2D)   (None, 14, 14, 512)       0         
    _________________________________________________________________
    block5_conv1 (Conv2D)        (None, 14, 14, 512)       2359808   
    _________________________________________________________________
    block5_conv2 (Conv2D)        (None, 14, 14, 512)       2359808   
    _________________________________________________________________
    block5_conv3 (Conv2D)        (None, 14, 14, 512)       2359808   
    _________________________________________________________________
    block5_conv4 (Conv2D)        (None, 14, 14, 512)       2359808   
    _________________________________________________________________
    block5_pool (MaxPooling2D)   (None, 7, 7, 512)         0         
    _________________________________________________________________
    flatten (Flatten)            (None, 25088)             0         
    _________________________________________________________________
    fc1 (Dense)                  (None, 4096)              102764544 
    _________________________________________________________________
    fc2 (Dense)                  (None, 4096)              16781312  
    _________________________________________________________________
    predictions (Dense)          (None, 1000)              4097000   
    =================================================================
    Total params: 143,667,240
    Trainable params: 143,667,240
    Non-trainable params: 0
    _________________________________________________________________
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60

    3. 网络结构图

    结构说明:

    • 16个卷积层(Convolutional Layer),分别用blockX_convX表示
    • 3个全连接层(Fully connected Layer),分别用fcXpredictions表示
    • 5个池化层(Pool layer),分别用blockX_pool表示

    VGG-19包含了19个隐藏层(16个卷积层和3个全连接层),故称为VGG-19

    **在这里插入图片描述
    **

    四、编译

    在准备对模型进行训练之前,还需要再对其进行一些设置。以下内容是在模型的编译步骤中添加的:

    • 损失函数(loss):用于衡量模型在训练期间的准确率。
    • 优化器(optimizer):决定模型如何根据其看到的数据和自身的损失函数进行更新。
    • 指标(metrics):用于监控训练和测试步骤。以下示例使用了准确率,即被正确分类的图像的比率。
    # 设置优化器
    opt = tf.keras.optimizers.Adam(learning_rate=1e-4)
    
    model.compile(optimizer=opt,
                  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
                  metrics=['accuracy'])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    五、训练模型

    epochs = 10
    
    history = model.fit(
        train_ds,
        validation_data=val_ds,
        epochs=epochs
    )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    Epoch 1/10
    16/16 [==============================] - 21s 274ms/step - loss: 5.4494 - accuracy: 0.1508 - val_loss: 6.8600 - val_accuracy: 0.0714
    Epoch 2/10
    16/16 [==============================] - 2s 130ms/step - loss: 1.7976 - accuracy: 0.3174 - val_loss: 6.8402 - val_accuracy: 0.3929
    Epoch 3/10
    16/16 [==============================] - 2s 139ms/step - loss: 1.4882 - accuracy: 0.4201 - val_loss: 6.8453 - val_accuracy: 0.5357
    Epoch 4/10
    16/16 [==============================] - 2s 135ms/step - loss: 1.1548 - accuracy: 0.5917 - val_loss: 6.8551 - val_accuracy: 0.3571
    Epoch 5/10
    16/16 [==============================] - 2s 139ms/step - loss: 1.0376 - accuracy: 0.6267 - val_loss: 6.8421 - val_accuracy: 0.4286
    Epoch 6/10
    16/16 [==============================] - 2s 136ms/step - loss: 1.0189 - accuracy: 0.5942 - val_loss: 6.8277 - val_accuracy: 0.5714
    Epoch 7/10
    16/16 [==============================] - 2s 133ms/step - loss: 0.6873 - accuracy: 0.7761 - val_loss: 6.8382 - val_accuracy: 0.6429
    Epoch 8/10
    16/16 [==============================] - 2s 128ms/step - loss: 0.3739 - accuracy: 0.9019 - val_loss: 6.8109 - val_accuracy: 0.5357
    Epoch 9/10
    16/16 [==============================] - 2s 128ms/step - loss: 0.3761 - accuracy: 0.8547 - val_loss: 6.8101 - val_accuracy: 0.6429
    Epoch 10/10
    16/16 [==============================] - 2s 129ms/step - loss: 0.1258 - accuracy: 0.9713 - val_loss: 6.7796 - val_accuracy: 0.8929
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    六、模型评估

    acc = history.history['accuracy']
    val_acc = history.history['val_accuracy']
    
    loss = history.history['loss']
    val_loss = history.history['val_loss']
    
    epochs_range = range(epochs)
    
    plt.figure(figsize=(12, 4))
    plt.subplot(1, 2, 1)
    plt.plot(epochs_range, acc, label='Training Accuracy')
    plt.plot(epochs_range, val_acc, label='Validation Accuracy')
    plt.legend(loc='lower right')
    plt.title('Training and Validation Accuracy')
    
    plt.subplot(1, 2, 2)
    plt.plot(epochs_range, loss, label='Training Loss')
    plt.plot(epochs_range, val_loss, label='Validation Loss')
    plt.legend(loc='upper right')
    plt.title('Training and Validation Loss')
    plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    在这里插入图片描述

    七、保存and加载模型

    # 保存模型
    model.save('model/my_model.h5')
    # 加载模型
    new_model = keras.models.load_model('model/my_model.h5')
    
    • 1
    • 2
    • 3
    • 4

    八、预测

    # 采用加载的模型(new_model)来看预测结果
    
    plt.figure(figsize=(10, 5))  # 图形的宽为10高为5
    
    for images, labels in val_ds.take(1):
        for i in range(8):
            ax = plt.subplot(2, 4, i + 1)  
            
            # 显示图片
            plt.imshow(images[i])
            
            # 需要给图片增加一个维度
            img_array = tf.expand_dims(images[i], 0) 
            
            # 使用模型预测图片中的人物
            predictions = new_model.predict(img_array)
            plt.title(class_names[np.argmax(predictions)])
    
            plt.axis("off")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    在这里插入图片描述

  • 相关阅读:
    vue中使用xlsx插件导出多sheet excel实现方法
    LearnOpenGL1.3:着色器
    第三章-内存管理
    C++头文件
    《第一行代码》Android (第3版)笔记
    影视广告创意与制作(二)
    stm32----SPI协议
    Java面向对象编程
    Spring
    ES系列二之常见问题解决
  • 原文地址:https://blog.csdn.net/weixin_45822638/article/details/134520912