课程设计——采用卷积神经网络训练人脸识别模型(数据集为olivettifaces 人脸图像)

完整资源获取
点击下载完整资源

1、资源项目源码均已通过严格测试验证,保证能够正常运行;
2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通;
3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;
4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。

程序处理流程

# 读取人脸数据库olivettifaces,并存储为pkl文件
import numpy as np
from PIL import Image
import pickle
from sklearn.model_selection import train_test_split
import tensorflow as tf
import matplotlib.pyplot as plt
from datetime import datetime
import xlwt
import net_input

读取数据

file_name = 'E:/人脸识别/faces_data.pkl'
dataset, train_data,test_data, train_label,test_label = net_input.read_file(file_name)
batch_size = 20

搭建网络

# 方法2
def weight_variable(shape):
    inital = tf.truncated_normal(shape,stddev=0.1)
    return tf.Variable(inital) 
def bias_variable(shape):
    inital = tf.constant(0.1,shape=shape)##初始值为0.1
    return tf.Variable(inital) 
def conv2d(x,W):
    ##strides=[batch,height,width,channel],所以固定不动Batch和channel,只改变height和width的步长
    return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')  
def max_pool_2(x):
    ###kszie难道不是指核的大小???不是!!!!
    return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')  

### (57,47)====》(40)
def model(x_image):
    ## conv1 layer ##
#     print(x_image.shape)
    W_conv1 = weight_variable([5,5,1,32]) ##patch5*5,in_size=1,out_size=32
    b_conv1 = bias_variable([32])
    conv1 = tf.nn.bias_add(conv2d(x_image,W_conv1),b_conv1)  ##output:57*47*32
    conv1_relu = tf.nn.relu(conv1)   ##output:57*47*32
    conv1_pool = max_pool_2(conv1_relu)  ##output:29*24*32   # 向上取整

    ## conv2 layer ##
    W_conv2 = weight_variable([5,5,32,64]) ##patch5*5,in_size=32,out_size=64
    b_conv2 = bias_variable([64])
    conv2 = tf.nn.bias_add(conv2d(conv1_pool,W_conv2),b_conv2)  ##output:29*24*64
    conv2_relu = tf.nn.relu(conv2)   ##output:29*24*64
    conv2_pool = max_pool_2(conv2_relu)  ##output:15*12*64

    ##func1 layer##
    W_fc1 = weight_variable([15*12*64,1024])
    b_fc1 = bias_variable([1024])
    ##shape[n_sample,7,7,64]-->>[n_sample,7*7*64]
    conv2_pool_flat = tf.reshape(conv2_pool,[-1,15*12*64])
    fc1 = tf.matmul(conv2_pool_flat,W_fc1)+b_fc1
    fc1_relu = tf.nn.relu(fc1)
    fc1_relu_drop = tf.nn.dropout(fc1_relu,keep_prob) 
    ##func2 layer##
    W_fc2 = weight_variable([1024,40])
    b_fc2 = bias_variable([40])
    fc2 = tf.matmul(fc1_relu_drop,W_fc2)+b_fc2
    return fc2
def compute_accuracy(v_xs,v_ys):
    global prediction  #将prediction定义为全局变量
    y_pre = sess.run(prediction,feed_dict={X:v_xs,Y:v_ys,keep_prob:0.5})  ##得到1行10列的数据,也就是[1,10]
    correct_prediction = tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))
    ##取第二维概率最大的(这里索引了最大值的位置),同样标签为最大的值也是我真实的标签值(索引了位置)(我的标签是one_hot类型的)
    ###判断预测和真实标签的index是否一样,一样就代表预测正确,否则就错误
    accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
    result = sess.run(accuracy,feed_dict={X:v_xs,Y:v_ys})
    return result
