データセットの準備
まず、オリベッティ顔データセットを読み込み、前処理を行います。データをゼロ平均にするために、グローバル(1つの特徴に焦点を当ててすべてのサンプルを中心化)とローカル(1つのサンプルに焦点を当ててすべての特徴を中心化)の両方で中心化します。また、顔のギャラリーを描画するための基本関数も定義します。
## オリベッティ顔データセットを読み込み、前処理を行う。
import logging
from numpy.random import RandomState
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_olivetti_faces
from sklearn import cluster
from sklearn import decomposition
rng = RandomState(0)
## 標準出力に進捗ログを表示する
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
faces, _ = fetch_olivetti_faces(return_X_y=True, shuffle=True, random_state=rng)
n_samples, n_features = faces.shape
## グローバル中心化(1つの特徴に焦点を当ててすべてのサンプルを中心化)
faces_centered = faces - faces.mean(axis=0)
## ローカル中心化(1つのサンプルに焦点を当ててすべての特徴を中心化)
faces_centered -= faces_centered.mean(axis=1).reshape(n_samples, -1)
print("Dataset consists of %d faces" % n_samples)
## 顔のギャラリーを描画するための基本関数を定義する。
n_row, n_col = 2, 3
n_components = n_row * n_col
image_shape = (64, 64)
def plot_gallery(title, images, n_col=n_col, n_row=n_row, cmap=plt.cm.gray):
fig, axs = plt.subplots(
nrows=n_row,
ncols=n_col,
figsize=(2.0 * n_col, 2.3 * n_row),
facecolor="white",
constrained_layout=True,
)
fig.set_constrained_layout_pads(w_pad=0.01, h_pad=0.02, hspace=0, wspace=0)
fig.set_edgecolor("black")
fig.suptitle(title, size=16)
for ax, vec in zip(axs.flat, images):
vmax = max(vec.max(), -vec.min())
im = ax.imshow(
vec.reshape(image_shape),
cmap=cmap,
interpolation="nearest",
vmin=-vmax,
vmax=vmax,
)
ax.axis("off")
fig.colorbar(im, ax=axs, orientation="horizontal", shrink=0.99, aspect=40, pad=0.01)
plt.show()
## データを見てみましょう。灰色が負の値を、
## 白色が正の値を示します。
plot_gallery("Faces from dataset", faces_centered[:n_components])