始める無料で始める

分類モデルの仕上げ

ここでは、タイタニックのデータセットを使って分類モデルを作成します。データはすでに df という DataFrame に読み込まれています。乗客に関する情報から、生存したかどうかを予測します。

予測に使う変数は NumPy 配列 predictors に格納されています。予測対象は df.survived ですが、Keras で扱えるように少し加工が必要です。予測特徴量の数は n_cols に保存されています。

ここではオプティマイザに 'sgd'Stochastic Gradient Descent)を使います。これについては次の章でさらに学びます!

この演習はコースの一部です

Pythonで学ぶDeep Learning入門

コースを見る

演習の手順

  • to_categorical() 関数を使って、df.survived をカテゴリ変数に変換します。
  • model という名前の Sequential モデルを指定します。
  • ユニット数が 32Dense レイヤーを追加します。activation'relu'input_shape(n_cols,) とします。
  • 出力の Dense レイヤーを追加します。結果が2クラスなのでユニット数は 2、分類モデルなので activation'softmax' にします。
  • モデルをコンパイルします。optimizer'sgd'、損失関数 loss'categorical_crossentropy'、各エポックの終わりに正解率を確認できるように metrics=['accuracy'] を指定します。
  • predictorstarget を使ってモデルを学習(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
____
コードを編集して実行