import os from time import time import numpy as np import matplotlib.pyplot as plt from PIL import Image from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.decomposition import PCA from sklearn.svm import SVC def load_data(path, image_size=(112, 92)): “”" 手动加载 ORL 数据集中的人脸图像。 返回 X 和 y 的数组形式。 “”" images = [] labels = [] for person_dir in sorted(os.listdir(path)): # 遍历每个人员目录 if not os.path.isdir(os.path.join(path, person_dir)): continue label = int(person_dir.split('_')[0]) - 1 # 假设目录名是以数字开头 for img_file in os.listdir(os.path.join(path, person_dir)): if img_file.endswith('.pgm'): img_path = os.path.join(path, person_dir, img_file) img = Image.open(img_path).convert('L') # 灰度化 img_resized = img.resize(image_size) # 转换到统一大小 img_array = np.array(img_resized, dtype=np.float64).flatten() / 255. images.append(img_array) labels.append(label) return np.array(images), np.array(labels) if name == ‘main’: data_path = r’D:\cxdownload\ORL人脸识别数据集’ print("Loading local face datasets...") t_start = time() X, Y = load_data(data_path) _, h, w = X.shape[0], 112, 92 target_names = [f"Person_{i}" for i in range(40)] n_classes = len(target_names) print(f"Total dataset size:") print(f"n_samples: {X.shape[0]}") print(f"n_features: {X.shape[1]}") print(f"n_classes: {n_classes}") print(f'done in {(time() - t_start):.3f}s') # 划分训练集与测试集 X_train, X_test, Y_train, Y_test = train_test_split( X, Y, test_size=0.25, random_state=42) # 进行PCA降维 n_components = 150 print("Extracting the top {} eigenfaces from {} faces...".format( n_components, X_train.shape[0])) t0 = time() pca = PCA(n_components=n_components, svd_solver='randomized', whiten=True).fit(X_train) print("done in {:.3f}s".f
时间: 2025-06-26 22:02:16 浏览: 18
### 使用PCA进行人脸特征提取并用SVC完成分类
#### 数据预处理
在人脸识别任务中,通常会将每张人脸图像视为一个高维向量。为了减少计算复杂度和提高模型性能,可以通过主成分分析(Principal Component Analysis, PCA)降低数据维度[^3]。
```python
from sklearn.decomposition import PCA
import numpy as np
def preprocess_data(data, n_components=0.95):
"""
对输入的数据应用PCA降维。
参数:
data (numpy.ndarray): 输入的人脸图像矩阵,形状为(n_samples, n_features)。
n_components (float or int): 要保留的主成分数目或方差比例。
返回:
pca_result (numpy.ndarray): 经过PCA降维后的数据。
"""
pca = PCA(n_components=n_components, svd_solver='full')
pca_result = pca.fit_transform(data)
return pca_result
```
通过上述函数 `preprocess_data` 可以对原始数据集执行PCA操作,其中参数 `n_components` 表示要保留的主要成分数量或者希望保持的总方差百分比[^4]。
#### 构建支持向量机分类器
对于经过PCA降维后得到的新特征空间中的样本点,可以训练一个线性或非线性的支持向量机来区分不同的类别标签[^1]。
```python
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
def build_svm_classifier(features, labels):
"""
建立并评估基于SVM的支持向量机分类器。
参数:
features (numpy.ndarray): 特征矩阵,形状为(n_samples, n_reduced_dimensions)。
labels (list or array-like): 类别标签列表。
返回:
clf (sklearn.SVC): 训练好的SVM分类器实例。
test_accuracy (float): 测试集上的准确率得分。
"""
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42)
clf = SVC(kernel="linear", C=1.0, gamma="scale") # 初始化线性核SVM
clf.fit(X_train, y_train)
predictions = clf.predict(X_test)
test_accuracy = accuracy_score(y_test, predictions)
return clf, test_accuracy
```
这段代码定义了一个名为 `build_svm_classifier` 的方法用于创建SVM分类器,并返回该分类器及其测试精度值。
#### 完整流程演示
以下是结合以上两部分功能的一个简单例子:
```python
if __name__ == "__main__":
from sklearn.datasets import fetch_lfw_people
lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
images = lfw_people.images.reshape((lfw_people.target.shape[0], -1))
targets = lfw_people.target
reduced_images = preprocess_data(images, n_components=0.85)
classifier, accuarcy = build_svm_classifier(reduced_images, targets)
print(f"SVM Classifier Accuracy on Test Set: {accuarcy:.2f}")
```
这里我们加载了LFW Faces数据集作为实验对象,调整其大小以便于快速运行程序;接着调用了前面编写的两个辅助函数完成了整个过程:先做PCA变换再送入到SVM里边去学习规律最后输出预测效果如何。
阅读全文
相关推荐


















