Kaggle competition: Predict Future Sales
<SOS> metric: rmse Kaggle data source: predict-future-sales<compute_test_metric>
import numpy as np
import pandas as pd
import scipy
import sklearn
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OrdinalEncoder
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
from itertools import product
from sklearn.cluster import KMeans
import lightgbm as lgb
_ = feature_importance(vc3.estimators_[0], X_train.drop(lgb_drop_cols, axis=1), display_results=True )<define_variables>
dpath = '.. /input/competitive-data-science-predict-future-sales/'
adpath ='.. /input/predict-future-sales/'
et_drop_cols = ['agg18_age_MAX', 'agg18_age_MEAN', 'agg18_age_MIN', 'agg18_dis_MEAN',
'agg18_escolari_MAX', 'agg18_escolari_MEAN', 'agg18_escolari_MIN',
'agg18_estadocivil1_COUNT', 'agg18_estadocivil1_MEAN',
'agg18_estadocivil2_COUNT', 'agg18_estadocivil2_MEAN',
'agg18_estadocivil3_COUNT', 'agg18_estadocivil3_MEAN',
'agg18_estadocivil4_COUNT', 'agg18_estadocivil4_MEAN',
'agg18_estadocivil5_COUNT', 'agg18_estadocivil5_MEAN',
'agg18_estadocivil6_COUNT', 'agg18_estadocivil6_MEAN',
'agg18_estadocivil7_COUNT', 'agg18_estadocivil7_MEAN',
'agg18_parentesco10_COUNT', 'agg18_parentesco10_MEAN',
'agg18_parentesco11_COUNT', 'agg18_parentesco11_MEAN',
'agg18_parentesco12_COUNT', 'agg18_parentesco12_MEAN',
'agg18_parentesco1_COUNT', 'agg18_parentesco1_MEAN',
'agg18_parentesco2_COUNT', 'agg18_parentesco2_MEAN',
'agg18_parentesco3_COUNT', 'agg18_parentesco3_MEAN',
'agg18_parentesco4_COUNT', 'agg18_parentesco4_MEAN',
'agg18_parentesco5_COUNT', 'agg18_parentesco5_MEAN',
'agg18_parentesco6_COUNT', 'agg18_parentesco6_MEAN',
'agg18_parentesco7_COUNT', 'agg18_parentesco7_MEAN',
'agg18_parentesco8_COUNT', 'agg18_parentesco8_MEAN',
'agg18_parentesco9_COUNT', 'agg18_parentesco9_MEAN',
'fe_rent_per_person', 'fe_rent_per_room', 'fe_tablet_adult_density',
'fe_tablet_density', 'r4h1_percent_in_male', 'r4m1_percent_in_female',
'rent_per_adult', 'rez_esc_escolari', 'rez_esc_r4t1', 'rez_esc_age']
et_drop_cols.extend(["idhogar", "parentesco1"] )<init_hyperparams>
df_train = pd.read_csv(dpath + 'sales_train.csv')
 df_test = pd.read_csv(dpath + 'test.csv', index_col='ID')
 df_shops = pd.read_csv(dpath + 'shops.csv', index_col='shop_id')
 df_items = pd.read_csv(dpath + 'items.csv', index_col='item_id')
 df_itemcat = pd.read_csv(dpath + 'item_categories.csv', index_col='item_category_id')
 sample_submission = pd.read_csv(dpath + 'sample_submission.csv', index_col='ID' )
