Created
September 19, 2019 08:18
-
-
Save smly/c1ef80d949fca70fda93f47e25da0bf1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
import lightgbm as lgb | |
# データをロード | |
df_train = pd.read_csv('./train.csv') | |
df_test = pd.read_csv('./test.csv') | |
# データフレームを「訓練」「テスト」の順番に連結する | |
df = pd.concat([df_train, df_test], sort=False) | |
# 訓練データの目標変数 `price` だけ取り出す | |
y_train = df.iloc[:len(df_train)]['price'].values | |
# データフレームの量的変数 (数字だけの列データ)、カテゴリカル変数(文字列などの列データ)を処理する | |
# カテゴリカル変数は `factorize()` により変換する (これは sklearn の LabelEncoder と同等の処理) | |
# 量的変数は欠損値を平均値によって埋める | |
# ここでは連結したデータフレーム `df` に対して処理することで、「訓練」「テスト」の両方に対して同時に処理をしている | |
cols = [] | |
categorical_cols = [] | |
for col in df.columns: | |
# データを一意に特定する Id と目標変数は変換しない | |
if col in ['listing_id', 'price']: | |
continue | |
elif pd.api.types.is_numeric_dtype(df[col]): | |
# 量的変数の場合 | |
df[col] = df[col].fillna(df[col].mean()) | |
else: | |
# カテゴリカル変数の場合 | |
df[col] = df[col].factorize()[0] | |
categorical_cols.append(col) # カテゴリカルのカラム名を `categorical_cols` リストに追加 | |
cols.append(col) # 処理済みのカラムを `cols` リストに追加 | |
# pandas のデータフレームから、numpy の行列データを作成する | |
X_train = df[cols].values[:len(df_train)] | |
X_test = df[cols].values[len(df_train):] | |
# LightGBM のデータセットオブジェクトを作成する | |
# 説明変数ごとの名前のリストと、そのうちカテゴリカルな変数をそれぞれ `feature_name`, `categorical_feature` で指定する | |
lgb_train = lgb.Dataset(X_train, label=y_train, feature_name=cols, categorical_feature=categorical_cols) | |
# LightGBM のハイパーパラメータ | |
# ドキュメント:https://github.com/microsoft/LightGBM/blob/master/docs/Parameters.rst#core-parameters | |
params = { | |
'task': 'train', | |
'boosting_type': 'gbdt', | |
'objective': 'regression', | |
'metric': 'rmse', | |
# 'num_leaves': 60, | |
# 'learning_rate': 0.05, | |
# 'feature_fraction': 0.9, | |
# 'bagging_fraction': 0.9, | |
} | |
# LightGBM で加法的に増やす決定木の数を `num_boost_round` で指定 | |
booster = lgb.train(params, lgb_train, num_boost_round=10) | |
# 予測を行う | |
df_test['price'] = booster.predict(X_test) | |
df_test[['listing_id', 'price']].to_csv('./_baseline_lgb_without_using_validation_set_less_param.csv', index=False) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment