• 365天深度学习训练营-第7周:咖啡豆识别


    目录

    一、前言

    二、我的环境

    三、代码实现

     四、VGG-16框架

     五、LeNet5模型

    六、模型改进


    一、前言

    1. >- **🍨 本文为[🔗365天深度学习训练营](https://mp.weixin.qq.com/s/xLjALoOD8HPZcH563En8bQ) 中的学习记录博客**
    2. >- **🍦 参考文章:365天深度学习训练营-第7周:咖啡豆识别(训练营内部成员可读)**
    3. >- **🍖 原作者:[K同学啊|接辅导、项目定制](https://mtyjkh.blog.csdn.net/)**
    1. ● 难度:夯实基础⭐⭐
    2. ● 语言:Python3、TensorFlow2
    3. ● 时间:95-99
    4. 🍺 要求:
    5. 1. 自己搭建VGG-16网络框架
    6. 2. 调用官方的VGG-16网络框架
    7. 🍻 拔高(可选):
    8. 1. 验证集准确率达到100%
    9. 2. 使用PPT画出VGG-16算法框架图(发论文需要这项技能)
    10. 🔎 探索(难度有点大)
    11. 1. 在不影响准确率的前提下轻量化模型
    12. ○ 目前VGG16的Total params是134,276,932

    二、我的环境

    语言环境:Python3.7

    编译器:jupyter notebook

    深度学习环境:TensorFlow2

    三、代码实现

    1. import tensorflow as tf
    2. gpus = tf.config.list_physical_devices("GPU")
    3. if gpus:
    4. tf.config.experimental.set_memory_growth(gpus[0], True) #设置GPU显存用量按需使用
    5. tf.config.set_visible_devices([gpus[0]],"GPU")
    6. from tensorflow.keras import layers
    7. import numpy as np
    8. import matplotlib.pyplot as plt
    9. import pathlib
    10. data_dir = "./49-data/"
    11. data_dir = pathlib.Path(data_dir)
    12. image_count = len(list(data_dir.glob('*/*.png')))
    13. print("图片总数为:",image_count)
    14. batch_size = 32
    15. img_height = 224
    16. img_width = 224
    17. """
    18. 关于image_dataset_from_directory()的详细介绍可以参考文章:https://mtyjkh.blog.csdn.net/article/details/117018789
    19. """
    20. train_ds = tf.keras.preprocessing.image_dataset_from_directory(
    21. data_dir,
    22. validation_split=0.2,
    23. subset="training",
    24. seed=123,
    25. image_size=(img_height, img_width),
    26. batch_size=batch_size)
    27. """
    28. 关于image_dataset_from_directory()的详细介绍可以参考文章:https://mtyjkh.blog.csdn.net/article/details/117018789
    29. """
    30. val_ds = tf.keras.preprocessing.image_dataset_from_directory(
    31. data_dir,
    32. validation_split=0.2,
    33. subset="validation",
    34. seed=123,
    35. image_size=(img_height, img_width),
    36. batch_size=batch_size)
    37. class_names = train_ds.class_names
    38. print(class_names)
    39. plt.figure(figsize=(10, 4)) # 图形的宽为10高为5
    40. for images, labels in train_ds.take(1):
    41. for i in range(10):
    42. ax = plt.subplot(2, 5, i + 1)
    43. plt.imshow(images[i].numpy().astype("uint8"))
    44. plt.title(class_names[labels[i]])
    45. plt.axis("off")
    46. for image_batch, labels_batch in train_ds:
    47. print(image_batch.shape)
    48. print(labels_batch.shape)
    49. break
    50. AUTOTUNE = tf.data.AUTOTUNE
    51. train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
    52. val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
    53. normalization_layer = layers.experimental.preprocessing.Rescaling(1./255)
    54. train_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
    55. val_ds = val_ds.map(lambda x, y: (normalization_layer(x), y))
    56. image_batch, labels_batch = next(iter(val_ds))
    57. first_image = image_batch[0]
    58. # 查看归一化后的数据
    59. print(np.min(first_image), np.max(first_image))
    60. # model = tf.keras.applications.VGG16(weights='imagenet')
    61. # model.summary()
    62. from tensorflow.keras import Input
    63. from tensorflow.keras.models import Model
    64. from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten
    65. def VGG16(nb_classes, input_shape):
    66. input_tensor = Input(shape=input_shape)
    67. # 1st block
    68. x = Conv2D(64, (3,3), activation='relu', padding='same',name='block1_conv1')(input_tensor)
    69. x = Conv2D(64, (3,3), activation='relu', padding='same',name='block1_conv2')(x)
    70. x = MaxPooling2D((2,2), strides=(2,2), name = 'block1_pool')(x)
    71. # 2nd block
    72. x = Conv2D(128, (3,3), activation='relu', padding='same',name='block2_conv1')(x)
    73. x = Conv2D(128, (3,3), activation='relu', padding='same',name='block2_conv2')(x)
    74. x = MaxPooling2D((2,2), strides=(2,2), name = 'block2_pool')(x)
    75. # 3rd block
    76. x = Conv2D(256, (3,3), activation='relu', padding='same',name='block3_conv1')(x)
    77. x = Conv2D(256, (3,3), activation='relu', padding='same',name='block3_conv2')(x)
    78. x = Conv2D(256, (3,3), activation='relu', padding='same',name='block3_conv3')(x)
    79. x = MaxPooling2D((2,2), strides=(2,2), name = 'block3_pool')(x)
    80. # 4th block
    81. x = Conv2D(512, (3,3), activation='relu', padding='same',name='block4_conv1')(x)
    82. x = Conv2D(512, (3,3), activation='relu', padding='same',name='block4_conv2')(x)
    83. x = Conv2D(512, (3,3), activation='relu', padding='same',name='block4_conv3')(x)
    84. x = MaxPooling2D((2,2), strides=(2,2), name = 'block4_pool')(x)
    85. # 5th block
    86. x = Conv2D(512, (3,3), activation='relu', padding='same',name='block5_conv1')(x)
    87. x = Conv2D(512, (3,3), activation='relu', padding='same',name='block5_conv2')(x)
    88. x = Conv2D(512, (3,3), activation='relu', padding='same',name='block5_conv3')(x)
    89. x = MaxPooling2D((2,2), strides=(2,2), name = 'block5_pool')(x)
    90. # full connection
    91. x = Flatten()(x)
    92. x = Dense(4096, activation='relu', name='fc1')(x)
    93. x = Dense(4096, activation='relu', name='fc2')(x)
    94. output_tensor = Dense(nb_classes, activation='softmax', name='predictions')(x)
    95. model = Model(input_tensor, output_tensor)
    96. return model
    97. model=VGG16(len(class_names), (img_width, img_height, 3))
    98. model.summary()
    99. # 设置初始学习率
    100. initial_learning_rate = 1e-4
    101. lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
    102. initial_learning_rate,
    103. decay_steps=30, # 敲黑板!!!这里是指 steps,不是指epochs
    104. decay_rate=0.92, # lr经过一次衰减就会变成 decay_rate*lr
    105. staircase=True)
    106. # 设置优化器
    107. opt = tf.keras.optimizers.Adam(learning_rate=initial_learning_rate)
    108. model.compile(optimizer=opt,
    109. loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    110. metrics=['accuracy'])
    111. epochs = 20
    112. history = model.fit(
    113. train_ds,
    114. validation_data=val_ds,
    115. epochs=epochs
    116. )
    117. acc = history.history['accuracy']
    118. val_acc = history.history['val_accuracy']
    119. loss = history.history['loss']
    120. val_loss = history.history['val_loss']
    121. epochs_range = range(epochs)
    122. plt.figure(figsize=(12, 4))
    123. plt.subplot(1, 2, 1)
    124. plt.plot(epochs_range, acc, label='Training Accuracy')
    125. plt.plot(epochs_range, val_acc, label='Validation Accuracy')
    126. plt.legend(loc='lower right')
    127. plt.title('Training and Validation Accuracy')
    128. plt.subplot(1, 2, 2)
    129. plt.plot(epochs_range, loss, label='Training Loss')
    130. plt.plot(epochs_range, val_loss, label='Validation Loss')
    131. plt.legend(loc='upper right')
    132. plt.title('Training and Validation Loss')
    133. plt.show()

     

     

     四、VGG-16框架

     

     五、LeNet5模型

    1. def LeNet5(nb_classes, input_shape):
    2. input_tensor = Input(shape=input_shape)
    3. # 1st block
    4. x = Conv2D(6, (5,5), activation='sigmoid', padding='same',name='block1_conv1')(input_tensor)
    5. #x = Conv2D(64, (3,3), activation='relu', padding='same',name='block1_conv2')(x)
    6. x = MaxPooling2D((2,2), strides=(2,2), name = 'block1_pool')(x)
    7. x = Conv2D(16, (5,5), activation='sigmoid', padding='same',name='block2_conv1')(x)
    8. x =MaxPooling2D((2,2),strides=(2,2),name = 'block2_pool')(x)
    9. # full connection
    10. x = Flatten()(x)
    11. x = Dense(120, activation='sigmoid', name='fc1')(x)
    12. x = Dense(84, activation='sigmoid', name='fc2')(x)
    13. output_tensor = Dense(nb_classes, activation='softmax', name='predictions')(x)
    14. model = Model(input_tensor, output_tensor)
    15. return model
    16. model=LeNet5(len(class_names), (img_width, img_height, 3))
    17. model.summary()

    效果极差,下次一定不用 

    六、模型改进

    1、调低学习率(或按迭代次数衰减)
    2、调整参数的初始化方法
    3、调整输入数据的标准化方法
    4、修改Loss函数
    5、增加正则化
    6、使用BN/GN层(中间层数据的标准化)
    7、使用dropout

    优化1

    1. model = keras.models.Sequential()
    2. # 优化 增加L2正则化
    3. model.add(keras.layers.Conv2D(64, (3, 3), padding='same', kernel_regularizer=keras.regularizers.l2(weight_decay)))
    4. model.add(keras.layers.Activation('relu'))
    5. # 优化 添加BN层和Dropout
    6. model.add(keras.layers.BatchNormalization())
    7. model.add(keras.layers.Dropout(0.3))
    8. model.add(keras.layers.Conv2D(64, (3, 3), padding='same', activation='relu'))
    9. model.add(keras.layers.MaxPooling2D(pool_size=(2, 2), strides=2))
    10. model.add(keras.layers.Conv2D(128, (3, 3), padding='same', activation='relu'))
    11. model.add(keras.layers.Conv2D(128, (3, 3), padding='same', activation='relu'))
    12. model.add(keras.layers.MaxPooling2D(pool_size=(2, 2), strides=2))
    13. model.add(keras.layers.Conv2D(256, (3, 3), padding='same', activation='relu'))
    14. model.add(keras.layers.Conv2D(256, (3, 3), padding='same', activation='relu'))
    15. model.add(keras.layers.MaxPooling2D(pool_size=(2, 2), strides=2))
    16. model.add(keras.layers.Conv2D(512, (3, 3), padding='same', activation='relu'))
    17. model.add(keras.layers.Conv2D(512, (3, 3), padding='same', activation='relu'))
    18. model.add(keras.layers.MaxPooling2D(pool_size=(2, 2), strides=2))
    19. model.add(keras.layers.Conv2D(512, (3, 3), padding='same', activation='relu'))
    20. model.add(keras.layers.Conv2D(512, (3, 3), padding='same', activation='relu'))
    21. model.add(keras.layers.MaxPooling2D(pool_size=(2, 2), strides=2))
    22. model.add(keras.layers.Flatten())
    23. model.add(keras.layers.Dense(256, activation='relu')) # VGG16为4096
    24. model.add(keras.layers.Dense(128, activation='relu')) # VGG16为4096
    25. model.add(keras.layers.Dense(num_classes, activation='softmax')) # VGG16为1000

    优化2

    1. model = models.Sequential([
    2. layers.experimental.preprocessing.Rescaling( 1. ,input_shape=(img_height, img_width, 3)),
    3. layers.Conv2D(filters=64, kernel_size=(3, 3), padding='same'), # 卷积层1
    4. #layers.BatchNormalization(), # BN层1
    5. layers.Activation('relu'), # 激活层1
    6. layers.Conv2D(filters=64, kernel_size=(3, 3), padding='same', ),
    7. #layers.BatchNormalization(), # BN层1
    8. layers.Activation('relu') , # 激活层1
    9. layers.MaxPool2D(pool_size=(2, 2), strides=2, padding='same'),
    10. #layers.Dropout(0.2), # dropout层
    11. #
    12. layers.Conv2D(filters=128, kernel_size=(3, 3), padding='same'),
    13. #layers.BatchNormalization(), # BN层1
    14. layers.Activation('relu'), # 激活层1
    15. layers.Conv2D(filters=128, kernel_size=(3, 3), padding='same'),
    16. #layers.BatchNormalization(), # BN层1
    17. layers.Activation('relu'), # 激活层1
    18. layers.MaxPool2D(pool_size=(2, 2), strides=2, padding='same'),
    19. #layers.Dropout(0.2), # dropout层
    20. #
    21. layers.Conv2D(filters=256, kernel_size=(3, 3), padding='same'),
    22. #layers.BatchNormalization() , # BN层1
    23. layers.Activation('relu'), # 激活层1
    24. layers.Conv2D(filters=256, kernel_size=(3, 3), padding='same'),
    25. #layers.BatchNormalization() , # BN层1
    26. layers.Activation('relu') , # 激活层1
    27. layers.Conv2D(filters=256, kernel_size=(3, 3), padding='same'),
    28. # layers.BatchNormalization(),
    29. layers.Activation('relu'),
    30. layers.MaxPool2D(pool_size=(2, 2), strides=2, padding='same'),
    31. #layers.Dropout(0.2),
    32. #
    33. layers.Conv2D(filters=512, kernel_size=(3, 3), padding='same'),
    34. # layers.BatchNormalization() , # BN层1
    35. layers.Activation('relu') , # 激活层1
    36. layers.Conv2D(filters=512, kernel_size=(3, 3), padding='same'),
    37. #layers.BatchNormalization() , # BN层1
    38. layers.Activation('relu'), # 激活层1
    39. layers.Conv2D(filters=512, kernel_size=(3, 3), padding='same'),
    40. #layers.BatchNormalization(),
    41. layers.Activation('relu'),
    42. layers.MaxPool2D(pool_size=(2, 2), strides=2, padding='same'),
    43. #layers.Dropout(0.2),
    44. #
    45. layers.Conv2D(filters=512, kernel_size=(3, 3), padding='same'),
    46. # layers.BatchNormalization() , # BN层1
    47. layers.Activation('relu'), # 激活层1
    48. layers.Conv2D(filters=512, kernel_size=(3, 3), padding='same'),
    49. #layers.BatchNormalization(), # BN层1
    50. layers.Activation('relu'), # 激活层1
    51. layers.Conv2D(filters=512, kernel_size=(3, 3), padding='same'),
    52. # layers.BatchNormalization(),
    53. layers.Activation('relu'),
    54. layers.MaxPool2D(pool_size=(2, 2), strides=2, padding='same'),
    55. #layers.Dropout(0.2),
    56. layers.Flatten(), # Flatten层,连接卷积层与全连接层
    57. layers.Dense(4096, activation='relu'), # 全连接层,特征进一步提取
    58. layers.Dense(4096, activation='relu'), # 全连接层,特征进一步提取
    59. layers.Dense(len(class_names),activation='softmax') # 输出层,输出预期结果
    60. ])
    61. model.summary()

  • 相关阅读:
    排序算法之---归并排序
    HTTP请求方法
    醋氯芬酸小鼠血清白蛋白纳米粒Aceclofenac-MSA|利凡诺大鼠血清白蛋白纳米粒Ethacridine-RSA
    XiaodiSec day007 Learn Note 小迪安全学习笔记
    Vue——方法与事件、 样式绑定、数据绑定、面试题、笔试题
    SpringBoot - 实现启动时执行指定任务(CommandLineRunner、ApplicationRunner)
    #css 自定义checkbox样式解决方案#
    对线性插值的理解
    app拉新渠道整合 一手地推、网推拉新平台整理
    跨链桥已成行业最大安全隐患,为什么和怎么办
  • 原文地址:https://blog.csdn.net/m0_58585940/article/details/127973813