• AI计算机视觉进阶项目(一)——带口罩识别检测(3)


    独热编码官方合作微信:gldz_super

    本专栏《AI计算机视觉进阶项目》主要以计算机视觉实战项目为主,第一个项目为口罩检测:该项目将分为几个模块进行展示。本项目已完成链接:

    1.AI计算机视觉进阶项目(一)——带口罩识别检测(1)_AI炮灰的博客-CSDN博客

    2.AI计算机视觉进阶项目(一)——带口罩识别检测(2)_AI炮灰的博客-CSDN博客

    一、本节任务

    1. 对带口罩识别检测(2)中生成的npz文件数据进行读取
    2. one_hot独热编码
    3. 分为train和test数据
    4. 搭建CNN模型
    5. 训练模型
    6. 保存模型

    二、任务实现

    2.1模块导入

    1. # 模块导入
    2. import numpy as np
    3. from sklearn.preprocessing import OneHotEncoder
    4. from sklearn.model_selection import train_test_split
    5. import tensorflow as tf
    6. from tensorflow.python.keras import layers, Sequential
    7. import pandas as pd
    8. import matplotlib.pyplot as plt

    2.2 数据读取

    1. # 1.读取NPZ文件
    2. arr = np.load('./imageData.npz')
    3. img_list = arr['arr_0']
    4. label_list = arr['arr_1']
    5. print(img_list.shape, label_list.shape) # (5320, 100, 100, 3) (5320,)

    2.3独热编码

    1. # 2.one_hot独热编码:将label的类别变为二进制独热编码格式这样类别直接的距离更加合理
    2. print(np.unique(label_list)) # 查看所有的类别
    3. # 实例化
    4. onehot = OneHotEncoder()
    5. # 编码:并把标签label_list由一维变为二维
    6. y_onehot = onehot.fit_transform(label_list.reshape(-1, 1)) # label_list由(53201)变为(5320, 3)
    7. print(y_onehot.shape)
    8. # 将y_onehot变为矩阵
    9. y_onehot_arr = y_onehot.toarray()
    10. print(y_onehot_arr)

    2.4数据集划分

    1. # 3.分为train和test数据
    2. x_train, x_test, y_train, y_test = train_test_split(img_list, y_onehot_arr, test_size=0.2, random_state=42)
    3. print(x_train.shape, x_test.shape, y_train.shape, y_test.shape)

    2.5模型搭建

    1. # 4.搭建模型
    2. model = Sequential([
    3. layers.Conv2D(16, 3, padding='same', input_shape=(100, 100, 3), activation='relu'),
    4. layers.MaxPool2D(),
    5. layers.Conv2D(32, 3, padding='same', activation='relu'),
    6. layers.MaxPool2D(),
    7. layers.Conv2D(64, 3, padding='same', activation='relu'),
    8. layers.MaxPool2D(),
    9. layers.Flatten(),
    10. layers.Dense(166, activation='relu'),
    11. layers.Dense(22, activation='relu'),
    12. layers.Dense(3, activation='sigmoid')
    13. ])
    14. # 编译模型
    15. model.compile(
    16. # optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
    17. # loss=tf.keras.losses.categorical_crossentroy,
    18. # metrics=['accurate']
    19. optimizer='adam',
    20. loss='categorical_crossentropy',
    21. metrics=['accuracy']
    22. )
    23. # 预览模型
    24. model.summary()

     2.6查看模型训练效果

    1. # 5.训练模型
    2. history = model.fit(
    3. x_train,
    4. y_train,
    5. validation_data=(x_test, y_test),
    6. batch_size=30,
    7. epochs=10
    8. )
    9. # 查看训练效果
    10. history_pd = pd.DataFrame(history.history)
    11. print(history_pd)

    2.7 画出损失和精确度

    1. # 查看损失
    2. plt.plot(history_pd['loss'])
    3. plt.plot(history_pd['val_loss'])
    4. plt.title('Model loss')
    5. plt.xlabel('epoch')
    6. plt.ylabel('loss')
    7. plt.legend(['train_set', 'test_set'], loc='upper right')
    8. plt.show()
    9. # 查看准确率
    10. # 查看损失
    11. plt.plot(history_pd['accuracy'])
    12. plt.plot(history_pd['val_accuracy'])
    13. plt.title('Model accuracy')
    14. plt.xlabel('epoch')
    15. plt.ylabel('accuracy')
    16. plt.legend(['train_set', 'test_set'], loc='upper right')
    17. plt.show()

     

     2.8保存模型

    1. # 6.保存模型:为了防止每次使用都需进行训练
    2. model.save('./face_mask_model.h5')

     保存模型后后面使用就不需要每次进行训练,直接可以使用保存后得模型

    三、完整代码

    1. """
    2. 流程:
    3. 1.读取NPZ文件
    4. 2.one_hot独热编码
    5. 3.分为train和test数据
    6. 4.搭建CNN模型
    7. 5.训练模型
    8. 6.保存模型
    9. """
    10. # 模块导入
    11. import numpy as np
    12. from sklearn.preprocessing import OneHotEncoder
    13. from sklearn.model_selection import train_test_split
    14. from tensorflow.python.keras import layers, Sequential
    15. import pandas as pd
    16. import matplotlib.pyplot as plt
    17. # 1.读取NPZ文件
    18. arr = np.load('./imageData.npz')
    19. img_list = arr['arr_0']
    20. label_list = arr['arr_1']
    21. print(img_list.shape, label_list.shape) # (5320, 100, 100, 3) (5320,)
    22. # 2.one_hot独热编码:将label的类别变为二进制独热编码格式这样类别直接的距离更加合理
    23. print(np.unique(label_list)) # 查看所有的类别
    24. # 实例化
    25. onehot = OneHotEncoder()
    26. # 编码:并把标签label_list由一维变为二维
    27. y_onehot = onehot.fit_transform(label_list.reshape(-1, 1)) # label_list由(53201)变为(5320, 3)
    28. print(y_onehot.shape)
    29. # 将y_onehot变为矩阵
    30. y_onehot_arr = y_onehot.toarray()
    31. print(y_onehot_arr)
    32. # 3.分为train和test数据
    33. x_train, x_test, y_train, y_test = train_test_split(img_list, y_onehot_arr, test_size=0.2, random_state=42)
    34. print(x_train.shape, x_test.shape, y_train.shape, y_test.shape)
    35. # 4.搭建模型
    36. model = Sequential([
    37. layers.Conv2D(16, 3, padding='same', input_shape=(100, 100, 3), activation='relu'),
    38. layers.MaxPool2D(),
    39. layers.Conv2D(32, 3, padding='same', activation='relu'),
    40. layers.MaxPool2D(),
    41. layers.Conv2D(64, 3, padding='same', activation='relu'),
    42. layers.MaxPool2D(),
    43. layers.Flatten(),
    44. layers.Dense(166, activation='relu'),
    45. layers.Dense(22, activation='relu'),
    46. layers.Dense(3, activation='sigmoid')
    47. ])
    48. # 编译模型
    49. model.compile(
    50. # optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
    51. # loss=tf.keras.losses.categorical_crossentroy,
    52. # metrics=['accurate']
    53. optimizer='adam',
    54. loss='categorical_crossentropy',
    55. metrics=['accuracy']
    56. )
    57. # 预览模型
    58. model.summary()
    59. # 5.训练模型
    60. history = model.fit(
    61. x_train,
    62. y_train,
    63. validation_data=(x_test, y_test),
    64. batch_size=30,
    65. epochs=10
    66. )
    67. # 查看训练效果
    68. history_pd = pd.DataFrame(history.history)
    69. print(history_pd)
    70. # 查看损失
    71. plt.plot(history_pd['loss'])
    72. plt.plot(history_pd['val_loss'])
    73. plt.title('Model loss')
    74. plt.xlabel('epoch')
    75. plt.ylabel('loss')
    76. plt.legend(['train_set', 'test_set'], loc='upper right')
    77. plt.show()
    78. # 查看准确率
    79. # 查看损失
    80. plt.plot(history_pd['accuracy'])
    81. plt.plot(history_pd['val_accuracy'])
    82. plt.title('Model accuracy')
    83. plt.xlabel('epoch')
    84. plt.ylabel('accuracy')
    85. plt.legend(['train_set', 'test_set'], loc='upper right')
    86. plt.show()
    87. # 6.保存模型:为了防止每次使用都需进行训练
    88. model.save('./face_mask_model.h5')

  • 相关阅读:
    Maven项目,进行编译,使用idea的 编译功能,就是正常的,但是在终端中执行 mvn clean compile 报错
    万亿数据秒级响应,Apache Doris 在360 数科实时数仓中的应用
    充值ChatGPTPLUS开卡平台Fomepay和WildCard选哪个虚拟信用卡(纯分享)
    Bridge 桥接模式简介与 C# 示例【结构型2】【设计模式来了_7】
    CentOS7系统及内核升级
    对软件重构的认识
    为什么Proteus串口无法正常显示
    Spring Boot 发送邮件
    蓝桥杯备赛经验分享---如何拿蓝桥国一?
    NVM Express® Zoned Namespace Command Set Specification翻译
  • 原文地址:https://blog.csdn.net/bigData1994pb/article/details/126450589