rf_params_1 = {"max_depth": None, "min_impurity_decrease": 1e-3, "min_samples_leaf": 2, "min_samples_split": 3, "n_estimators":750 }
rf_params_2 = {"max_depth": 25, "min_impurity_decrease": 1e-3, "min_samples_leaf": 2, "min_samples_split": 3, "n_estimators":700 }
rf_params_3 = {"max_depth": 31, "min_impurity_decrease": 1e-4, "min_samples_leaf": 3, "min_samples_split": 2, "n_estimators":850 }
rf_params_4 = {"max_depth": 32, "min_impurity_decrease": 1e-3, "min_samples_leaf": 2, "min_samples_split": 2, "n_estimators":950 }
rf_params_5 = {"max_depth": 29, "min_impurity_decrease": 1e-3, "min_samples_leaf": 2, "min_samples_split": 2, "n_estimators":800 }
rf_param_list = [rf_params_1, rf_params_2, rf_params_3, rf_params_4, rf_params_5]<train_on_grid>
calendar = pd.read_csv(adpath + 'calendar.csv', dtype='int16' )
ets = []
for i in range(10):
rf_params = rf_param_list[i % len(rf_param_list)]
rf = RandomForestClassifier(random_state=217+i, n_jobs=4, verbose=0, class_weight="balanced", **rf_params)
 ets.append(( 'rf{}'.format(i), rf))
vc2 = VotingClassifier(ets, voting='soft')
 _ = vc2.fit(X_train.drop(et_drop_cols, axis=1), y_train )<compute_train_metric>
def shop_name2city(sn):
sn = sn.split() [0]
if sn == 'Цифровой' or sn == 'Интернет-магазин': sn = 'Internet'
if sn[0] == '!': sn = sn[1:]
return sn
df_shops['city'] = df_shops['shop_name'].apply(shop_name2city)
 df_shops['city_enc'] = LabelEncoder().fit_transform(df_shops['city'] ).astype('int8')
 city_info = pd.read_pickle(adpath + 'city_info.pkl')
 df_shops['city_size'] = df_shops['city'].map(city_info['city_size'] )
vc2.voting = 'soft'
global_rf_score_soft = f1_score(y_test, vc2.predict(X_test.drop(et_drop_cols, axis=1)) , average='macro')
 vc2.voting = 'hard'
global_rf_score_hard = f1_score(y_test, vc2.predict(X_test.drop(et_drop_cols, axis=1)) , average='macro')
 print('Validation score of a VotingClassifier on RF with soft voting strategy: {:.4f}'.format(global_rf_score_soft))
print('Validation score of a VotingClassifier on RF with hard voting strategy: {:.4f}'.format(global_rf_score_hard))<compute_train_metric>
class Items() :
def __init__(self, df_items, df_itemcat):
self.df_items = df_items
self.df_itemcat = df_itemcat
self.set_hl_cat()
self.make_items_ext()
self.item_features = ['item_category_id', 'hl_cat_id']
def set_hl_cat(self):
self.df_itemcat['hl_cat_id'] = self.df_itemcat['item_category_name'].str.split(n=1, expand=True)[0]
self.df_itemcat['hl_cat_id'] = LabelEncoder().fit_transform(self.df_itemcat['hl_cat_id'])
 def make_items_ext(self):
self.df_items = df_items.merge(self.df_itemcat, how = 'left',
left_on = 'item_category_id', right_index = True)
 def get_items_df(self):
return self.df_items[self.item_features].astype('int32' )
vc2.voting = 'soft'
global_rf_score_soft = f1_score(y_test, vc2.predict(X_test.drop(et_drop_cols, axis=1)) , average='macro')
 vc2.voting = 'hard'
global_rf_score_hard = f1_score(y_test, vc2.predict(X_test.drop(et_drop_cols, axis=1)) , average='macro')
 print('Validation score of a VotingClassifier on RF with soft voting strategy: {:.4f}'.format(global_rf_score_soft))
print('Validation score of a VotingClassifier on RF with hard voting strategy: {:.4f}'.format(global_rf_score_hard))<compute_train_metric>
items = Items(df_items, df_itemcat )
vc2.voting = 'soft'
global_rf_score_soft = f1_score(y_test, vc2.predict(X_test.drop(et_drop_cols, axis=1)) , average='macro')
 vc2.voting = 'hard'
