Kaggle competition: Santander Product Recommendation
preds_xgb = pipeline.predict(X_test )<compute_test_metric>
start_time = datetime.datetime.now()
demographic_cols = ['fecha_dato',
'ncodpers','ind_empleado','pais_residencia','sexo','age','fecha_alta','ind_nuevo','antiguedad','indrel',
'indrel_1mes','tiprel_1mes','indresi','indext','conyuemp','canal_entrada','indfall',
'tipodom','cod_prov','ind_actividad_cliente','renta','segmento']
notuse = ["ult_fec_cli_1t","nomprov"]
product_col = [
'ind_ahor_fin_ult1','ind_aval_fin_ult1','ind_cco_fin_ult1','ind_cder_fin_ult1','ind_cno_fin_ult1','ind_ctju_fin_ult1',
'ind_ctma_fin_ult1','ind_ctop_fin_ult1','ind_ctpp_fin_ult1','ind_deco_fin_ult1','ind_deme_fin_ult1',
'ind_dela_fin_ult1','ind_ecue_fin_ult1','ind_fond_fin_ult1','ind_hip_fin_ult1','ind_plan_fin_ult1',
'ind_pres_fin_ult1','ind_reca_fin_ult1','ind_tjcr_fin_ult1','ind_valo_fin_ult1','ind_viv_fin_ult1','ind_nomina_ult1',
'ind_nom_pens_ult1','ind_recibo_ult1']
train_cols = demographic_cols + product_col
print(confusion_matrix(y_test,preds_xgb))
print(roc_auc_score(y_test,preds_xgb))
print(classification_report(y_test,preds_xgb))<import_modules>
df_train = pd.read_csv('.. /input/juneextra/juneExtra.csv', usecols=train_cols )
from sklearn.model_selection import RandomizedSearchCV<define_search_space>
df_test = pd.read_csv('.. /input/santander-product-recommendation/test_ver2.csv', usecols = demographic_cols )
params = {
"clf__learning_rate" : list(np.arange(0.05,0.6,0.05)) ,
"clf__max_depth" : list(np.arange(1,20,2)) ,
"clf__min_child_weight" : list(np.arange(1,9,1)) ,
"clf__gamma" : list(np.arange(1,20,1)) ,
"clf__colsample_bytree" : [ 0.3, 0.4, 0.5 , 0.7 ],
"clf__subsample" : list(np.arange(0.1,0.9,0.1)) ,
"clf__n_estimators" : [200,500,800,1000,1500,2000],
"clf__reg_alpha" : list(np.arange(0.1,0.9,0.1))
}<choose_model_class>
df_train = df_train[df_train['ind_nuevo'] == 0]
df_train = df_train[df_train['antiguedad'] != -999999]
df_train = df_train[df_train['indrel'] == 1]
df_train = df_train[df_train['indresi'] == 'S']
df_train = df_train[df_train['indfall'] == 'N']
df_train = df_train[df_train['tipodom'] == 1]
df_train = df_train[df_train['ind_empleado'] == 'N']
df_train = df_train[df_train['pais_residencia'] == 'ES']
df_train = df_train[df_train['indrel_1mes'] == 1]
df_train = df_train[df_train['tiprel_1mes'] ==('A' or 'I')]
df_train = df_train[df_train['indext'] == 'N']
grid = RandomizedSearchCV(pipeline,
param_distributions=params,
scoring='roc_auc',cv=5,verbose=5 )<train_model>
drop_column = ['ind_nuevo','indrel','indresi','indfall','tipodom','ind_empleado','pais_residencia','indrel_1mes','indext','conyuemp','fecha_alta','tiprel_1mes']
df_train.drop(drop_column, axis=1, inplace = True)
 df_test.drop(drop_column, axis=1, inplace = True )
grid.fit(X_train,y_train )<find_best_params>
df_train["renta"] = pd.to_numeric(df_train["renta"], errors="coerce")
 df_test["renta"] = pd.to_numeric(df_test["renta"], errors="coerce" )
grid.best_params_, grid.best_score_<init_hyperparams>
for cod in unique_prov:
df_test.loc[df_test['cod_prov']==cod,['renta']] = df_test.loc[df_test['cod_prov']==cod,['renta']].fillna({'renta':grouped[cod]} ).values
df_train.loc[df_train['cod_prov']==cod,['renta']] = df_train.loc[df_train['cod_prov']==cod,['renta']].fillna({'renta':grouped[cod]} ).values
best_matrix = {'subsample': 0.30000000000000004,
'reg_alpha': 0.2,
'n_estimators': 500,
'min_child_weight': 3,
'max_depth': 9,
'learning_rate': 0.15000000000000002,
'gamma': 4,
'colsample_bytree': 0.3}<choose_model_class>
df_test.renta.fillna(df_test["renta"].median() , inplace=True )
xgb_model = xgb.XGBClassifier(**best_matrix,silent=False,
eval_metric = 'auc' )<choose_model_class>
replace_mapping = {
"sexo": {"V":0,'H':1},
}
df_train.replace(replace_mapping, inplace= True )
finalized_model = pipeline = Pipeline([ 
('union',FeatureUnion(
 transformer_list = [ 
('num',num_pipeline), 
('text',text_pipeline)
 ])) , 
('clf',xgb_model)
 ] )<prepare_x_and_y>
