图像处理:基于耶鲁大学Yale_64x64.mat的数据集进行人脸识别

#数据准备
import cv2
#准备由训练训练数据集和测试数据集
#实现cnn数据图标检测
#使用检测数据进行检测

#模块引入,其中scipy.io是为了引入同文件夹下的数据集
import tensorflow as tf
import numpy as np
#注意加载此包
import scipy.io as sio
#打开文件数据,第一个参数传递是文件名称,f是文件句柄
f =open('Yale_64x64.mat', 'rb')
#通过sio方法进行加载,加载后是字典类型
mdict = sio.loadmat(f)

#获取训练数据和训练标签
train_data = mdict['fea']
train_label = mdict['gnd']

#实现数据的无序排列
train_data = np.random.permutation(train_data)
train_label = np.random.permutation(train_label)
#从数据中抽取一部分作为测试数据
test_data = train_data[0:64]
test_label = train_label[0:64]
#生成随机种子
np.random.seed(100)
test_data = np.random.permutation(test_data)
test_label = np.random.permutation(test_label)

#准备训练数据,转换类型,对读入图片进行归一化处理,astype转换数据类型,/255是进行归一化,即像素0-1之间的转化
#转换完后,train_data数据集为三维,图片数量*64*64,其中64*64为每张图片矩阵的维度,1代表图片是黑白的
train_data = train_data.reshape(train_data.shape[0],64,64,1).astype(np.float32)/255
#数据集共有15种人脸,所以建立165*15的数据标签
train_labels_new = np.zeros(165*15)

for i in range(0,165):
    #数据标签放在0开始的14列的标签中
    j = int(train_label[i,0]) -1
    train_labels_new[i,j] = 1
#完成训练数据的准备

test_data_input = test_data.reshape(test_data.reshape(train_data.shape[0],64,64,1)).astype(np.float32)/255
test_labels_input = np.zeros(64*15)

for i in range(0,64):
    #数据标签放在0开始的14列的标签中
    j = int(test_label[i,0]) -1
    test_labels_input[i,j] = 1
#完成测试数据的准备

data_input = tf.placeholder(tf.float32,[None, 64, 64, 1])
label_input = tf.placeholder(tf.float32,[None,15])

#实现CNN卷积神经网络,并测试最终训练样本实现的检测概率
#tf.layer方法可以直接实现一个卷积神经网络的搭建
#通过卷积方法实现
layer1 = tf.layers.conv2d(inputs=data_input, filters = 32,kernel_size=2,
                          strides=1,padding='SAME',activation=tf.nn.relu)
#实现池化层,减少数据量,pool_size=2表示数据量减少一半
layer1_pool = tf.layers.max_pooling2d(layer1,pool_size=2,strides=2)
#第二层设置输出,完成维度的转换,以第一次输出作为输入,建立n行的32*32*32输出
layer2 = tf.reshape(layer1_pool,[-1,32*32*32])
#设置输出激励函数
layer2_relu = tf.layers.dense(layer2, 1024, tf.nn.relu)
#完成输出,设置输入数据和输出维度
output = tf.layers.dense(layer2_relu, 15)

#建立损失函数
loss = tf.losses.softmax_cross_entropy(onehot_labels=label_input,logits=output)
#使用梯度下降法进行训练
train = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
#定义检测概率
accuracy = tf.metrics.accuracy(
    labels=tf.arg_max(label_input,axis=1),predictions=tf.arg_max(output,axis=1))[1]

#对所有变量进行初始化
init = tf.group(
    tf.global_variables_initializer(),tf.local_variables_initializer(),tf.local_variables_initializer())
#定义for循环,完成样本的加载和数据训练
with tf.Session() as sess:
    sess.run(init)
    for i in range(0, 200):
        #准备数据
        train_data_input = np.array(train_data)
        train_label_input = np.array(train_labels_new)
        #完成数据加载并计算损失函数和训练值
        sess.run([train,loss],feed_dict={data_input:train_data_input,label_input:train_labels_input})
        acc = sess.run(accuracy,feed_dict={data_input:test_data_input,label_input:test_labels_input})
#打印当前概率精度
    print('acc:%.2f',acc)
  • 0
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
好的,您的问题是如何利用Python语言基于卷积神经网络的人脸识别,使用数据集Yale_64x64.mat。以下是一个基本的实现过程: 1. 导入必要的库和数据集 ```python import numpy as np import scipy.io as sio from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D from keras.utils import np_utils # 导入数据集 data = sio.loadmat('Yale_64x64.mat') X, y = data['fea'], data['gnd'] ``` 2. 数据预处理 ```python # 将数据集划分为训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 将数据集转换为CNN所需的格式 X_train = X_train.reshape(X_train.shape[0], 64, 64, 1).astype('float32') X_test = X_test.reshape(X_test.shape[0], 64, 64, 1).astype('float32') y_train = np_utils.to_categorical(y_train) y_test = np_utils.to_categorical(y_test) ``` 3. 建立卷积神经网络模型 ```python model = Sequential() model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(64, 64, 1))) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(15, activation='softmax')) ``` 4. 编译模型并训练 ```python model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=20, batch_size=32) ``` 5. 评估模型性能 ```python scores = model.evaluate(X_test, y_test, verbose=0) print('Test loss:', scores[0]) print('Test accuracy:', scores[1]) ``` 这是一个基本的卷积神经网络人脸识别的实现过程,您可以根据需要进行调整和改进。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

MarkJhon

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

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

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

打赏作者

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

抵扣说明:

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

余额充值