分類モデルの仕上げ
ここでは、タイタニックのデータセットを使って分類モデルを作成します。データはすでに df という DataFrame に読み込まれています。乗客に関する情報から、生存したかどうかを予測します。
予測に使う変数は NumPy 配列 predictors に格納されています。予測対象は df.survived ですが、Keras で扱えるように少し加工が必要です。予測特徴量の数は n_cols に保存されています。
ここではオプティマイザに 'sgd'(Stochastic Gradient Descent)を使います。これについては次の章でさらに学びます!
この演習はコースの一部です
Pythonで学ぶDeep Learning入門
演習の手順
to_categorical()関数を使って、df.survivedをカテゴリ変数に変換します。modelという名前のSequentialモデルを指定します。- ユニット数が
32のDenseレイヤーを追加します。activationは'relu'、input_shapeは(n_cols,)とします。 - 出力の
Denseレイヤーを追加します。結果が2クラスなのでユニット数は 2、分類モデルなのでactivationは'softmax'にします。 - モデルをコンパイルします。
optimizerは'sgd'、損失関数lossは'categorical_crossentropy'、各エポックの終わりに正解率を確認できるようにmetrics=['accuracy']を指定します。 predictorsとtargetを使ってモデルを学習(fit)します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Import necessary modules
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
from tensorflow.keras.utils import to_categorical
# Convert the target to categorical: target
target = ____
# Set up the model
model = ____
# Add the first layer
____
# Add the output layer
____
# Compile the model
____
# Fit the model
____