# 搭建图-----会话图
# workbook = xlwt.Workbook() 
# sheet = workbook.add_sheet("loss") 
j = 1
with tf.Graph().as_default():
#     tf.reset_default_graph() # 这个可以不用细究,是为了防止重复定义报错
    ###define placeholder for inputs to network # 给X、Y定义placeholder,要指定数据类型、形状:
    X = tf.placeholder(tf.float32,[None,2679],name='X')  ##57*47,None表示其值大小不定,在这里作为第一个维度值,用以指代batch的大小,意即x的数量不定
    Y = tf.placeholder(tf.float32,[None,40],name='Y')  ##40类输出
    keep_prob = tf.placeholder(tf.float32)  ###定义丢掉率
    x_image = tf.reshape(X,[-1,57,47,1])##shape:[n_sample,28,28,1]
    
    global_steps = tf.Variable(1, trainable=False)
    
    # 先定义网络-----获得prediction
    prediction = model(x_image)
    print(prediction.shape)
    # 定义我们的cost
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=prediction,labels=Y))
    # 定义optimizer来minimize cost
    trainer = tf.train.AdamOptimizer().minimize(cost,global_step=global_steps)
    saver = tf.train.Saver()
  
    format_str = "%s    Iteration =  %d   loss = %0.3f"
    with tf.Session() as sess:
        # 首先给所有的变量都初始化(不用管什么意思,反正是一句必须的话):
        sess.run(tf.global_variables_initializer())

        # 定义一个costs列表,来装迭代过程中的cost,从而好画图分析模型训练进展
        costs = []  

        # 指定迭代次数:
        for it in range(20+1):
            batch = dataset.next_batch(batch_size)
            _,batch_cost = sess.run([trainer,cost],feed_dict={X:batch[0],Y:batch[1],keep_prob:0.5})
#             _,batch_cost = sess.run([trainer,cost],feed_dict={X:train_data,Y:train_label,keep_prob:0.5})
#             loss_new = str(round(batch_cost, 3))
#             sheet.write(it, 1, loss_new)
#             workbook.save('loss_face.xls')

            # 每100个迭代就打印一次cost:
            if it % 10 == 0:
#                 print('iteration%d ,batch_cost: '%it,batch_cost)
                print('loss:',format_str%(datetime.now(),it,batch_cost))
#                 print('正确率:',compute_accuracy(train_data,train_label))
#                 costs.append(batch_cost)

            if it % 20 == 0:
                file = str(j)+"saver_face"
                checkpoint = file+'/' + 'model.ckpt'
                saver.save(sess, checkpoint, global_step=global_steps)  
                
#             if it % 1000 == 0:
#                 write_file=open('E:/人脸识别/faces_loss2.pkl','wb')  
#                 pickle.dump(costs,write_file)  # 将数据存入pickle
#                 write_file.close() 
        
         ### 训练结束后,看下测试集和训练集上的正确率
#         print('test_accuracy:',compute_accuracy(test_data,test_label))
#         print('train_accuracy:',compute_accuracy(train_data,train_label))

(?, 40)
loss: 2018-12-21 20:43:24.476421 Iteration = 0 loss = 31.150
loss: 2018-12-21 20:43:27.703828 Iteration = 10 loss = 4.764
loss: 2018-12-21 20:43:29.736402 Iteration = 20 loss = 3.683

def train():
    j = 1
    with tf.Graph().as_default():
        X = tf.placeholder(tf.float32,[None,2679],name='X')  ##57*47,None表示其值大小不定,在这里作为第一个维度值,用以指代batch的大小,意即x的数量不定
        Y = tf.placeholder(tf.float32,[None,40],name='Y')  ##40类输出
        keep_prob = tf.placeholder(tf.float32)  ###定义丢掉率
        x_image = tf.reshape(X,[-1,57,47,1])##shape:[n_sample,28,28,1] 
        global_steps = tf.Variable(1, trainable=False)
        prediction = model(x_image)
        cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=prediction,labels=Y))
        trainer = tf.train.AdamOptimizer().minimize(cost,global_step=global_steps)
        saver = tf.train.Saver()
        format_str = "%s    Iteration =  %d   loss = %0.3f"
        with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())
            for it in range(20+1):
                batch = dataset.next_batch(batch_size)
                _,batch_cost = sess.run([trainer,cost],feed_dict={X:batch[0],Y:batch[1],keep_prob:0.5})
                if it % 10 == 0:
                    print('loss:',format_str%(datetime.now(),it,batch_cost))
                if it % 20 == 0:
                    file = str(j)+"saver_face"
                    checkpoint = file+'/' + 'model.ckpt'
                    saver.save(sess, checkpoint, global_step=global_steps)  
    print('训练结束!')
if __name__ == '__main__':
    train()
  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

毕业小助手

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值