고유 벡터와 SVM 을 이용한 얼굴 인식

Beginner

This tutorial is from open-source community. Access the source code

소개

이 실습에서는 고유 벡터 (eigenfaces) 와 서포트 벡터 머신 (SVMs) 을 사용하여 얼굴 인식을 수행하는 단계를 안내합니다. 이 실습에서 사용하는 데이터셋은 "Labeled Faces in the Wild" 데이터셋의 전처리된 일부입니다.

VM 팁

VM 시작이 완료되면 왼쪽 상단 모서리를 클릭하여 Notebook 탭으로 전환하여 연습을 위한 Jupyter Notebook에 접근할 수 있습니다.

때때로 Jupyter Notebook 이 완전히 로드되기까지 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사를 자동화할 수 없습니다.

학습 중 문제가 발생하면 Labby 에 문의하십시오. 세션 후 피드백을 제공하면 문제를 신속하게 해결해 드리겠습니다.

라이브러리 가져오기

from time import time
import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split
from sklearn.model_selection import RandomizedSearchCV
from sklearn.datasets import fetch_lfw_people
from sklearn.metrics import classification_report
from sklearn.metrics import ConfusionMatrixDisplay
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.svm import SVC
from scipy.stats import loguniform

먼저 필요한 모든 라이브러리를 가져와야 합니다.

데이터셋 로드 및 탐색

lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
n_samples, h, w = lfw_people.images.shape
X = lfw_people.data
n_features = X.shape[1]
y = lfw_people.target
target_names = lfw_people.target_names
n_classes = target_names.shape[0]

scikit-learnfetch_lfw_people() 함수를 사용하여 데이터셋을 다운로드합니다. 그런 다음 이미지의 샘플 수, 높이, 너비를 가져와 데이터셋을 탐색합니다. 또한 입력 데이터 X, 타겟 y, 타겟 이름 target_names, 클래스 수 n_classes를 가져옵니다.

데이터 전처리

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42
)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

데이터셋을 학습용과 테스트용으로 분할하고, 입력 데이터를 StandardScaler() 함수를 사용하여 스케일링하여 데이터를 전처리합니다.

PCA 수행

n_components = 150

pca = PCA(n_components=n_components, svd_solver="randomized", whiten=True).fit(X_train)
eigenfaces = pca.components_.reshape((n_components, h, w))

X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)

입력 데이터에서 특징을 추출하기 위해 주성분 분석 (PCA) 을 수행합니다. 주성분의 개수를 150 으로 설정하고 학습 데이터에 PCA 모델을 적합시킵니다. 그런 다음 고유 얼굴 (eigenfaces) 을 얻고 입력 데이터를 주성분으로 변환합니다.

서포트 벡터 머신 (SVM) 분류 모델 학습

param_grid = {
    "C": loguniform(1e3, 1e5),
    "gamma": loguniform(1e-4, 1e-1),
}

clf = RandomizedSearchCV(
    SVC(kernel="rbf", class_weight="balanced"), param_grid, n_iter=10
)
clf = clf.fit(X_train_pca, y_train)

변환된 데이터를 사용하여 SVM 분류 모델을 학습합니다. RandomizedSearchCV()를 사용하여 SVM 모델에 대한 최적의 하이퍼파라미터를 찾습니다.

모델 성능 평가

y_pred = clf.predict(X_test_pca)
print(classification_report(y_test, y_pred, target_names=target_names))
ConfusionMatrixDisplay.from_estimator(
    clf, X_test_pca, y_test, display_labels=target_names, xticks_rotation="vertical"
)

테스트 데이터를 사용하여 대상 값을 예측하고 classification_report() 함수를 사용하여 모델 성능을 평가합니다. 또한 ConfusionMatrixDisplay() 함수를 사용하여 혼동 행렬을 플롯합니다.

예측 시각화

def plot_gallery(images, titles, h, w, n_row=3, n_col=4):
    """Helper function to plot a gallery of portraits"""
    plt.figure(figsize=(1.8 * n_col, 2.4 * n_row))
    plt.subplots_adjust(bottom=0, left=0.01, right=0.99, top=0.90, hspace=0.35)
    for i in range(n_row * n_col):
        plt.subplot(n_row, n_col, i + 1)
        plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)
        plt.title(titles[i], size=12)
        plt.xticks(())
        plt.yticks(())

prediction_titles = [
    title(y_pred, y_test, target_names, i) for i in range(y_pred.shape[0])
]

plot_gallery(X_test, prediction_titles, h, w)

예측 결과를 시각화하여, 예측된 이름과 실제 이름이 표시된 초상화 갤러리를 그립니다.

고유 벡터 시각화

eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])]
plot_gallery(eigenfaces, eigenface_titles, h, w)

plt.show()

입력 데이터에서 추출된 특징을 시각화하기 위해 고유 벡터를 플롯합니다.

요약

이 실습에서는 고유 벡터와 SVM 을 사용하여 얼굴 인식을 수행하는 방법을 배웠습니다. 먼저 데이터셋을 로드하고 탐색한 후, 입력 데이터를 스케일링하여 데이터를 전처리했습니다. 그런 다음 PCA 를 사용하여 입력 데이터에서 특징을 추출하고 SVM 분류 모델을 학습했습니다. 모델 성능을 평가하고 예측 결과와 고유 벡터를 시각화했습니다.