はじめに
Kerasでモデルを学習させるとき、「エポック数はどれくらいがちょうどいいの?」と迷ったことはありませんか?
エポックを増やすほど精度は上がりますが、やりすぎると過学習(overfitting)が起き、検証データの精度が下がってしまいます。
この記事では、実際にグラフを使ってエポック数と精度の関係を“見える化”してみましょう。
エポック数とは?
エポック(epoch)とは、「すべての学習データを1回使って学習すること」を指します。
たとえば、訓練データが1000件あり、バッチサイズが100なら、1エポック = 100件×10回の更新で完了します。
- バッチサイズ:1回の学習で使うデータ数
- エポック数:データを何回繰り返すか
この2つは混同されがちですが、モデルの学習挙動を理解するうえで非常に重要なパラメータです。
👉 関連記事:
【Keras入門】バッチサイズとは?精度との関係を実験で比較!
実験設定
今回は MNIST 手書き数字データセットを使い、エポック数を変えて学習精度を比較します。
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt
# データ読み込み
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# ====== 関数化:新しいモデルを毎回作成 ======
def create_model():
model = keras.Sequential([
layers.Input(shape=(28, 28)),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dropout(0.2),
layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
return model
# ====== エポック数を変えて比較 ======
histories = {}
for epochs in [5, 20, 100]:
print(f"\n=== Epochs: {epochs} ===")
model = create_model()
history = model.fit(
x_train, y_train,
validation_data=(x_test, y_test),
epochs=epochs,
batch_size=128,
verbose=0
)
histories[epochs] = {
'history': history.history,
'test_result': model.evaluate(x_test, y_test, verbose=0)
}
# ====== 結果出力 ======
for epochs, result in histories.items():
train_acc = result['history']['accuracy'][-1]
val_acc = result['history']['val_accuracy'][-1]
test_loss, test_acc = result['test_result']
print(f"\n=== Epochs: {epochs} ===")
print(f"最終訓練精度: {train_acc:.4f}")
print(f"最終検証精度: {val_acc:.4f}")
print(f"テスト精度: {test_acc:.4f}")
結果とグラフ
以下のように、エポック数が増えると訓練精度は上がるものの、検証精度(val_accuracy)はあるところで頭打ちになります。
plt.figure(figsize=(8,5))
for epochs, result in histories.items():
plt.plot(result['history']['val_accuracy'], label=f'val_acc (epochs={epochs})')
plt.title("Validation Accuracy vs. Epochs")
plt.xlabel("Epoch")
plt.ylabel("Accuracy")
plt.legend()
plt.show()
実行結果例
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz 11490434/11490434 ━━━━━━━━━━━━━━━━━━━━ 2s 0us/step === Epochs: 5 === === Epochs: 20 === === Epochs: 100 === === Epochs: 5 === 最終訓練精度: 0.9707 最終検証精度: 0.9748 テスト精度: 0.9748 === Epochs: 20 === 最終訓練精度: 0.9912 最終検証精度: 0.9839 テスト精度: 0.9839 === Epochs: 100 === 最終訓練精度: 0.9973 最終検証精度: 0.9819 テスト精度: 0.9819
グラフ描画
結果まとめ
| エポック数 | 最終訓練精度 | 最終検証精度 | 備考 |
|---|---|---|---|
| 5 | 0.97 | 0.97 | まだ伸びしろあり |
| 20 | 0.991 | 0.983 | ベスト付近 |
| 100 | 0.997 | 0.981 | 過学習が発生 |
➡️ 約 20エポック前後 が最適なバランスです。
過学習を防ぐには?
EarlyStopping
一定期間精度が向上しなければ学習を自動停止します。
from tensorflow.keras.callbacks import EarlyStopping
early_stopping = EarlyStopping(monitor='val_loss', patience=3)
model.fit(x_train, y_train, epochs=100, validation_split=0.2,
callbacks=[early_stopping])
👉 関連記事: Keras EarlyStoppingで過学習防止:精度低下の原因と対策
Dropout
モデルの一部のノードを無効化して過学習を抑制します。
👉 関連記事: 【Keras/CNN】Dropoutの効果をコードで可視化!使い所と設定値の決め方策
データ拡張(Data Augmentation)
訓練データをランダムに変形・反転などして水増しします。
👉 関連記事: 5エポック→40エポック!学習回数でAIの精度はどこまで伸びる?【Keras転移学習で検証】
まとめ
- エポック数とは「学習データを何回繰り返すか」
- 増やしすぎると過学習を起こす
- グラフで精度を確認しながら調整するのがベスト
- 20エポック前後を目安に、EarlyStoppingなどを活用


0 件のコメント:
コメントを投稿