global_rf_score_hard = f1_score(y_test, vc2.predict(X_test.drop(et_drop_cols, axis=1)) , average='macro')
 print('Validation score of a VotingClassifier on RF with soft voting strategy: {:.4f}'.format(global_rf_score_soft))
print('Validation score of a VotingClassifier on RF with hard voting strategy: {:.4f}'.format(global_rf_score_hard))<predict_on_test>
class TT_Extended() :
def __init__(self, df_train, df_test, items, df_shops, calendar, cmode, verbose=True):
self.info = verbose
self.df_train = df_train.copy()
self.df_test = df_test.copy()
self.df_shops = df_shops.copy()
self.calendar = self.set_calender(calendar.copy())
 self.idx_columns = ['date_block_num', 'shop_id', 'item_id']
self.df_test['date_block_num'] = 34
self.df_test['item_cnt_month'] = 0.
 self.df_test['item_cnt_month'] = self.df_test['item_cnt_month'].astype('float32')
 self.df_train[self.idx_columns] = self.df_train[self.idx_columns].astype('int32')
 self.df_test[self.idx_columns] = self.df_test[self.idx_columns].astype('int32')
 self.df_train_cleaning(cmode)
 self.item_mean_features = []
self.shop_mean_features = []
self.df_items = items.get_items_df()
self.item_ext_features = list(self.df_items.columns)
 self.df_items_ext = self.items_ext()
self.df_bb = self.build_bb()
self.df_train_ext = self.df_train_agg(cmin = 0, cmax = 1000, drop = None)
 self.add_train_df()
self.df_train_ext = self.df_train_extention()
def df_train_cleaning(self, mode):
assert mode in ['keep', 'drop', 'block', 'total', 't+b']
if self.info: print('Cleaning train dataframe...( Mode -', mode, ')')
 shop_idx = self.df_train[(self.df_train['shop_id'] == 9)| 
(self.df_train['shop_id'] == 20)].index
self.df_train.drop(shop_idx, inplace=True)
 self.df_train = self.df_train[(self.df_train['item_price'] > 0)& 
(self.df_train['item_price'] < 51000)]
self.df_train = self.df_train[self.df_train['item_cnt_day'] <= 1000]
shop_repl_dict = {0 : 57, 1 : 58, 11 : 10, 40 : 39}
self.df_train['shop_id'] = self.df_train['shop_id'].apply(
 lambda s: shop_repl_dict.get(s)if s in shop_repl_dict else s)
 if mode == 'drop':
self.df_train = self.df_train[self.df_train['item_cnt_day'] > 0]
elif mode == 'block':
item_block_cnt = self.df_train.groupby(['date_block_num', 'shop_id', 'item_id'])['item_cnt_day'].sum()
items_to_drop = item_block_cnt[item_block_cnt <= 0].index
self.df_train = self.df_train[~self.df_train.set_index(
 ['date_block_num', 'shop_id', 'item_id'] ).index.isin(items_to_drop)]
elif mode == 'total':
item_total_cnt = self.df_train.groupby(['shop_id', 'item_id'])['item_cnt_day'].sum()
items_to_drop = item_total_cnt[item_total_cnt <= 0].index
self.df_train = self.df_train[~self.df_train.set_index(
 ['shop_id', 'item_id'] ).index.isin(items_to_drop)]
elif mode == 't+b':
item_total_cnt = self.df_train.groupby(['shop_id', 'item_id'])['item_cnt_day'].sum()
items_to_drop = item_total_cnt[item_total_cnt <= 0].index
self.df_train = self.df_train[~self.df_train.set_index(
 ['shop_id', 'item_id'] ).index.isin(items_to_drop)]
item_block_cnt = self.df_train.groupby(['date_block_num', 'shop_id', 'item_id'])['item_cnt_day'].sum()
items_to_drop = item_block_cnt[item_block_cnt <= 0].index
self.df_train = self.df_train[~self.df_train.set_index(
 ['date_block_num', 'shop_id', 'item_id'] ).index.isin(items_to_drop)]
