画像分類(MNIST, CIFAR-10など)

Kerasを用いた画像分類モデルの実装は、深層学習の基本かつ重要な応用分野です。以下では、MNISTCIFAR-10といった代表的な画像データセットを使った分類モデルの構築手順を、ポイントごとに詳しく解説します。


1. データセットの概要

MNIST:

  • 手書き数字(0〜9)画像のデータセット

  • 画像サイズ: 28×28ピクセル、グレースケール

  • クラス数: 10

CIFAR-10:

  • 自然画像(犬、猫、飛行機など10クラス)のデータセット

  • 画像サイズ: 32×32ピクセル、RGBカラー

  • クラス数: 10


2. 必要なライブラリのインポート

python
import numpy as np from tensorflow.keras.datasets import mnist, cifar10 from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D from tensorflow.keras.utils import to_categorical

3. データの読み込みと前処理

MNISTの例:

python
(x_train, y_train), (x_test, y_test) = mnist.load_data() # 入力データの整形と正規化 x_train = x_train.reshape(-1, 28, 28, 1).astype('float32') / 255.0 x_test = x_test.reshape(-1, 28, 28, 1).astype('float32') / 255.0 # ラベルのone-hotエンコーディング y_train = to_categorical(y_train, 10) y_test = to_categorical(y_test, 10)

CIFAR-10の例(カラー画像の場合):

python
(x_train, y_train), (x_test, y_test) = cifar10.load_data() # 正規化 x_train = x_train.astype('float32') / 255.0 x_test = x_test.astype('float32') / 255.0 # ラベルのone-hotエンコーディング y_train = to_categorical(y_train, 10) y_test = to_categorical(y_test, 10)

4. モデルの構築(CNNを使用)

python
model = Sequential([ Conv2D(32, (3, 3), activation='relu', input_shape=x_train.shape[1:]), MaxPooling2D(pool_size=(2, 2)), Conv2D(64, (3, 3), activation='relu'), MaxPooling2D(pool_size=(2, 2)), Flatten(), Dense(128, activation='relu'), Dense(10, activation='softmax') ])

5. モデルのコンパイル

python
model.compile( optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'] )

6. モデルの学習

python
model.fit( x_train, y_train, epochs=10, batch_size=64, validation_split=0.1 )

7. モデルの評価と予測

python
# テストデータで評価 loss, accuracy = model.evaluate(x_test, y_test) print(f"Test accuracy: {accuracy:.4f}") # 推論 predictions = model.predict(x_test)

8. 解説と応用のポイント

  • **CNN(畳み込みニューラルネットワーク)**は画像認識に特化した構造で、特徴抽出に優れている。

  • MNISTでは単純なCNNでも高精度が得られるが、CIFAR-10ではより深いネットワークやデータ拡張が必要になる。

  • モデルの汎化性能を向上させるために、DropoutBatchNormalizationの導入も有効。

  • より高精度を求める場合は、VGGResNetなどの事前学習済みモデルと転移学習を組み合わせることができる。

生成日:2025/05/22