LoginSignup
0
0

More than 3 years have passed since last update.

[Kaggle] ep.1 - タイタニックでなんとなく雰囲気を掴む

Posted at

tldr

サンプルのタイタニックをやってみました。

目次はこちら

始める

参考図書は以下を使います。

コード

データの読み込み

Google Driveからデータを読み込む準備をします。
以下を実行すると認証・認可画面に飛ばされて、Googleアカウントでログインすると認証コードがコピーできます。
それを入力するとGoogle Driveがマウントされます。

from google.colab import drive
drive.mount('/content/drive')

次に色々なライブラリのインポートを行ったのちに、Google Driveからトレーニングデータとテストデータを読み込みます。

%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import statsmodels.api as sm
import numpy as np

train = pd.read_csv("/content/drive/My Drive/Colab Notebooks/data/titanic/train.csv")
test = pd.read_csv("/content/drive/My Drive/Colab Notebooks/data/titanic/test.csv")

学習データとテストデータを特徴量と目的変数に分ける

#学習データを特徴量と目的変数に分ける
train_x=train.drop(['Survived'],axis=1)
train_y=train['Survived']

#テストデータは特徴量のみなので、そのままで良い
test_x=test.copy(

不要なデータを取り除く

from sklearn.preprocessing import LabelEncoder

# PassengerIdの削除
train_x = train_x.drop(['PassengerId'], axis=1)
test_x = test_x.drop(['PassengerId'], axis=1)

# Name, Ticket and Cabinの削除
train_x = train_x.drop(['Name', 'Ticket', 'Cabin'], axis=1)
test_x = test_x.drop(['Name', 'Ticket', 'Cabin'], axis=1)

# label encodingを文字列に適用する
for c in ['Sex', 'Embarked']:
  le = LabelEncoder()
  le.fit(train_x[c].fillna('NA'))

  train_x[c] = le.transform(train_x[c].fillna('NA'))
  test_x[c] = le.transform(test_x[c].fillna('NA'))

モデルを作成する

from xgboost import XGBClassifier

# モデルを作成して、学習する
model = XGBClassifier(n_estimators=20, random_state=71)
model.fit(train_x, train_y)

# テストデータの予測値を確立で出す
pred = model.predict_proba(test_x)[:, 1]

# テストデータの予測値を2値に変換
pred_label = np.where(pred > 0.5, 1, 0)

# 提出用のファイルを作成
submission = pd.DataFrame({'PassengerId': test['PassengerId'], 'Survived': pred_label})
submission.to_csv('submission_first.csv', index=False
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0