return
def set_calender(self, calendar):
calendar['date_block_num'] =(calendar['year'] - 2013)*12 +(calendar['month'] - 1)
 calendar['hdays'] = calendar['mdays'] - calendar['wdays']
calendar.set_index('date_block_num', inplace=True)
 return calendar
def items_ext(self):
dfi = self.df_items.copy()
dfi['fsb'] = self.df_train.groupby('item_id')['date_block_num'].min()
dfi['fsb'].fillna(34, inplace=True)
 dfi['fsb'] = dfi['fsb'].astype('int8')
 self.item_ext_features += ['fsb']
return dfi
def build_bb(self):
if self.info: print('Building index dataframe...')
 df_work = []
for block_num in self.df_train['date_block_num'].unique() :
cur_shops = self.df_train.loc[self.df_train['date_block_num'] == block_num, 'shop_id'].unique()
cur_items = self.df_train.loc[self.df_train['date_block_num'] == block_num, 'item_id'].unique()
df_work.append(np.array(list(product(*[[block_num], cur_shops, cur_items])) , dtype='int32'))
df_work = pd.DataFrame(np.vstack(df_work), columns = self.idx_columns)
 return df_work
def df_train_agg(self, cmin = 0, cmax = 20, drop = None):
if self.info: print('Aggregation...')
 df_work = self.df_train.groupby(self.idx_columns ).agg({'item_price' : np.mean,
'item_cnt_day': np.sum})
 df_work.reset_index(inplace=True)
 df_work = df_work.rename(columns={'item_cnt_day': 'item_cnt_month'})
 df_work = pd.merge(self.df_bb, df_work, on=self.idx_columns, how='left')
 df_work['item_cnt_month'] = df_work['item_cnt_month'].astype('float32' ).fillna(0.).clip(cmin, cmax)
 df_work['item_price'] = df_work['item_price'].astype('float32' ).fillna(0.)
df_tmp = self.df_train[self.df_train['item_cnt_day'] > 0].groupby(self.idx_columns ).agg({'item_cnt_day': 'count'})
 df_tmp.reset_index(inplace=True)
 df_tmp = df_tmp.rename(columns={'item_cnt_day': 'item_rate_month'})
 df_work = pd.merge(df_work, df_tmp, on=self.idx_columns, how='left')
 df_work['item_rate_month'] = df_work['item_rate_month'].astype('float32' ).fillna(0.)
del df_tmp
if drop: df_work.drop(drop, axis=1, inplace=True)
 return df_work
def add_train_df(self):
self.df_train_ext = pd.concat([self.df_train_ext, self.df_test], ignore_index=True,
sort=False, keys=self.idx_columns)
 def add_item_means(self, df, feature = None):
if feature == None :
group_items = ['date_block_num','item_id']
feature = 'item_cnt'
else:
group_items = ['date_block_num','item_id'] + [feature]
feature_mean_name = feature + '_mean'
if self.info: print('Adding item means for', feature, '...')
 df_tmp = df.groupby(group_items)['item_cnt_month'].mean()
df_tmp = df_tmp.reset_index().rename(columns = {'item_cnt_month': feature_mean_name})
 df = pd.merge(df, df_tmp, on=group_items, how='left')
 self.item_mean_features.append(feature_mean_name)
 del df_tmp
return df
def add_shop_means(self, df, feature):
group_items = ['date_block_num', 'shop_id'] + [feature]
feature_mean_name = feature + '_mean'
if self.info: print('Adding shop means for', feature, '...')
 df_tmp = df.groupby(group_items)['item_cnt_month'].mean()
df_tmp = df_tmp.reset_index().rename(columns = {'item_cnt_month': feature_mean_name})
 df = pd.merge(df, df_tmp, on=group_items, how='left')
 self.shop_mean_features.append(feature)
 del df_tmp
