はじめに
この実験では、固有顔(eigenfaces)とサポートベクターマシン(Support Vector Machines, 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-learn のfetch_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)
主成分分析(Principal Component Analysis, 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)
予測された名前と実際の名前を付けた肖像画のギャラリーを描画することで、予測結果を可視化します。
固有顔(Eigenfaces)の可視化
eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])]
plot_gallery(eigenfaces, eigenface_titles, h, w)
plt.show()
また、入力データから抽出された特徴を可視化するために、固有顔(eigenfaces)を描画します。
まとめ
この実験では、固有顔(eigenfaces)とサポートベクターマシン(SVM)を使用して顔認識を行う方法を学びました。まず、データセットを読み込んで探索し、次に入力データをスケーリングすることでデータを前処理しました。その後、主成分分析(PCA)を行って入力データから特徴を抽出し、SVM 分類モデルを訓練しました。モデルの性能を評価し、予測結果と固有顔を可視化しました。