Skip to content

Keras Sequential.predict_classes()の代替方法

問題概要

TensorFlow 2.6以降のバージョンで、KerasのSequentialモデルにおいてpredict_classes()メソッドを使用しようとすると、以下のエラーが発生します:

AttributeError: 'Sequential' object has no attribute 'predict_classes'

この問題は、TensorFlowのバージョンアップデートによってpredict_classes()メソッドが非推奨となり、最終的には完全に削除されたことが原因です。

解決策

predict_classes()の代わりに、モデルの出力からクラス予測値を取得する方法をいくつか紹介します。使用する方法は、分類問題のタイプ(バイナリ分類か多クラス分類か)によって異なります。

python
# 確率予測の取得
predictions_proba = model.predict(X_test)

# クラス予測の取得(最大確率のインデックスを取得)
predictions = np.argmax(predictions_proba, axis=-1)
python
# 確率予測の取得
predictions_proba = model.predict(X_test)

# クラス予測の取得(0.5以上なら1、それ以下なら0)
predictions = (predictions_proba > 0.5).astype("int32")

詳細な説明

非推奨化の背景

predict_classes()メソッドはTensorFlow 2.6で完全に削除されました。これに先立つバージョンでは、以下のような警告メッセージが表示されていました:

model.predict_classes() is deprecated and will be removed after 2021-01-01. Please use instead:

  • np.argmax(model.predict(x), axis=-1), if your model does multi-class classification (e.g. if it uses a softmax last-layer activation).
  • (model.predict(x) > 0.5).astype("int32"), if your model does binary classification (e.g. if it uses a sigmoid last-layer activation).

多クラス分類の実装例

ソフトマックス活性化関数を使用する多クラス分類モデルの場合:

python
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

# モデル構築例
model = Sequential()
model.add(Dense(24, input_dim=13, activation='relu'))
model.add(Dense(18, activation='relu'))
model.add(Dense(6, activation='softmax'))  # 多クラス分類
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

# 訓練
history = model.fit(X_train, y_train, batch_size=256, epochs=10, verbose=2, validation_split=0.2)

# 評価
score, acc = model.evaluate(X_test, y_test, verbose=2, batch_size=256)
print('Test accuracy:', acc)

# クラス予測(新しい方法)
predictions_proba = model.predict(X_test)
predictions = np.argmax(predictions_proba, axis=1)

バイナリ分類の実装例

シグモイド活性化関数を使用するバイナリ分類モデルの場合:

python
# モデル構築例(バイナリ分類)
model = Sequential()
model.add(Dense(24, input_dim=13, activation='relu'))
model.add(Dense(18, activation='relu'))
model.add(Dense(1, activation='sigmoid'))  # バイナリ分類
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# クラス予測(新しい方法)
predictions_proba = model.predict(X_test)
predictions = (predictions_proba > 0.5).astype("int32")

INFO

axisパラメータの値:

  • axis=1: 各行における最大値のインデックスを取得
  • axis=-1: 最後の次元における最大値のインデックスを取得(多くの場合、axis=1と同じ)

性能評価指標の計算

クラス予測値を取得した後、F1スコア、精度、再現率などの評価指標を計算できます:

python
from sklearn.metrics import f1_score, accuracy_score, recall_score

# 評価指標の計算
f1 = f1_score(y_true, predictions, average='weighted')
accuracy = accuracy_score(y_true, predictions)
recall = recall_score(y_true, predictions, average='weighted')

print(f'F1 Score: {f1:.4f}')
print(f'Accuracy: {accuracy:.4f}')
print(f'Recall: {recall:.4f}')

まとめ

TensorFlow 2.6以降では、predict_classes()メソッドの代わりに以下の方法を使用してください:

  1. 多クラス分類: np.argmax(model.predict(x), axis=1)
  2. バイナリ分類: (model.predict(x) > 0.5).astype("int32")

この変更は後方互換性を壊す変更ですが、より明確で柔軟な予測処理を提供します。古いコードを更新する際は、モデルがバイナリ分類か多クラス分類かを確認し、適切な方法を選択してください。