Skip to content

第 11 章 ソースコード一覧

書籍第 11 章「画像データを用いた機械学習」に掲載しているソースコードの一覧です。番号は書籍の「入力」番号と対応しています。上のバッジから、この章のコードをまとめた Google Colab ノートブックを開けます。

入力 11.1: MNISTサブセットの読み込み

import numpy as np
from urllib.request import urlretrieve

# MNISTサブセット(1,000枚)のダウンロードと読み込み
url = "https://ml.kano.ac/chapters/data/mnist_1000_raw.npz"
urlretrieve(url, "mnist_1000_raw.npz")
data = np.load("mnist_1000_raw.npz")
X, y = data["X"], data["y"]

print(f"データの形状: {X.shape}")
print(f"ラベルの形状: {y.shape}")
print(f"クラス: {np.unique(y)}")

入力 11.2: 先頭10枚の画像の表示

import matplotlib.pyplot as plt

# 先頭10枚の画像を表示
fig, axes = plt.subplots(2, 5, figsize=(10, 4))
for i, ax in enumerate(axes.ravel()):
    ax.imshow(X[i].reshape(28, 28), cmap="gray")
    ax.set_title(f"ラベル: {y[i]}")
    ax.axis("off")
plt.tight_layout()
plt.show()

入力 11.3: データの分割と正規化

from sklearn.model_selection import train_test_split

# 訓練データとテストデータの分割
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# 画素値の正規化(0〜255 → 0〜1)
X_train = X_train / 255.0
X_test = X_test / 255.0

print(f"訓練データ: {X_train.shape}")
print(f"テストデータ: {X_test.shape}")

入力 11.4: 生の画素値による分類の学習と評価

from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# ロジスティック回帰モデルの学習
model_pixel = LogisticRegression(
    max_iter=1000,
    solver="lbfgs",
    random_state=42
)
model_pixel.fit(X_train, y_train)

# テストデータでの予測と評価
y_pred_pixel = model_pixel.predict(X_test)
acc_pixel = accuracy_score(y_test, y_pred_pixel)
print(f"生の画素値による分類精度: {acc_pixel:.4f}")

入力 11.5: 誤分類された画像の表示

import numpy as np
import matplotlib.pyplot as plt

# 誤分類されたインデックスを取得
misclassified = np.where(y_pred_pixel != y_test)[0]
print(f"誤分類数: {len(misclassified)} / {len(y_test)}")

# 誤分類された画像の一部を表示
fig, axes = plt.subplots(2, 5, figsize=(12, 6))
for i, ax in enumerate(axes.ravel()):
    idx = misclassified[i]
    ax.imshow(X_test[idx].reshape(28, 28), cmap="gray")
    ax.set_title(f"正解: {y_test[idx]}, 予測: {y_pred_pixel[idx]}")
    ax.axis("off")
plt.suptitle("誤分類の例(生の画素)")
plt.tight_layout()
plt.show()

入力 11.6: 混同行列の計算と表示

import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import seaborn as sns

# 混同行列の計算と表示
cm = confusion_matrix(y_test, y_pred_pixel)
plt.figure(figsize=(8, 6))
sns.heatmap(cm, annot=True, fmt="d", cmap="Blues",
            xticklabels=range(10), yticklabels=range(10))
plt.xlabel("予測")
plt.ylabel("正解")
plt.title("混同行列(生の画素)")
plt.tight_layout()
plt.show()

入力 11.7: HOG特徴量の抽出

from skimage.feature import hog
import numpy as np

# 画像配列からHOG特徴量を抽出する
def extract_hog_features(images):
    hog_features = []
    for img in images:
        feature = hog(
            img.reshape(28, 28),
            orientations=9,
            pixels_per_cell=(4, 4),
            cells_per_block=(2, 2),
            block_norm="L2-Hys",
            feature_vector=True
        )
        hog_features.append(feature)
    return np.array(hog_features)

# HOG特徴量の抽出
X_train_hog = extract_hog_features(X_train)
X_test_hog = extract_hog_features(X_test)

print(f"HOG特徴量の形状(訓練): {X_train_hog.shape}")
print(f"HOG特徴量の形状(テスト): {X_test_hog.shape}")

入力 11.8: HOG特徴量による分類の学習と評価

from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# ロジスティック回帰モデルの学習
model_hog = LogisticRegression(
    max_iter=1000,
    solver="lbfgs",
    random_state=42
)
model_hog.fit(X_train_hog, y_train)

# テストデータでの予測と評価
y_pred_hog = model_hog.predict(X_test_hog)
acc_hog = accuracy_score(y_test, y_pred_hog)
print("HOG特徴量による分類精度:",
      f"{acc_hog:.4f}")

入力 11.9: 生の画素値とHOG特徴量の精度比較

print(f"生の画素値による分類精度: {acc_pixel:.4f}")
print(f"HOG特徴量による分類精度: {acc_hog:.4f}")
diff = acc_hog - acc_pixel
print(f"精度の改善: {diff:.4f} ({diff * 100:.2f}ポイント)")