MATLAB人脸识别源码
时间: 2023-10-31 09:06:37 浏览: 104
以下是MATLAB实现的人脸识别源代码:
```matlab
clear all;
close all;
clc;
%% Load Data
load face.mat % face.mat包含人脸图像和标签
%% Split into Training and Test Sets
trainingPercent = 0.8; % 训练集占80%
testingPercent = 0.2; % 测试集占20%
numObservations = size(X, 2);
numTraining = round(numObservations * trainingPercent);
numTesting = round(numObservations * testingPercent);
% 随机排列数据
idx = randperm(numObservations);
XTrain = X(:, idx(1:numTraining));
YTrain = Y(idx(1:numTraining));
XTest = X(:, idx(numTraining+1:end));
YTest = Y(idx(numTraining+1:end));
%% Train Classifier
mdl = fitcecoc(XTrain', YTrain); % 使用fitcecoc函数训练分类器
%% Test Classifier
YTestPredicted = predict(mdl, XTest'); % 使用训练的分类器预测测试集标签
accuracy = sum(YTestPredicted == YTest) / numel(YTest); % 计算准确率
fprintf('Accuracy = %.2f%%\n', accuracy * 100);
%% Visualize Results
% 随机选择一个测试样本进行可视化
i = randi([1 numTesting]);
x = XTest(:, i);
yTrue = YTest(i);
yPred = YTestPredicted(i);
% 可视化该样本
figure;
colormap gray;
subplot(1, 2, 1);
imagesc(reshape(x, 64, 64));
axis image;
title(sprintf('True Label: %d', yTrue));
subplot(1, 2, 2);
imagesc(reshape(mdl.ClassificationEnsemble.BinaryLearners{yPred}.Beta, 64, 64));
axis image;
title(sprintf('Predicted Label: %d', yPred));
```
该代码使用了人脸数据集,将其分为训练集和测试集,并使用fitcecoc函数训练分类器。然后,使用训练的分类器预测测试集标签并计算准确率。最后,随机选择一个测试样本进行可视化。
阅读全文