用keras的cnn做人脸分类 keras图像分类

   2023-02-09 学习力599
核心提示:keras介绍Keras是一个简约,高度模块化的神经网络库。采用Python / Theano开发。使用Keras如果你需要一个深度学习库:可以很容易和快速实现原型(通过总模块化,极简主义,和可扩展性)同时支持卷积网络(vision)和复发性的网络(序列数据)。以及两者的组合

keras介绍

Keras是一个简约,高度模块化的神经网络库。采用Python / Theano开发。
使用Keras如果你需要一个深度学习库:

可以很容易和快速实现原型(通过总模块化,极简主义,和可扩展性)
同时支持卷积网络(vision)和复发性的网络(序列数据)。以及两者的组合。
无缝地运行在CPU和GPU上。
keras的资源库网址为https://github.com/fchollet/keras

olivettifaces人脸数据库介绍

Olivetti Faces是纽约大学的一个比较小的人脸库,由 40个人的400张图片构成,即每个人的人脸图片为10张。每张图片的灰度级为8位,每个像素的灰度大小位于0-255之间,每张图片大小为64×64。 如下图,这个图片大小是1140942,一共有2020张人脸,故每张人脸大小是(1140/20)(942/20)即5747=2679:
用keras的cnn做人脸分类

预处理模块

使用了PIL(Python Imaging Library)模块,是Python平台事实上的图像处理标准库。
预处理流程是:打开文件-》归一化-》将图片转为数据集-》生成label-》使用pickle序列化数据集

numpy.ndarray.flatten函数的功能是将一个矩阵平铺为向量

from PIL import Image
import numpy
import cPickle

img = Image.open('G:\data\olivettifaces.gif')
# numpy supports conversion from image to ndarray and normalization by dividing 255
# 1140 * 942 ndarray
img_ndarray = numpy.asarray(img, dtype='float64') / 255
# create numpy array of 400*2679
img_rows, img_cols = 57, 47
face_data = numpy.empty((400, img_rows*img_cols))
# convert 1140*942 ndarray to 400*2679 matrix

for row in range(20):
    for col in range(20):
        face_data[row*20+col] = numpy.ndarray.flatten(img_ndarray[row*img_rows:(row+1)*img_rows, col*img_cols:(col+1)*img_cols])

# create label
face_label = numpy.empty(400, dtype=int)
for i in range(400):
    face_label[i] = i / 10

# pickling file
f = open('G:\data\olivettifaces.pkl','wb')
# store data and label as a tuple
cPickle.dump((face_data,face_label), f)
f.close()

分类模型

程序参考了官方示例:https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py
一共有40个类,每个类10个样本,共400个样本。其中320个样本用于训练,40个用于验证,剩下40个测试
注意给第一层指定input_shape,如果是MLP,代码为:


model = Sequential()
# Dense(64) is a fully-connected layer with 64 hidden units.# in the first layer, you must specify the expected input data shape:# here, 20-dimensional vectors.
model.add(Dense(64, input_dim=20, init='uniform'))

后面可以不指定Dense的input shape

from __future__ import print_function
import numpy as np
import cPickle

np.random.seed(1337) # for reproducibililty

from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.utils import np_utils

# split data into train,vavlid and test
# train:320
# valid:40
# test:40
def split_data(fname):
    f = open(fname, 'rb')
    face_data,face_label = cPickle.load(f)

    X_train = np.empty((320, img_rows * img_cols))
    Y_train = np.empty(320, dtype=int)

    X_valid = np.empty((40, img_rows* img_cols))
    Y_valid = np.empty(40, dtype=int)

    X_test = np.empty((40, img_rows* img_cols))
    Y_test = np.empty(40, dtype=int)

    for i in range(40):
        X_train[i*8:(i+1)*8,:] = face_data[i*10:i*10+8,:]
        Y_train[i*8:(i+1)*8] = face_label[i*10:i*10+8]

        X_valid[i] = face_data[i*10+8,:]
        Y_valid[i] = face_label[i*10+8]

        X_test[i] = face_data[i*10+9,:]
        Y_test[i] = face_label[i*10+9]
    
    return (X_train, Y_train, X_valid, Y_valid, X_test, Y_test)

if __name__=='__main__':
    batch_size = 10
    nb_classes = 40
    nb_epoch = 12

    # input image dimensions
    img_rows, img_cols = 57, 47
    # number of convolutional filters to use
    nb_filters = 32
    # size of pooling area for max pooling
    nb_pool = 2
    # convolution kernel size
    nb_conv = 3

    (X_train, Y_train, X_valid, Y_valid, X_test, Y_test) = split_data('G:\data\olivettifaces.pkl')
    X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
    X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)
    
    print('X_train shape:', X_train.shape)
    print(X_train.shape[0], 'train samples')
    print(X_test.shape[0], 'test samples')
    # convert label to binary class matrix
    Y_train = np_utils.to_categorical(Y_train, nb_classes)
    Y_test = np_utils.to_categorical(Y_test, nb_classes)

    model = Sequential()
    # 32 convolution filters , the size of convolution kernel is 3 * 3
    # border_mode can be 'valid' or 'full'
    #‘valid’only apply filter to complete patches of the image. 
    # 'full'  zero-pads image to multiple of filter shape to generate output of shape: image_shape + filter_shape - 1
    # when used as the first layer, you should specify the shape of inputs 
    # the first number means the channel of an input image, 1 stands for grayscale imgs, 3 for RGB imgs
    model.add(Convolution2D(nb_filters, nb_conv, nb_conv,
                            border_mode='valid',
                            input_shape=(1, img_rows, img_cols)))
    # use rectifier linear units : max(0.0, x)
    model.add(Activation('relu'))
    # second convolution layer with 32 filters of size 3*3
    model.add(Convolution2D(nb_filters, nb_conv, nb_conv))
    model.add(Activation('relu'))
    # max pooling layer, pool size is 2 * 2
    model.add(MaxPooling2D(pool_size=(nb_pool, nb_pool)))
    # drop out of max-pooling layer , drop out rate is 0.25 
    model.add(Dropout(0.25))
    # flatten inputs from 2d to 1d
    model.add(Flatten())
    # add fully connected layer with 128 hidden units
    model.add(Dense(128))
    model.add(Activation('relu'))
    model.add(Dropout(0.5))
    # output layer with softmax 
    model.add(Dense(nb_classes))
    model.add(Activation('softmax'))
    # use cross-entropy cost and adadelta to optimize params
    model.compile(loss='categorical_crossentropy', optimizer='adadelta')
    # train model with bath_size =10, epoch=12
    # set verbose=1 to show train info
    model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch,
          show_accuracy=True, verbose=1, validation_data=(X_test, Y_test))
    # evaluate on test set
    score = model.evaluate(X_test, Y_test, show_accuracy=True, verbose=0)
    print('Test score:', score[0])
    print('Test accuracy:', score[1])

