Kaggle competition: M5 Forecasting - Accuracy
<SOS> metric: M5_WRMSSE Kaggle data source: m5-forecasting-accuracy<prepare_output>
from datetime import datetime, timedelta
import gc
import numpy as np, pandas as pd
import lightgbm as lgb
Final_Pred = -4447 + np.exp(Ytest.inverse_transform(( ypredRidge*.20309379 + ypredLasso*.46724816 + ypredXG*.37162723)) )<feature_engineering>
CAL_DTYPES={"event_name_1": "category", "event_name_2": "category", "event_type_1": "category",
"event_type_2": "category", "weekday": "category", 'wm_yr_wk': 'int16', "wday": "int16",
"month": "int16", "year": "int16", "snap_CA": "float32", 'snap_TX': 'float32', 'snap_WI': 'float32' }
PRICE_DTYPES = {"store_id": "category", "item_id": "category", "wm_yr_wk": "int16","sell_price":"float32" }
Final_Pred[np.exp(Ytest.inverse_transform(ypredRidge)) >y.max() ] = np.exp(Ytest.inverse_transform(ypredXG)) [np.exp(Ytest.inverse_transform(ypredRidge)) >y.max() ]<save_to_csv>
pd.options.display.max_columns = 50
submission = pd.DataFrame({
"Id": IdTest,
"SalePrice": Final_Pred
})
 submission.to_csv('submission.csv', index=False )<load_from_csv>
h = 28
max_lags = 57
tr_last = 1913
fday = datetime(2016,4, 25)
 fday
train_df = pd.read_csv(".. /input/house-prices-advanced-regression-techniques/train.csv")
 test_df = pd.read_csv(".. /input/house-prices-advanced-regression-techniques/test.csv")
 X_train = train_df.drop(['SalePrice'], axis=1)
 y_train = train_df['SalePrice']
train_df
combined = pd.concat([train_df,test_df])
 all_data = [train_df,test_df]
total = combined.isnull().sum().sort_values(ascending=False)
 percent_1 = combined.isnull().sum() /combined.isnull().count() *100
percent_2 =(round(percent_1, 1)).sort_values(ascending=False)
 missing_data = pd.concat([total, percent_2], axis=1, keys=['Total', '%'])
 missing_data.head(20 )<groupby>
def create_dt(is_train = True, nrows = None, first_day = 1200):
prices = pd.read_csv(".. /input/m5-forecasting-accuracy/sell_prices.csv", dtype = PRICE_DTYPES)
 for col, col_dtype in PRICE_DTYPES.items() :
if col_dtype == "category":
prices[col] = prices[col].cat.codes.astype("int16")
 prices[col] -= prices[col].min()
cal = pd.read_csv(".. /input/m5-forecasting-accuracy/calendar.csv", dtype = CAL_DTYPES)
 cal["date"] = pd.to_datetime(cal["date"])
 for col, col_dtype in CAL_DTYPES.items() :
if col_dtype == "category":
cal[col] = cal[col].cat.codes.astype("int16")
 cal[col] -= cal[col].min()
start_day = max(1 if is_train else tr_last-max_lags, first_day)
 numcols = [f"d_{day}" for day in range(start_day,tr_last+1)]
catcols = ['id', 'item_id', 'dept_id','store_id', 'cat_id', 'state_id']
dtype = {numcol:"float32" for numcol in numcols}
dtype.update({col: "category" for col in catcols if col != "id"})
 dt = pd.read_csv(".. /input/m5-forecasting-accuracy/sales_train_validation.csv",
nrows = nrows, usecols = catcols + numcols, dtype = dtype)
 for col in catcols:
if col != "id":
dt[col] = dt[col].cat.codes.astype("int16")
 dt[col] -= dt[col].min()
if not is_train:
for day in range(tr_last+1, tr_last+ 28 +1):
dt[f"d_{day}"] = np.nan
dt = pd.melt(dt,
id_vars = catcols,
value_vars = [col for col in dt.columns if col.startswith("d_")],
var_name = "d",
value_name = "sales")
 dt = dt.merge(cal, on= "d", copy = False)
 dt = dt.merge(prices, on = ["store_id", "item_id", "wm_yr_wk"], copy = False)
 return dt
combined.groupby('MSZoning')['Id'].count()<filter>
def create_fea(dt):
lags = [7, 28]
lag_cols = [f"lag_{lag}" for lag in lags ]
for lag, lag_col in zip(lags, lag_cols):
dt[lag_col] = dt[["id","sales"]].groupby("id")["sales"].shift(lag)
 wins = [7, 28]
