CNN人脸表情识别简单尝试

本文档介绍了使用CNN进行人脸表情识别的过程,包括数据集的处理、模型搭建、训练及评估。通过读取fer2013数据集,利用Pandas、cv2和Keras进行数据预处理和模型构建,并探讨了batch_size对训练的影响。
摘要由CSDN通过智能技术生成

CNN人脸表情识别简单尝试

目录

一:查看fer2013数据集(cvs格式)
二:使用Pandas读取csv
三:使用cv2查看其中一张图片
四:将数据集划分
五:将数据转换为数组(array)格式,否则keras会报错
六:使用matplotlib显示照片
七:搭建模型
八:查看模型结构图(使用pydot)
九:开始训练
十:使用matplotlib绘图查看结果
10.1:batch_size对于训练的影响
10.2:评估结果
总结
首先,下载fer2013数据集,
网址:https://www.kaggle.com/datasets/deadskull7/fer2013
使用pandas读取csv

import numpy as np
import pandas as pd
data = pd.read_csv('D:/code/fer2013.csv')
num_of_instances = len(data)#获取数据集的数量
print("数据集的数量为:",num_of_instances)

pixels = data['pixels']
emotions = data['emotion']
usages = data['Usage']

在这里插入图片描述
使用csv查看其中某一张照片

import cv2
img0 = list(map(eval,pixels[0].split(' ')))
np_img0 = np.asarray(img0)
img0 = np_img0.reshape(48,48)
import matplotlib.pyplot as plt
plt.imshow(img0,cmap = "gray")

在这里插入图片描述
划分数据集

emotions_Str = ['anger','disgust','fear','happy','neutral','sad','surprised']

在这里插入图片描述

from tensorflow.keras.utils import to_categorical
from PIL import Image
import os

num_classes = 7   #表情的类别数目
x_train,y_train,x_val,y_val,x_test,y_test = [],[],[],[],[],[]
from tqdm import tqdm
for i in tqdm(range(num_of_instances)):
    usages_name = usages[i]
    emotions_Str_Nmae = emotions_Str[emotions[i]]
    one_hot_label = to_categorical(emotions[i],num_classes) #标签转换为one-hot编码,以满足keras对于数据的要求
    img = list(map(eval,pixels[i].split(' ')))
    np_img = np.asarray(img)
    img = np_img.reshape(48,48)
    if usages[i] == 'Training':
        x_train.append(img)
        y_train.append(one_hot_label)
    elif usages[i] == 'PrivateTest':
        x_val.append(img)
        y_val.append(one_hot_label)
    else:
        x_test.append(img)
        y_test.append(one_hot_label)
    subfolder = os.path.join('D:/code/')
    if not os.path.exists(subfolder):
        os.makedirs(subfolder)
    im = Image.fromarray(img).convert('L')
    im.save(os.path.join(subfolder , (str(i)+'.jpg') ))

在这里插入图片描述
将数据转换为数组(array)格式,否则keras会报错

len(x_train)
x_train = np.array(x_train)
y_train = np.array(y_train)
x_train = x_train.reshape(-1,48,48,1)
x_test = np.array(x_test)
y_test = np.array(y_test)
x_test = x_test.reshape(-1,
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值