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:

预处理模块

使用了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做人脸分类的更多相关文章

  1. 使用CNN做文本分类——将图像2维卷积换成1维

    使用CNN做文本分类 from __future__ import division, print_function, absolute_import import tensorflow as tf ...

  2. keras 的svm做分类

    SVC继承了父类BaseSVC SVC类主要方法: ★__init__() 主要参数: C: float参数 默认值为1.0 错误项的惩罚系数.C越大,即对分错样本的惩罚程度越大,因此在训练样本中准确 ...

  3. .NET做人脸识别并分类

    .NET做人脸识别并分类 在游乐场.玻璃天桥.滑雪场等娱乐场所,经常能看到有摄影师在拍照片,令这些经营者发愁的一件事就是照片太多了,客户在成千上万张照片中找到自己可不是件容易的事.在一次游玩等活动或家 ...

  4. CNN眼中的世界:利用Keras解释CNN的滤波器

    转载自:https://keras-cn.readthedocs.io/en/latest/legacy/blog/cnn_see_world/ 文章信息 本文地址:http://blog.keras ...

  5. 万字总结Keras深度学习中文文本分类

    摘要:文章将详细讲解Keras实现经典的深度学习文本分类算法,包括LSTM.BiLSTM.BiLSTM+Attention和CNN.TextCNN. 本文分享自华为云社区<Keras深度学习中文 ...

  6. (转!)利用Keras实现图像分类与颜色分类

    2018-07-19 全部谷歌渣翻加略微修改 大家将就的看哈 建议大佬们还是看看原文 点击收获原文 其中用到的示例文件 multi-output-classification 大家可以点击 下载 . ...

  7. 机器学习: Tensor Flow +CNN 做笑脸识别

    Tensor Flow 是一个采用数据流图(data flow graphs),用于数值计算的开源软件库.节点(Nodes)在图中表示数学操作,图中的线(edges)则表示在节点间相互联系的多维数据数 ...

  8. Tensorflow&CNN:裂纹分类

    版权声明:本文为博主原创文章,转载 请注明出处:https://blog.csdn.net/sc2079/article/details/90478551 - 写在前面 本科毕业设计终于告一段落了.特 ...

  9. 基于CNN的人脸相似度检测

    人脸相似度检测主要是检测两张图片中人脸的相似度,从而判断这两张图片的对象是不是一个人. 在上一篇文章中,使用CNN提取人脸特征,然后利用提取的特征进行分类.而在人脸相似度检测的工作中,我们也可以利用卷 ...

随机推荐

  1. [转]常用的快速Web原型图设计工具

    转自大神: http://www.cnblogs.com/lhb25/archive/2009/04/25/1443254.html 做产品原型是非常重要的一个环节,做产品原型就会用使用各式各样的工具 ...

  2. java 静态代码块 构造块 构造方法

    class className{ static{ }//静态代码块 { }//构造代码块 public className(){} //构造方法 }

  3. 利用cubieboard设置samba打印服务器

    #注意安装下面软件前,先将cubieboard的动态地址改为静态地址! apt-get install samba #安装samba vi /etc/samba/smb.conf //配置 workg ...

  4. 【转载】[C#]Log4net中的RollingFileAppender解析

    Log4日志组件的应用确实简单实用,在比较了企业库和Log4的日志功能后,个人觉得Log4的功能更加强大点.补充说明下,我使用的企业库是2.0版本,Log4net是1.2.1版本的. 在Log4net ...

  5. web_submit_data函数上传图片

    web_submit_data函数上传图片 通常loadrunner上传下载文件脚本不能通过录制来实现,录制上传脚本回放过程会出问题,主要原因在于上传文件的路径,了解了上传文件的原理之后,可以手工完成 ...

  6. python--day2--基础数据类型与变量

    笔者:QQ:   360212316 python控制语句 for循环语句示例: for i in range(10): print(i) for循环语句示例1: for i in range(10) ...

  7. CentOS7上搭建WEB服务器

    mysql 安装 直接yum install mysql-server是不可以的 1 wget http://repo.mysql.com/mysql-community-release-el7-5. ...

  8. Java入门记(一):折腾HelloWorld

    HelloWorld,学习每门语言的第一步.有人戏称,这些年的编程生涯就是学习各种语言的HelloWorld,不知是自谦还是自嘲.目前所在的公司使用Java作为主要开发语言,我进行语言转换也大半年了, ...

  9. c#自制视屏监控

    项目需要开发一个监控程序,主要是监控其它电脑的操作情况. 先说下原理吧,首先我们列出做远程监控的基本步骤,远端电脑的ip,捕捉屏幕的方法,传输,接收并显示. 突然不知道怎么写下去了....... 程序 ...

  10. Android_SQLite版本升级,降级 管理

    今天我们主要学习了数据库版本升级对软件的管理操作. 我们手机经常会收到xxx软件升级什么的提醒,你的软件版本更新,同时你的数据库对应的版本也要相应的更新. 数据库版本更新需要主要的问题: 软件的1.0 ...