SVM支持向量机实战:从零实现人脸简易识别系统

1次阅读
没有评论

共计 2256 个字符,预计需要花费 6 分钟才能阅读完成。

image.webp

技术背景

支持向量机(SVM)在图像分类任务中表现优异,尤其适合小样本场景。它通过寻找最优分类超平面实现数据分割,核函数技巧还能处理线性不可分问题。相比深度学习,SVM 训练更快、调参更简单,是入门计算机视觉的理想选择。

SVM 支持向量机实战:从零实现人脸简易识别系统

实现步骤

1. 数据准备

我们使用 Labeled Faces in the Wild(LFW)数据集,这是经典的人脸识别基准数据集。以下是数据加载与预处理的关键步骤:

from sklearn.datasets import fetch_lfw_people
import matplotlib.pyplot as plt

# 加载数据(限制类别数量便于演示)lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
X = lfw_people.images
y = lfw_people.target

# 可视化样本
fig, axes = plt.subplots(3, 5, figsize=(10, 6))
for i, ax in enumerate(axes.flat):
    ax.imshow(X[i], cmap='gray')
    ax.set(xticks=[], yticks=[], 
           xlabel=lfw_people.target_names[y[i]])

2. 特征工程

HOG(方向梯度直方图)能有效捕捉人脸轮廓特征,我们使用 skimage 库实现:

from skimage.feature import hog
from skimage.transform import resize
import numpy as np

# 定义 HOG 参数
orientations = 8
pixels_per_cell = (16, 16)
cells_per_block = (1, 1)

# 提取 HOG 特征
def extract_hog(images):
    features = []
    for img in images:
        # 统一图像尺寸
        resized_img = resize(img, (128, 64))
        # 提取 HOG 特征
        hog_feature = hog(resized_img, orientations=orientations,
                         pixels_per_cell=pixels_per_cell,
                         cells_per_block=cells_per_block,
                         visualize=False)
        features.append(hog_feature)
    return np.array(features)

X_hog = extract_hog(X)

3. 模型训练

比较线性核与 RBF 核的效果:

from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# 数据标准化与分割
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_hog)
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)

# 线性 SVM
svm_linear = SVC(kernel='linear', C=1.0)
svm_linear.fit(X_train, y_train)

# RBF 核 SVM
svm_rbf = SVC(kernel='rbf', gamma='scale', C=1.0)
svm_rbf.fit(X_train, y_train)

# 评估模型
print(f"Linear SVM 准确率: {svm_linear.score(X_test, y_test):.3f}")
print(f"RBF SVM 准确率: {svm_rbf.score(X_test, y_test):.3f}")

避坑指南

  1. 数据泄露预防
  2. 特征标准化必须在训练集上 fit 后,再 transform 测试集
  3. 使用 Pipeline 封装处理流程

  4. 类别不平衡处理

  5. 设置 class_weight=’balanced’
  6. 对少数类进行过采样

  7. 参数调优技巧

  8. 先用网格搜索粗调,再局部精细调整
  9. gamma 值对 RBF 核影响极大,建议从 ’scale’ 开始

延伸思考

  1. 与传统 CNN 对比
  2. SVM 在小样本场景下表现更好
  3. CNN 需要更多数据但特征提取更自动化

  4. 嵌入式部署优化

  5. 使用线性核减少计算量
  6. 量化特征向量为整型
  7. 考虑 LibSVM 的 C ++ 实现

完整代码示例

# 完整流程封装
from sklearn.pipeline import make_pipeline
from sklearn.metrics import classification_report

# 构建处理管道
pipe = make_pipeline(StandardScaler(),
    SVC(kernel='linear', C=1.0, class_weight='balanced')
)

# 训练评估
pipe.fit(X_train, y_train)
y_pred = pipe.predict(X_test)
print(classification_report(y_test, y_pred, 
                          target_names=lfw_people.target_names))

总结

通过本教程,我们实现了基于 HOG+SVM 的人脸识别系统。虽然准确率可能不及深度学习,但整个流程清晰展示了传统机器学习的完整工作流。建议初学者先掌握这种方法,再过渡到更复杂的模型。

正文完
 0
评论(没有评论)