return df
def df_train_extention(self, test_cat_only = False):
df_work = self.df_train_ext.merge(df_shops[['city_enc', 'city_size']], how = 'left', on = 'shop_id')
 df_work = df_work.merge(self.calendar[['mdays', 'wdays', 'hdays']],
how = 'left', left_on = 'date_block_num', right_index = True)
 df_work = df_work.merge(self.df_items_ext[self.item_ext_features],
how = 'left', left_on = 'item_id', right_index = True)
 ssbn = self.df_train.groupby('shop_id')['date_block_num'].min().astype('int8')
 ssbn.name = 'ssbn'
df_work = df_work.merge(ssbn, how = 'left', on = 'shop_id')
 if test_cat_only:
test_cat = df_work[df_work['date_block_num'] == 34]['item_category_id'].unique()
df_work = df_work[df_work['item_category_id'].isin(test_cat)]
return df_work
def make_base_df(self, keepnans = False):
df_work = self.df_train_ext.copy()
if keepnans:
fill_value = None
else:
fill_value = 0
df_work = pd.pivot_table(df_work, values='item_cnt_month', index=['shop_id', 'item_id'],
columns = 'date_block_num', aggfunc=np.sum, fill_value = fill_value)
 df_work.columns.name = ''
return df_work
def add_total_cnt(self, df):
if self.info: print('Adding total count...')
 df_base = self.make_base_df()
for i in range(1, 33):
df_base[i + 1] += df_base[i]
df_base = df_base.shift(1, axis=1 ).loc[:, 1:].astype('int32')
 df_base = df_base.melt(var_name='date_block_num', value_name='total_cnt', ignore_index=False)
 df = df.merge(df_base, how='left', on=self.idx_columns)
 del df_base
return df
def add_item_lags(self, df, feature_name, nlags=3, keepnans = False):
if self.info: print('Adding item lags for', feature_name, '...')
 df_tmp = df[['date_block_num', 'shop_id', 'item_id', feature_name]]
for i in range(nlags, 0, -1):
lag_feature_name = feature_name +'_lag-' + str(i)
 df_shifted = df_tmp.copy()
df_shifted.columns = ['date_block_num', 'shop_id', 'item_id', lag_feature_name]
df_shifted['date_block_num'] += i
df = pd.merge(df, df_shifted, on=['date_block_num', 'shop_id', 'item_id'], how='left')
 if keepnans:
df[lag_feature_name] = df[lag_feature_name].astype('float32')
 else:
df[lag_feature_name] = df[lag_feature_name].fillna(0 ).astype('float32')
 del df_tmp
return df
def add_shop_lags(self, df, feature_name, nlags=3):
mean_feature_name = feature_name + '_mean'
if self.info: print('Adding lags for', mean_feature_name, '...')
 df_tmp = df[['date_block_num', 'shop_id', feature_name, mean_feature_name]]
for i in range(nlags, 0, -1):
lag_feature_name = mean_feature_name + '_lag-' + str(i)
 df_shifted = df_tmp.copy()
df_shifted.columns = ['date_block_num', 'shop_id', feature_name, lag_feature_name]
df_shifted['date_block_num'] += i
df = pd.merge(df, df_shifted.drop_duplicates() , on=['date_block_num', 'shop_id', feature_name], how='left')
 df[lag_feature_name] = df[lag_feature_name].fillna(0 ).astype('float32')
 del df_tmp
del df_shifted
return df
def shop_clustering(self, df_work):
print('No shop clusters provided')
 return df_work
def build_work_db(self, hd, item_mean_features = [], shop_mean_features = [], add_total_cnt = False):
if self.info: print('Building work dataframe...')
 df_work = self.df_train_ext.copy()
df_work = self.add_item_means(df_work)
 for mf in item_mean_features:
df_work = self.add_item_means(df_work, mf)
 for mf in shop_mean_features:
df_work = self.add_shop_means(df_work, mf)
 df_work = self.add_item_lags(df_work, 'item_cnt_month', hd, keepnans = False)
 df_work = self.add_item_lags(df_work, 'item_rate_month', hd)
 df_work = self.add_item_lags(df_work, 'item_price', hd)
 for mf in self.item_mean_features:
df_work = self.add_item_lags(df_work, mf, hd)
 for mf in self.shop_mean_features:
df_work = self.add_shop_lags(df_work, mf, hd)
 df_work.drop(df_work[df_work['date_block_num'] < hd].index, inplace=True)
 df_work.drop(self.item_mean_features, axis=1, inplace=True)
 df_work.drop(['item_category_id_mean', 'item_price', 'item_rate_month'], axis=1, inplace=True)
 self.item_mean_features = []
self.shop_mean_features = []
df_work['qmean'] = df_work[['item_cnt_month_lag-1',
'item_cnt_month_lag-2',
'item_cnt_month_lag-3']].mean(skipna=True, axis=1)
 df_work['new'] = df_work['fsb'] == df_work['date_block_num']
df_work['fsb'] = df_work['date_block_num'] - df_work['fsb']
df_work['ssbn'] = df_work['date_block_num'] - df_work['ssbn']
df_work['month'] =(df_work['date_block_num']%12 ).astype('int8')
 idx = df_work[(df_work['item_price_lag-1'] == 0)&(df_work['item_price_lag-2'] != 0)].index
df_work.loc[idx, 'item_price_lag-1'] = df_work.loc[idx, 'item_price_lag-2']
idx = df_work[(df_work['item_price_lag-2'] == 0)&(df_work['item_price_lag-3'] != 0)].index
df_work.loc[idx, 'item_price_lag-2'] = df_work.loc[idx, 'item_price_lag-3']
df_work['grad-1'] = df_work['item_cnt_month_lag-1']/df_work['item_cnt_month_lag-2']
df_work['grad-1'] = df_work['grad-1'].replace([np.inf, -np.inf], np.nan ).fillna(0.)
df_work['grad-2'] = df_work['item_cnt_month_lag-2']/df_work['item_cnt_month_lag-3']
df_work['grad-2'] = df_work['grad-2'].replace([np.inf, -np.inf], np.nan ).fillna(0.)
df_work = self.shop_clustering(df_work)
 if add_total_cnt: df_work = self.add_total_cnt(df_work)
 col2clip = ['item_cnt_month',
'item_cnt_month_lag-3', 'item_cnt_month_lag-2', 'item_cnt_month_lag-1',
'item_cnt_mean_lag-3', 'item_cnt_mean_lag-2','item_cnt_mean_lag-1',
'city_enc_mean_lag-3', 'city_enc_mean_lag-2', 'city_enc_mean_lag-1',
'item_category_id_mean_lag-3', 'item_category_id_mean_lag-2', 'item_category_id_mean_lag-1',
'qmean']
df_work[col2clip] = df_work[col2clip].clip(0, 20)
 return df_work
def get_work_db(self, hd = 3, item_mean_features = [],
shop_mean_features = [],
drop_features = None,
add_total_cnt = False):
df_work = self.build_work_db(hd, item_mean_features, shop_mean_features, add_total_cnt)
 if drop_features == None:
return df_work
else:
return df_work.drop(drop_features, axis = 1 )
def combine_voters(data, weights=[0.3, 0.3, 0.4], voting="soft"):
vc.voting="soft"
vc1_probs = vc.predict_proba(data.drop(xgb_drop_cols, axis=1))
vc2.voting="soft"
vc2_probs = vc2.predict_proba(data.drop(et_drop_cols, axis=1))
vc3.voting="soft"
vc3_probs = vc3.predict_proba(data.drop(lgb_drop_cols, axis=1))
final_vote =(vc1_probs * weights[0])+(vc2_probs * weights[1])+(vc3_probs * weights[2])
 predictions = np.argmax(final_vote, axis=1)
 if voting=="hard":