dummy_col = ['sexo','canal_entrada','cod_prov','segmento']
X = train_data.drop(['Survived'],axis=1)
 y = train_data['Survived']<train_model>
limit = int(0.05 * len(df_train.index))
for col in dummy_col:
if len(df_train[col].unique())> 6:
trainlist = df_train[col].value_counts()
print(trainlist)
 use_col = []
for i,item in enumerate(trainlist):
if item > limit:
use_col.append(df_train[col].value_counts().index[i])
 for item in df_train[col].unique() :
if item not in use_col:
row_index = df_train[col] == item
df_train.loc[row_index,col] = np.nan
for item in df_test[col].unique() :
if item not in use_col:
row_index = df_test[col] == item
df_test.loc[row_index,col] = np.nan
finalized_model.fit(X,y )<drop_column>
df_train = pd.get_dummies(df_train, prefix=dummy_col, columns = dummy_col)
 df_test = pd.get_dummies(df_test, prefix=dummy_col, columns = dummy_col )
final_test = test_data.drop(['PassengerId'],axis=1 )<define_variables>
df_train["age"] = pd.to_numeric(df_train["age"], errors="coerce")
 df_test["age"] = pd.to_numeric(df_test["age"], errors="coerce")
 age_group = [[0,19],[19,26],[26,36],[36,41],[41,47],[47,55],[55,60],[60,70],[70,80],[80,170]]
def create_age_group(df):
df['age_group'] = np.nan
for i,age in enumerate(age_group):
row_index =(df['age'] >= age[0])&(df['age'] < age[1])
 df.loc[row_index,'age_group'] = i
create_age_group(df_train)
 create_age_group(df_test)
 df_train.drop('age', axis=1, inplace = True)
 df_test.drop('age', axis=1, inplace = True )
PassengerId = test_data['PassengerId']<predict_on_test>
models = {}
model_preds = {}
id_preds = defaultdict(list)
 ids = df_test['ncodpers'].values
for c in product_col:
if c != 'ncodpers':
print(c)
 y_train = df_train[c]
x_train = df_train.drop(product_col + ['ncodpers',"fecha_dato"], 1)
 clf = LogisticRegression()
clf.fit(x_train, y_train)
 x_train2 = df_test.drop(['ncodpers',"fecha_dato"], 1)
 p_train = clf.predict_proba(x_train2)[:,1]
p_train2 = clf.predict_proba(x_train)[:,1]
models[c] = clf
model_preds[c] = p_train
for id, p in zip(ids, p_train):
id_preds[id].append(p)
final_prediction = finalized_model.predict(final_test )<save_to_csv>
df_recent = pd.read_csv('.. /input/santander-product-recommendation/train_ver2.csv',usecols=['ncodpers'] + product_col)
 df_recent = df_recent.drop_duplicates(['ncodpers'], keep='last' )
submission = pd.DataFrame({ 'PassengerId': PassengerId,
'Survived': final_prediction })
 submission.to_csv(path_or_buf ="Titanic_Submission.csv", index=False )<import_modules>
df_recent = pd.read_csv('.. /input/santander-product-recommendation/train_ver2.csv',usecols=['ncodpers'] + product_col)
import pandas as pd
import numpy as np<load_from_csv>
sample = pd.read_csv('.. /input/santander-product-recommendation/sample_submission.csv' )
train=pd.read_csv(".. /input/train.csv")
 test=pd.read_csv(".. /input/test.csv" )<drop_column>
already_active = {}
for row in df_recent.values:
row = list(row)
 id = row.pop(0)
 active = [c[0] for c in zip(tuple(product_col), row)if c[1] > 0]
already_active[id] = active
train_preds = {}
for id, p in id_preds.items() :
preds = [i[0] for i in sorted([i for i in zip(tuple(product_col), p)if i[0] not in already_active[id]],
key=lambda i:i [1],
reverse=True)[:7]]
train_preds[id] = preds
test_preds = []
for row in sample.values:
id = row[0]
p = train_preds[id]
test_preds.append(' '.join(p))
train.drop(['Name'],axis=1,inplace=True )<load_from_csv>
sample['added_products'] = test_preds
sample_sub=pd.read_csv(".. /input/gender_submission.csv" )<drop_column>
sample.to_csv('LR_sub.csv', index=False)
 print(datetime.datetime.now() -start_time)