Kaggle competition: M5 Forecasting - Accuracy
<SOS> metric: M5_WRMSSE Kaggle data source: m5-forecasting-accuracy<save_to_csv>
from datetime import datetime, timedelta
import gc
import numpy as np, pandas as pd
import lightgbm as lgb
result.to_csv("submission.csv", index = False )<compute_test_metric>
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" }
def haversine_array(lat1, lng1, lat2, lng2):
lat1, lng1, lat2, lng2 = map(np.radians,(lat1, lng1, lat2, lng2))
AVG_EARTH_RADIUS = 6371
lat = lat2 - lat1
lng = lng2 - lng1
d = np.sin(lat * 0.5)** 2 + np.cos(lat1)* np.cos(lat2)* np.sin(lng * 0.5)** 2
h = 2 * AVG_EARTH_RADIUS * np.arcsin(np.sqrt(d))
return h
def bearing_array(lat1, lng1, lat2, lng2):
AVG_EARTH_RADIUS = 6371
lng_delta_rad = np.radians(lng2 - lng1)
 lat1, lng1, lat2, lng2 = map(np.radians,(lat1, lng1, lat2, lng2))
y = np.sin(lng_delta_rad)* np.cos(lat2)
 x = np.cos(lat1)* np.sin(lat2)- np.sin(lat1)* np.cos(lat2)* np.cos(lng_delta_rad)
 return np.degrees(np.arctan2(y, x))<feature_engineering>
pd.options.display.max_columns = 50
def preprocess(df):
df['pickup_datetime'] = pd.to_datetime(df['pickup_datetime'])
 df['pickup_year'] = df['pickup_datetime'].dt.year
df['pickup_month'] = df['pickup_datetime'].dt.month
df['pickup_day'] = df['pickup_datetime'].dt.day
df['pickup_hour'] = df['pickup_datetime'].dt.hour + 1
df['pickup_weekday'] = df['pickup_datetime'].dt.weekday + 1
df['pickup_minute'] = df['pickup_datetime'].dt.minute
df['pickup_seconde'] = df['pickup_datetime'].dt.minute * 60
df['store_and_fwd_flag'] = pd.get_dummies(df['store_and_fwd_flag'], drop_first=True)
 df['pickup_datetime'] = pd.to_numeric(df['pickup_datetime'], errors='coerce')
 df['bearing'] = df.apply(lambda x: bearing_array(x['pickup_latitude'], x['pickup_longitude'], x['dropoff_latitude'], x['dropoff_longitude']),axis=1)
 df.loc[:, 'center_latitude'] =(df['pickup_latitude'].values + df['dropoff_latitude'].values)/ 2
df.loc[:, 'center_longitude'] =(df['pickup_longitude'].values + df['dropoff_longitude'].values)/ 2
df['distance'] = df.apply(lambda x: haversine_array(x['pickup_latitude'], x['pickup_longitude'], x['dropoff_latitude'], x['dropoff_longitude']),axis=1)
<load_from_csv>
h = 28
max_lags = 57
tr_last = 1913 + 28
fday = datetime(2016,4, 25)+ timedelta(days= 28)
 fday,tr_last,max_lags
dataDir = '.. /input/'
df_train = pd.read_csv(dataDir + 'train.csv', index_col='id')
 df_test = pd.read_csv(dataDir + 'test.csv', index_col='id' )<filter>
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_evaluation.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
df_train = df_train[df_train.trip_duration < 3600]<prepare_x_and_y>
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" )
EXCLUDES = ['trip_duration', 'dropoff_datetime']
df_train['passenger_count'] = df_train.passenger_count.map(lambda x: 1 if x == 0 else x)
 df_train = df_train[df_train.passenger_count <= 6]
X = df_train[get_columns_selected(df_train, EXCLUDES)]
y = df_train.trip_duration
X.shape, y.shape<compute_train_metric>
FIRST_DAY = 350
cv = ShuffleSplit(4, test_size=0.01, train_size=0.02, random_state=0)
 rf = RandomForestRegressor()
losses = -cross_val_score(rf, X, y, cv=cv, scoring='neg_mean_squared_log_error')
 losses = [np.sqrt(l)for l in losses]
np.mean(losses )<train_model>
df.dropna(inplace = True)
 df.shape
rf.fit(X, y )<predict_on_test>
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"]
X_test = df_test[get_columns_selected(df_test, [])]
y_pred = rf.predict(X_test)
 y_pred.mean()<load_from_csv>
submission = pd.read_csv(dataDir + 'sample_submission.csv')
 submission.head()<prepare_output>
%%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 )
submission['trip_duration'] = y_pred
submission.head()<save_to_csv>
del df, X_train, y_train, fake_valid_inds,train_inds ; gc.collect()
submission.to_csv('submission.csv', index=False )<save_to_csv>
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,
}
submission.to_csv('submission.csv', index=False )<load_from_csv>
%%time
m_lgb = lgb.train(params, train_data, valid_sets = [fake_valid_data], verbose_eval=20 )
df_train = pd.read_csv(os.path.join('.. ', 'input', 'train.csv'), index_col=0 )<count_duplicates>
m_lgb.save_model("model.lgb" )
<count_duplicates><EOS> 
sub.id.nunique() , sub["id"].str.contains("evaluation$" ).sum()