Titanicデータセットを使用してランダムフォレストをトレーニングし、生存を予測する

2024年6月17日

以下は、Titanicデータセットを使用してランダムフォレストをトレーニングし、生存を予測するサンプルコードです。まずは、データの読み込みから始めます。

python
import pandas as pd

# データの読み込み
titanic_data = pd.read_csv('titanic.csv')

# データの概要を確認
print(titanic_data.head())

次に、データの前処理を行います。これには、欠損値の補完、カテゴリカル変数のエンコーディング、不要な列の削除などが含まれます。

python
# データの前処理
from sklearn.model_selection import train_test_split
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import LabelEncoder

# 不要な列を削除
titanic_data.drop(['PassengerId', 'Name', 'Ticket', 'Cabin'], axis=1, inplace=True)

# 欠損値の補完
imputer = SimpleImputer(strategy='most_frequent')
titanic_data['Age'] = imputer.fit_transform(titanic_data['Age'].values.reshape(-1, 1))

# カテゴリカル変数のエンコーディング
label_encoder = LabelEncoder()
titanic_data['Sex'] = label_encoder.fit_transform(titanic_data['Sex'])
titanic_data['Embarked'] = label_encoder.fit_transform(titanic_data['Embarked'])

# データの分割
X = titanic_data.drop('Survived', axis=1)
y = titanic_data['Survived']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

最後に、ランダムフォレストモデルをトレーニングし、テストデータで評価します。

python
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

# ランダムフォレストモデルのトレーニング
rf_model = RandomForestClassifier(n_estimators=100, random_state=42)
rf_model.fit(X_train, y_train)

# テストデータでの予測
y_pred = rf_model.predict(X_test)

# モデルの評価
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)

これで、ランダムフォレストを使用してTitanicデータセットの生存を予測する準備が整いました。必要に応じて、さらにモデルのチューニングや他の評価メトリクスの計算を追加で行うことができます。

未分類

Posted by ぼっち