vc.voting="hard"
vc1_preds = vc.predict(data.drop(xgb_drop_cols, axis=1))
vc2.voting="hard"
vc2_preds = vc2.predict(data.drop(et_drop_cols, axis=1))
vc3.voting="hard"
vc3_preds = vc3.predict(data.drop(lgb_drop_cols, axis=1))
predictions = np.array(stats.mode(np.column_stack([vc1_preds, vc2_preds, vc3_preds, predictions]), axis=1)[0])[:,0]
return predictions<compute_train_metric>
%%time
pfs = TT_Extended(df_train, df_test, items, df_shops, calendar, cmode='total' )
combo_preds = combine_voters(X_test, weights=[0.33, 0.34, 0.33])
 global_combo_score_soft = f1_score(y_test, combo_preds, average='macro')
 global_combo_score_soft<compute_train_metric>
pfs.shop_clustering = simple_shop_clustering
combo_preds = combine_voters(X_test, weights=[0.4, 0.2, 0.4], voting="hard")
 global_combo_score_soft = f1_score(y_test, combo_preds, average='macro')
 global_combo_score_soft<compute_train_metric>
%%time
df_work = pfs.get_work_db(hd = 3,
item_mean_features = ['city_enc'],
shop_mean_features = ['item_category_id'],
drop_features = ['wdays', 'hdays', 'ssbn'],
add_total_cnt = False ).copy()
combo_preds = combine_voters(X_test, weights=[0.4, 0.3, 0.3])
 global_combo_score_soft= f1_score(y_test, combo_preds, average='macro')
 global_combo_score_soft<compute_train_metric>
X_train = df_work[df_work.date_block_num < 33].drop(['item_cnt_month'], axis=1)
 y_train = df_work[df_work.date_block_num < 33]['item_cnt_month']
X_valid = df_work[df_work.date_block_num == 33].drop(['item_cnt_month'], axis=1)
 y_valid = df_work[df_work.date_block_num == 33]['item_cnt_month']
X_test = df_work[df_work.date_block_num == 34].drop(['item_cnt_month'], axis=1 )
combo_preds = combine_voters(X_test, weights=[0.3, 0.4, 0.3])
 global_combo_score_soft = f1_score(y_test, combo_preds, average='macro')
 global_combo_score_soft<compute_train_metric>
del df_work
combo_preds = combine_voters(X_test, weights=[0.4, 0.5, 0.2])
 global_combo_score_soft = f1_score(y_test, combo_preds, average='macro')
 global_combo_score_soft<compute_train_metric>
%%time
feature_names = X_train.columns.tolist()
params = {
'objective': 'mse',
'metric': 'rmse',
'num_leaves': 255,
'learning_rate': 0.005,
'feature_fraction': 0.75,
'bagging_fraction': 0.75,
'bagging_freq': 5,
'seed': 1,
'verbose': 1,
'force_row_wise' : True
}
categorical_feature_names = [
'item_category_id',
'hl_cat_id',
'city_enc',
'month',
'shop_group'
]
lgb_train = lgb.Dataset(X_train[feature_names], y_train, categorical_feature=None)
 lgb_eval = lgb.Dataset(X_valid[feature_names], y_valid, categorical_feature=None, reference=lgb_train)
 evals_result = {}
gbm = lgb.train(
 params,
lgb_train,
num_boost_round = 4000,
valid_sets =(lgb_train, lgb_eval),
feature_name = feature_names,
categorical_feature = categorical_feature_names,
verbose_eval = 100,
evals_result = evals_result,
early_stopping_rounds = 100 )
<create_dataframe><EOS> 
sample_submission['item_cnt_month'] = gbm.predict(X_test[feature_names] ).clip(0, 20)
 sample_submission.to_csv('submission_k_l3_1.csv' )