sklearn.model_selection の train_test_split を使用してデータを訓練用とテスト用に分割する
このステップでは、トレーニングプロセスに向けてデータを準備します。機械学習の重要な部分は、モデルが一度も見たことのないデータで評価することです。これを行うために、データセットを 2 つの部分に分割します。トレーニングセットとテストセットです。モデルはトレーニングセットから学習し、テストセットを使用してそのパフォーマンスを評価します。
まず、特徴量(入力変数、X)とターゲット(予測したい値、y)を分離する必要があります。この場合、X は MedHouseVal 以外のすべての列になり、y は MedHouseVal 列になります。
次に、sklearn.model_selection の train_test_split 関数を使用して分割を実行します。
以下のコードを main.py ファイルに追加してください。
from sklearn.model_selection import train_test_split
## Prepare the data
X = california_df.drop('MedHouseVal', axis=1) ## Features (input variables)
y = california_df['MedHouseVal'] ## Target variable (what we want to predict)
## Split the data into training and testing sets
## test_size=0.2: テスト用に 20% のデータを確保し、トレーニング用に 80% を使用
## random_state=42: 分割を再現可能にする(実行ごとに同じ結果が得られる)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
## Print the shapes of the new datasets to confirm the split
print("\n--- Data Split ---")
print("X_train shape:", X_train.shape) ## Training features
print("X_test shape:", X_test.shape) ## Test features
print("y_train shape:", y_train.shape) ## Training target values
print("y_test shape:", y_test.shape) ## Test target values
ターミナルからスクリプトを再度実行してください。
python3 main.py
DataFrame の下に、新しく作成されたトレーニングセットとテストセットの形状が表示されます。これにより、データが正しく分割されたことが確認できます。
--- Data Split ---
X_train shape: (16512, 8)
X_test shape: (4128, 8)
y_train shape: (16512,)
y_test shape: (4128,)