tensorflow1.1/构建卷积神经网络人脸识别

环境:tensorflow1.1,python3,matplotlin2.02

olivettifaces是纽约大学的一个比较小的人脸库,由40个人的400张图片构成,即每个人的人脸图片为10张。每张图片的灰度级为8位,每个像素的灰度大小位于0-255之间,每张图片大小为64×64。图片大小是1190*942,一共有20*20张人脸,故每张人脸大小是(1190/20)*(942/20)即57*47=2679本文所用的训练数据就是这张图片,400个样本,40个类别。

#coding:utf-8
"""
python 3
tensorflow 1.1
matplotlib 2.02
"""
import tensorflow as tf
import pickle
import numpy as np
import matplotlib.pyplot as plt

#读取数据集
with open('facedataset.pickle','rb') as f:
    (train_data,train_labels),(test_data,test_labels) = pickle.load(f)

tf.set_random_seed(100)
np.random.seed(100)
batch_size = 40
learning_rate = 0.01

#定义one_hot
def label_to_one_hot(labels_dense, num_classes=10):
    num_labels = labels_dense.shape[0]
    index_offset = np.arange(num_labels) * num_classes
    labels_one_hot = np.zeros((num_labels, num_classes))
    labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
    return labels_one_hot

train_data = train_data.astype(np.float32)
test_data = test_data.astype(np.float32)
train_labels = label_to_one_hot(train_labels,num_classes=40).astype(np.int32)
test_labels = label_to_one_hot(test_labels,num_classes=40).astype(np.int32)
#查看图片
plt.imshow(train_data[0].reshape((57,47)))
plt.title('the face picture',fontdict={'size':16,'color':'c'})
plt.gray()
plt.show()

#定义输入形状
xs = tf.placeholder(tf.float32,[None,57*47])
ys = tf.placeholder(tf.int32,[None,40])

#构建神经网络
x = tf.reshape(xs,[-1,57,47,1])
conv1 = tf.layers.conv2d(inputs=x,filters=5,kernel_size=3,strides=1,padding='same',activation=tf.nn.relu)
pool1 = tf.layers.max_pooling2d(conv1,pool_size=2,strides=2)
conv2 = tf.layers.conv2d(inputs=pool1,filters=10,kernel_size=3,strides=1,padding='same',activation=tf.nn.relu)
pool2 = tf.layers.max_pooling2d(conv2,pool_size=2,strides=2)
flat = tf.reshape(pool2,[-1,14*11*10])
output = tf.layers.dense(flat,40)

#计算loss
loss = tf.losses.softmax_cross_entropy(onehot_labels=ys,logits=output)
train = tf.train.AdamOptimizer(learning_rate).minimize(loss)
_,accuracy = tf.metrics.accuracy(labels=tf.argmax(ys,axis=1),predictions=tf.argmax(output,axis=1))
with tf.Session() as sess:
    init = tf.group(tf.global_variables_initializer(),tf.local_variables_initializer())
    sess.run(init)
    for i in range(10):
        _,c = sess.run([train,loss],feed_dict={xs:train_data,ys:train_labels})
        print('= = = = = = > > > > > >loss: %.4f' %c)
    acc = sess.run(accuracy,feed_dict={xs:test_data,ys:test_labels})
    print('accuracy is :%.4f' %acc)

由于数据集很小,在训练的时候就没有考虑采用batch训练

结果:

这里写图片描述

这里写图片描述

训练注意事项

在神经网络训练的过程中,如果数据集没有被打乱,原始数据集是有序的,会对检测精度造成很大影响
上述实验中在训练集和label上设置相同的随机种子,打乱顺序后训练,检测精度显著提高。
这里写图片描述

这里写图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值