from sklearn.metrics import confusion_matrix
from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
# =========================================================================================
# 比如这里我的labels列表
labels = ['Anger', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']
#################################导入模型
import cv2
import tensorflow as tf
from DeepFace import functions,analyze
import numpy as nptf_version = int(tf.__version__.split(".")[0])
print('tf_version:',tf_version)
if tf_version == 1:import kerasfrom keras.models import Model, Sequentialfrom keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, Flatten, Dense, Dropoutfrom keras.optimizers import SGDfrom keras.preprocessing.image import ImageDataGenerator
elif tf_version == 2:from tensorflow import kerasfrom tensorflow.keras.models import Model, Sequentialfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, Flatten, Dense, Dropoutfrom tensorflow.keras.optimizers import SGDfrom tensorflow.keras.preprocessing.image import ImageDataGeneratornum_classes = 7model = Sequential()#1st convolution layer
model.add(Conv2D(64, (5, 5), activation='relu', input_shape=(48,48,1)))
model.add(MaxPooling2D(pool_size=(5,5), strides=(2, 2)))#2nd convolution layer
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(AveragePooling2D(pool_size=(3,3), strides=(2, 2)))#3rd convolution layer
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(AveragePooling2D(pool_size=(3,3), strides=(2, 2)))model.add(Flatten())#fully connected neural networks
model.add(Dense(1024, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(1024, activation='relu'))
model.add(Dropout(0.2))model.add(Dense(num_classes, activation='softmax'))train_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory('data/train',target_size=(48, 48),batch_size=32,color_mode="grayscale",class_mode='categorical')
test_datagen = ImageDataGenerator(rescale=1./255)
# validation_generator = test_datagen.flow_from_directory(
#         'data/val',
#         target_size=(48, 48),
#         batch_size=32,
#         color_mode="grayscale",
#         class_mode = 'categorical')
test_generator = test_datagen.flow_from_directory('dataset/test',target_size=(48, 48),# shuffle = False ,#随机打乱默认为true# batch_size=1235,color_mode="grayscale",class_mode = 'categorical')
sgd = SGD(learning_rate=0.001, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd,metrics=['accuracy'])
model.summary()
# model.fit_generator(train_generator, epochs=50,validation_data=validation_generator)
model.load_weights(r'C:\Users\zhoutao\.deepface\weights\facial_expression_model_weights.h5')
################################
# test_steps_per_epoch = np.math.ceil(test_generator.samples / test_generator.batch_size)
# predictions = model.predict_generator(test_generator, steps=test_steps_per_epoch)
predictions = model.predict_generator(test_generator)
# Get most likely class
predicted_classes = np.argmax(predictions, axis=1)
true_classes = test_generator.classes
class_labels = list(test_generator.class_indices.keys())
print(class_labels)
report = metrics.classification_report(true_classes, predicted_classes, target_names=class_labels)
print(report)
confusion_matrix = confusion_matrix(true_classes, predicted_classes)
print(confusion_matrix)
############################################
###绘制图像import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocatordef plotCM(classes, matrix, savname):"""classes: a list of class names"""# Normalize by rowmatrix = matrix.astype(np.float)# linesum = matrix.sum(1)# linesum = np.dot(linesum.reshape(-1, 1), np.ones((1, matrix.shape[1])))# matrix /= linesum# plotplt.switch_backend('agg')fig = plt.figure()ax = fig.add_subplot(111)cax = ax.matshow(matrix)fig.colorbar(cax)ax.xaxis.set_major_locator(MultipleLocator(1))ax.yaxis.set_major_locator(MultipleLocator(1))for i in range(matrix.shape[0]):for j in range(matrix.shape[1]):ax.text(j, i, str('%.2f' % (matrix[i, j])), va='center', ha='center')ax.set_xticklabels([''] + classes, rotation=90)ax.set_yticklabels([''] + classes)# saveplt.savefig(savname)
plotCM(labels, confusion_matrix, 'confusion_matrix.jpg')

利用deepface网络进行表情分类相关推荐

  1. 一篇文章教会你利用Python网络爬虫获取分类图片

    点击上方"IT共享之家",进行关注 回复"资料"可获赠Python学习福利 [一.项目背景] 博海拾贝是一支互联网从业者在线教育的团队,扎根于中国教育行业以及互 ...

  2. 利用Python网络爬虫获取分类图片,简单处理反爬教学

    本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理 本文章来自腾讯云 作者:Python进阶者 想要学习Python?有问题得不到第一 ...

  3. 利用胶囊网络实现对CIFAR10分类

    利用胶囊网络实现对CIFAR10分类 数据集:CIFAR-10数据集由10个类中的60000个32x32彩色图像组成,每个类有6000个图像.有50000个训练图像和10000个测试图像. 实验:搭建 ...

  4. 人脸表情分类与识别:opencv人脸检测+Keras情绪分类

    本次讲述的表情分类是识别的分析流程分为: 1.加载pre-model网络与权重: 2.利用opencv的函数进行简单的人脸检测: 3.抠出人脸的图并灰化: 4.表情分类器检测 . 一.表情数据集 主要 ...

  5. keras系列︱人脸表情分类与识别:opencv人脸检测+Keras情绪分类(四)

    人脸识别热门,表情识别更加.但是表情识别很难,因为人脸的微表情很多,本节介绍一种比较粗线条的表情分类与识别的办法. Keras系列: 1.keras系列︱Sequential与Model模型.kera ...

  6. Linux网络常用工具分类介绍

    Linux网络命令较多,单纯的介绍网络命令的用法也没什么意思.本文将常见的网络命令进行分类,并做出思维导图,对每个分类的命令选择性的介绍其作用.常见选项和用法举例.BTW,不建议记住所有命令,了解一下 ...

  7. 利用TCN网络实现MNIST手写体数据集的识别

    利用TCN网络实现MNIST手写体数据集的识别 TCN识别MNIST的GitHub网址 https://github.com/locuslab/TCN 论文来源 https://arxiv.org/p ...

  8. 表情识别(四)--多网络级联表情识别

    EmotiW2015比赛静态表情识别的亚军,采用的方法为cnn的级联,人脸检测方面也采用了当时3种算法的共同检测,通过在FER2013数据库上进行模型预训练,并在SFEW2.0(比赛数据)上fine- ...

  9. matlab径向基网络,MATLAB——径向基网络拟合曲线和分类

    1.广义RBF P=:.:; rand('state',pi); %指定状态,产生相同的随机数 T=sin(*P)+rand(,length(P)); % 给正弦函数加噪声 plot(P,T,'o') ...

  10. 学习 | 文献通读《基于LDA的游客网络评论主题分类:以故宫为例》

    基于LDA的游客网络评论主题分类:以故宫为例 基于LDA的主题发现模型: [关注问题] 主题及情感倾向: 关键词 LDA 游客 网络评论 情感分析 故宫 [主要模块] 1.LDA主题分类,得到4个主题 ...

最新文章

  1. [百万级]通用存储过程.分页存储过程
  2. oracle数据库res,ipcs、ipcrm、sysresv、kernel.shmmax
  3. Kali国内源更新sources.list
  4. 对Java单例模式 volatile关键字作用的理解
  5. 转载:opencv:关于vs opencv每次都要配置的解决方案
  6. Linux环境配置1
  7. 52 两个链表的第一个公共结点(时间空间效率的平衡)
  8. python编程入门课_程序设计入门—Python
  9. Eclipse使用常见设置
  10. 哈工大威海数据结构实验
  11. 铁路现代化技术系统整理(二)之TMIS
  12. 6个好用免费的LiDAR数据处理软件【2021最新】
  13. closest()方法简介
  14. Java,php,运维工程师转型大数据开发怎么样?你属于哪一类?
  15. firefox火狐浏览器flash播放视频
  16. 神舟战神Z8-CA5NP,RTX3060怎么样?测评值得买吗?详细性能点评
  17. 《C++ Primer Plus》第八章习题与参考答案
  18. warning:In file included from...
  19. js中isNaN和Number.isNaN的区别
  20. 我在上海乐字节学习java的第二十五天(持续更新中)

热门文章

  1. python类代码编写细节
  2. decaNLP-一个可以同时处理机器翻译、问答、摘要、文本分类、情感分析等十项自然语言任务的通用模型
  3. for/map循环里面进行异步操作async/await后返回数据,for里不能直接return执行方法函数...
  4. HTML 5 会为 Flash 和 Silverlight 送终吗?
  5. 初探单点登录 SSO
  6. Webpack入门教程三十
  7. 基本类型和引用类型,执行环境和作用域
  8. Range的学习笔记
  9. HeadFirst jsp 08 无脚本JSP
  10. cocos2d Labels and Fonts 标签和字体