• 眼睛状态识别


    活动地址:CSDN21天学习挑战赛

    学习的最大理由是想摆脱平庸,早一天就多一份人生的精彩;迟一天就多一天平庸的困扰。各位小伙伴,如果您:
    想系统/深入学习某技术知识点…
    一个人摸索学习很难坚持,想组团高效学习…
    想写博客但无从下手,急需写作干货注入能量…
    热爱写作,愿意让自己成为更好的人…

    **

    创作计划

    **
    1,机缘

    A,眼睛状态识别项目中的经验分享
    B,日常学习过程中的记录
    C,通过眼睛状态识别进行技术交流

    2,收获

    A,获得了10粉丝的关注
    B,获得了20正向的赞、阅读量等
    C,认识了眼睛状态识别的同行

    3,日常

    1. 创作已经是我生活的一部分了
    2. 有限的时间下,周二、周四、周六进行创作,其余时间学习

    4,憧憬

    创作规划是设计眼睛识别的模型、对比官方模型,进一步理解卷积神经网络

    **

    学习计划

    **
    1,学习目标

    掌握动态学习率的设置、理解混淆矩阵

    2,学习内容

    A,设置数据集
    B,查看数据
    C,设置动态学习率

    3,学习时间

    周一至周五晚上 7 点—晚上9点
    周六下午 6 点-下午 9 点
    周日下午 6 点-下午 9 点

    4,学习产出

    技术笔记 2 遍
    CSDN技术博客 3 篇
    学习的vlog 视频 1 个

    **

    学习日记

    **
    1,学习知识点

    设置动态学习率、学习混淆矩阵

    2,学习遇到的问题

    混淆矩阵的理解

    3,学习的收获

    掌握了动态学习率的设置,理解了混淆矩阵

    4,实操

    import matplotlib.pyplot as plt
    from sklearn.metrics import confusion_matrix
    import seaborn as sns
    import pandas as pd
    
    # 支持中文
    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)
    
    import pathlib
    
    data_dir = "D:/BaiduNetdiskDownload/017_Eye_dataset"
    data_dir = pathlib.Path(data_dir)
    image_count = len(list(data_dir.glob('*/*')))
    
    print("图片总数为:",image_count)
    
    batch_size = 64
    img_height = 224
    img_width = 224
    
    train_ds = tf.keras.preprocessing.image_dataset_from_directory(
        data_dir,
        validation_split=0.2,
        subset="training",
        seed=12,
        image_size=(img_height, img_width),
        batch_size=batch_size)
    
    val_ds = tf.keras.preprocessing.image_dataset_from_directory(
        data_dir,
        validation_split=0.2,
        subset="validation",
        seed=12,
        image_size=(img_height, img_width),
        batch_size=batch_size)
    class_names = train_ds.class_names
    print(class_names)
    plt.figure(figsize=(10, 5))  # 图形的宽为10高为5
    plt.suptitle("数据展示")
    
     for images, labels in train_ds.take(1):
         for i in range(8):
             ax = plt.subplot(2, 4, i + 1)
    
             ax.patch.set_facecolor('yellow')
    
             plt.imshow(images[i].numpy().astype("uint8"))
             plt.title(class_names[labels[i]])
    
             plt.axis("off")
     plt.show()
    
    for image_batch, labels_batch in train_ds:
        print(image_batch.shape)
        print(labels_batch.shape)
        break
    AUTOTUNE = tf.data.AUTOTUNE
    
    train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
    val_ds   = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
    
    model = tf.keras.applications.VGG16()
    # 打印模型信息
    model.summary()
    # 设置初始学习率
    initial_learning_rate = 1e-4
    
    lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
            initial_learning_rate,
            decay_steps=20,      # 敲黑板!!!这里是指 steps,不是指epochs
            decay_rate=0.96,     # lr经过一次衰减就会变成 decay_rate*lr
            staircase=True)
    
    # 将指数衰减学习率送入优化器
    optimizer = tf.keras.optimizers.Adam(learning_rate=lr_schedule)
    model.compile(optimizer=optimizer,
                  loss     ='sparse_categorical_crossentropy',
                  metrics  =['accuracy'])
    epochs = 10
    
    history = model.fit(
        train_ds,
        validation_data=val_ds,
        epochs=epochs
    )
    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()
    #混淆矩阵
    # 定义一个绘制混淆矩阵图的函数
    def plot_cm(labels, predictions):
        # 生成混淆矩阵
        conf_numpy = confusion_matrix(labels, predictions)
        # 将矩阵转化为 DataFrame
        conf_df = pd.DataFrame(conf_numpy, index=class_names, columns=class_names)
    
        plt.figure(figsize=(8, 7))
    
        sns.heatmap(conf_df, annot=True, fmt="d", cmap="BuPu")
    
        plt.title('混淆矩阵', fontsize=15)
        plt.ylabel('真实值', fontsize=14)
        plt.xlabel('预测值', fontsize=14)
        plt.show()
    
    val_pre   = []
    val_label = []
    
    for images, labels in val_ds:#这里可以取部分验证数据(.take(1))生成混淆矩阵
        for image, label in zip(images, labels):
            # 需要给图片增加一个维度
            img_array = tf.expand_dims(image, 0)
            # 使用模型预测图片中的人物
            prediction = model.predict(img_array)
    
            val_pre.append(class_names[np.argmax(prediction)])
            val_label.append(class_names[label])
    plot_cm(val_label, val_pre)
    
    # 保存模型
    model.save('model/17_model.h5')
    # 加载模型
    new_model = tf.keras.models.load_model('model/17_model.h5')
    # 采用加载的模型(new_model)来看预测结果
    
    plt.figure(figsize=(10, 5))  # 图形的宽为10高为5
    plt.suptitle("预测结果展示")
    
    for images, labels in val_ds.take(1):
        for i in range(8):
            ax = plt.subplot(2, 4, i + 1)
    
            # 显示图片
            plt.imshow(images[i].numpy().astype("uint8"))
    
            # 需要给图片增加一个维度
            img_array = tf.expand_dims(images[i], 0)
    
            # 使用模型预测图片中的人物
            predictions = new_model.predict(img_array)
            plt.title(class_names[np.argmax(predictions)])
    
            plt.axis("off")
    plt.show()
    
    • 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
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174

    输出:在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    分析:通过对比训练集曲线与测试集曲线,可以看出无论是准确率还是损失率,训练集与测试集都十分吻合。说明没有出现过拟合现象。通过观察,使用模型预测的眼睛状态都是正确的,说明模型是有效的。

  • 相关阅读:
    Spring Boot 应用启动时 java.lang.reflect.InaccessibleObjectException 问题的解决
    【LeetCode-数组】--搜索插入位置
    【Springboot】整合wxjava实现 微信小程序:授权登录
    单片机为什么一直用C语言,不用其他编程语言?
    Java面试题汇总(持续更新.....)
    BOPPPS+课程思政教学模式在计算机导论课程中的应用
    C#语言async, await 简单介绍与实例(入门级)
    Centos安装openjdk11并配置JAVA_HOME
    Hold the door! 基于Django建立基础框架
    Node.js【Express 中间件(中间件的概念、Express 中间件的初体验、中间件的分类、自定义中间件)】
  • 原文地址:https://blog.csdn.net/misterfm/article/details/126228993