结果:
准确率有97%
用keras的cnn做人脸分类

 
反对 0举报 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • 拓端数据tecdat|使用Python中Keras的LSTM递归神经网络进行时间序列预测
    拓端数据tecdat|使用Python中Keras的LSTM递归神
     时间序列预测问题是预测建模问题中的一种困难类型。与回归预测建模不同,时间序列还增加了输入变量之间序列依赖的复杂性。用于处理序列依赖性的强大神经网络称为 递归神经网络。长短期记忆网络或LSTM网络是深度学习中使用的一种递归神经网络,可以成功地训
    03-08
  • 探索学习率设置技巧以提高Keras中模型性能 | 炼丹技巧
    探索学习率设置技巧以提高Keras中模型性能 | 炼
      学习率是一个控制每次更新模型权重时响应估计误差而调整模型程度的超参数。学习率选取是一项具有挑战性的工作,学习率设置的非常小可能导致训练过程过长甚至训练进程被卡住,而设置的非常大可能会导致过快学习到次优的权重集合或者训练过程不稳定。迁移学
    03-08
  • Keras函数式API介绍 keras框架介绍
    Keras函数式API介绍 keras框架介绍
    参考文献:Géron, Aurélien. Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems. O'Reilly Media, 2019.Keras的Sequential顺序模型可以快速搭建简易的神经网络,同时Ker
    02-09
  • keras——经典模型之LeNet5  实现手写字识别
    keras——经典模型之LeNet5 实现手写字识别
    经典论文:Gradient-Based Learning Applied to Document Recognition参考博文:https://blog.csdn.net/weixin_44344462/article/details/89212507构建LeNet-5模型#定义LeNet5网络深度为1的灰度图像def LeNet5(x_train, y_train, x_test, y_test):########搭
    02-09
  • Keras2.2 predict和fit_generator的区别
    查看keras文档中,predict函数原型:predict(self, x, batch_size=32, verbose=0)说明:只使用batch_size=32,也就是说每次将batch_size=32的数据通过PCI总线传到GPU,然后进行预测。在一些问题中,batch_size=32明显是非常小的。而通过PCI传数据是非常耗时的
    02-09
  • keras模块学习之-激活函数(activations)--笔
    本笔记由博客园-圆柱模板 博主整理笔记发布,转载需注明,谢谢合作!   每一个神经网络层都需要一个激活函数,例如一下样例代码:           from keras.layers.core import Activation, Densemodel.add(Dense(64))model.add(Activation('tanh'))或把
    02-09
  • 用于NLP的CNN架构搬运:from keras0.x to keras2.x
    用于NLP的CNN架构搬运:from keras0.x to keras
    本文亮点:将用于自然语言处理的CNN架构,从keras0.3.3搬运到了keras2.x,强行练习了Sequential+Model的混合使用,具体来说,是Model里嵌套了Sequential。本文背景:暑假在做一个推荐系统的小项目,老师让我们搜集推荐系统领域Top5的算法和模型,要求结合深度
    02-09
  • keras: 在构建LSTM模型时,使用变长序列的方法
    众所周知,LSTM的一大优势就是其能够处理变长序列。而在使用keras搭建模型时,如果直接使用LSTM层作为网络输入的第一层,需要指定输入的大小。如果需要使用变长序列,那么,只需要在LSTM层前加一个Masking层,或者embedding层即可。from keras.layers import
    02-09
  • 条件随机场CRF原理介绍 以及Keras实现
    条件随机场CRF原理介绍 以及Keras实现
    本文是对CRF基本原理的一个简明的介绍。当然,“简明”是相对而言中,要想真的弄清楚CRF,免不了要提及一些公式,如果只关心调用的读者,可以直接移到文末。 #按照之前的思路,我们依旧来对比一下普通的逐帧softmax和CRF的异同。 #CRF主要用于序列标注问题
    02-09
  • win10 python3.7 Anaconda3 安装tensorflow+Keras
    win10 python3.7 Anaconda3 安装tensorflow+Ker
    首先tensorflow 不支持python3.7,只能用tf1.9 也就是说:py3.7+ tf 1.9 +keras 2.2.0 才可以https://docs.floydhub.com/guides/environments/这个链接可以查询不同版本应该下载那个到Tensorflow支持Python3.7的一个whl:Unofficial Windows Binaries for Pyth
    02-09
点击排行