驚くほど簡単な技術系健忘録

驚くほど簡単な技術系健忘録

アプリやWebサービス、RPAを作る上での健忘録を書いていきます。

KaggleのRestaurant Revenue Predictionの写経をしてみた

qiita.com

とりあえずこのQiitaの記事を写経しました。

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

import datetime
from sklearn.preprocessing import LabelEncoder

df_train = pd.read_csv("/kaggle/input/restaurant-revenue-prediction/train.csv.zip")
df_test =  pd.read_csv("/kaggle/input/restaurant-revenue-prediction/test.csv.zip")

#再度分解するためにそれぞれのデータにラベルを付ける
df_train['Label'] = "train"
df_test['Label'] = "test"

#目的変数を抽出
revenue = df_train['revenue']
del df_train['revenue']

#前処理がしやすいように、trainとtestをconcat関数で結合(axis=0はユニオン)
#結合関数は pd.concat
df_whole = pd.concat([df_train, df_test], axis=0)

#Open Dateを年・月・日に分解
#applyは関数適用
#lambdaは無名関数
df_whole['Open Date'] = pd.to_datetime(df_whole['Open Date'])
df_whole['Year'] = df_whole['Open Date'].apply(lambda x : x.year)
df_whole['Month'] = df_whole['Open Date'].apply(lambda x : x.month)
df_whole['Day'] = df_whole['Open Date'].apply(lambda x : x.day)

#Cityを数値に変換
le = LabelEncoder()
df_whole['City'] = le.fit_transform(df_whole['City'])

#City Groupを数値に変換 Other -> 0, Big Cities -> 1
#map関数は置換(replace)と似ているがmapだとNANが発生する可能性がある
df_whole['City Group'] = df_whole['City Group'].map({'Other':0, 'Big Cities':1})

#Typeを数値に変換 FC -> 0, IL -> 1, DT -> 2, MB ->3
df_whole['Type'] = df_whole['Type'].map({'FC':0, 'IL':1, 'DT':2, 'MB':3})

#iloc関数を用いて再びtrainとtestに分割
#locはスライス関数スライスする範囲はA:BでAからBという形で引数を指定
"""
del df_whole['Label']
df_train = df_whole.iloc[:df_train.shape[0]]
df_test = df_whole.iloc[df_train.shape[0]:]
"""

#Labelを用いてtrainとtestに分割
df_train = df_whole[df_whole['Label'] == "train"]
df_test = df_whole[df_whole['Label'] == "test"]
del df_train['Label']
del df_test['Label']

#ここから学習させる
from sklearn.ensemble import RandomForestRegressor

#学習に使う特徴量のカラム名を取得
df_train_columns = [col for col in df_train.columns if col not in ['Id', 'Open Date']]

rf = RandomForestRegressor(
    n_estimators=200
    ,max_depth=5
    ,max_features=0.5
    ,random_state=449
    ,n_jobs=-1
)

rf.fit(df_train[df_train_columns], revenue)

prediction = rf.predict(df_test[df_train_columns])

submission = pd.DataFrame({'Id':df_test.Id, 'Prediction':prediction})
submission.to_csv('TFI_submission.csv', index=False)

写経するとよく使う使う関数やデータの成形方法がわかっていい気がする。
コード中のコメントは自分なりの解釈も含んでいる。

写経元のQiitaにもあるように特徴量の取り方とかの工夫をしないと全然スコアは上がらないなーー。