for win in wins :
for lag,lag_col in zip(lags, lag_cols):
dt[f"rmean_{lag}_{win}"] = dt[["id", lag_col]].groupby("id")[lag_col].transform(lambda x : x.rolling(win ).mean())
 date_features = {
"wday": "weekday",
"week": "weekofyear",
"month": "month",
"quarter": "quarter",
"year": "year",
"mday": "day",
}
for date_feat_name, date_feat_func in date_features.items() :
if date_feat_name in dt.columns:
dt[date_feat_name] = dt[date_feat_name].astype("int16")
 else:
dt[date_feat_name] = getattr(dt["date"].dt, date_feat_func ).astype("int16" )
combined[combined['MSZoning'].isnull() ]<categorify>
FIRST_DAY = 350
MSZoningMap = {'FV': 1, 'RL': 2, 'RH': 3, 'RM': 4, 'C(all)': 5}
for d in all_data:
d['MSZoning'] = d['MSZoning'].fillna('RL')
 d['MSZoning'] = d['MSZoning'].map(MSZoningMap)
 combined['MSZoning'] = combined['MSZoning'].fillna('RL')
 combined['MSZoning'] = combined['MSZoning'].map(MSZoningMap)
 combined['MSZoning'].unique()<feature_engineering>
df.dropna(inplace = True)
 df.shape
subclass_map = train_df.groupby('MSSubClass')['SalePrice'].mean().sort_values()
for d in all_data:
for idx, s in enumerate(subclass_map.index):
d.loc[d['MSSubClass'] == s,'MSSubClass'] = idx+1
for idx, s in enumerate(subclass_map.index):
combined.loc[combined['MSSubClass'] == s,'MSSubClass'] = idx+1
train_df.groupby('MSSubClass')['SalePrice'].describe().sort_values('mean' )<count_missing_values>
cat_feats = ['item_id', 'dept_id','store_id', 'cat_id', 'state_id'] + ["event_name_1", "event_name_2", "event_type_1", "event_type_2"]
useless_cols = ["id", "date", "sales","d", "wm_yr_wk", "weekday"]
train_cols = df.columns[~df.columns.isin(useless_cols)]
X_train = df[train_cols]
y_train = df["sales"]
combined['MSSubClass'].isnull().sum()<feature_engineering>
combined['LotFrontage'] = combined['LotFrontage'].fillna(0)
 for d in all_data:
d['LotFrontage'] = d['LotFrontage'].fillna(0)
 d['LotFrontage'] =(d['LotFrontage']-combined['LotFrontage'].mean())/combined['LotFrontage'].std()
combined['LotFrontage'] =(combined['LotFrontage']-combined['LotFrontage'].mean())/combined['LotFrontage'].std()<train_model>
%%time
np.random.seed(777)
 fake_valid_inds = np.random.choice(X_train.index.values, 2_000_000, replace = False)
 train_inds = np.setdiff1d(X_train.index.values, fake_valid_inds)
 train_data = lgb.Dataset(X_train.loc[train_inds] , label = y_train.loc[train_inds],
categorical_feature=cat_feats, free_raw_data=False)
 fake_valid_data = lgb.Dataset(X_train.loc[fake_valid_inds], label = y_train.loc[fake_valid_inds],
categorical_feature=cat_feats,
free_raw_data=False )
plt.plot(y_train, X_train['LotArea'], 'o')
 m, b = np.polyfit(y_train, X_train['LotArea'], 1)
 plt.plot(y_train, m*y_train + b )<feature_engineering>
del df, X_train, y_train, fake_valid_inds,train_inds ; gc.collect()
combined['LotArea'] = combined['LotArea'].fillna(0)
 for d in all_data:
d['LotArea'] = d['LotArea'].fillna(0)
 d['LotArea'] =(d['LotArea']-combined['LotArea'].mean())/combined['LotArea'].std()
combined['LotArea'] =(combined['LotArea']-combined['LotArea'].mean())/combined['LotArea'].std()<data_type_conversions>
params = {
"objective" : "poisson",
"metric" :"rmse",
"force_row_wise" : True,
"learning_rate" : 0.075,
"sub_row" : 0.75,
"bagging_freq" : 1,
"lambda_l2" : 0.1,
"metric": ["rmse"],
'verbosity': 1,
'num_iterations' : 1200,
'num_leaves': 128,
"min_data_in_leaf": 100,
}
combined['Alley'] = combined['Alley'].fillna('None')
 for d in all_data:
d['Alley'] = d['Alley'].fillna('None' )<drop_column>
%%time
m_lgb = lgb.train(params, train_data, valid_sets = [fake_valid_data], verbose_eval=20 )
combined.drop(['Street','Alley'], axis=1, inplace=True)
 for d in all_data:
d.drop(['Street','Alley'], axis=1, inplace=True )<drop_column>
m_lgb.save_model("model.lgb" )
<feature_engineering><EOS> 
sub.id.nunique() , sub["id"].str.contains("validation$" ).sum()