Kaggle competition: Santander Product Recommendation
def fix_name_suffix(blob):
temp = ['Mr.','Miss.','Mrs.','Master.','Dr.','Rev.']
if blob in temp:
return blob[0:len(blob)-1]
else:
return 'no_suffix'<feature_engineering>
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
train_data['NameSuffix'] = train_data['NameSuffix'].apply(fix_name_suffix)
 test_data['NameSuffix'] = test_data['NameSuffix'].apply(fix_name_suffix )<drop_column>
df_train = pd.read_csv('.. /input/juneextra/juneExtra.csv', usecols=train_cols )
del train_data['Name']
del test_data['Name']<data_type_conversions>
df_test = pd.read_csv('.. /input/santander-product-recommendation/test_ver2.csv', usecols = demographic_cols )
train_data.Ticket = [i[0] for i in train_data.Ticket.astype("str")]
test_data.Ticket = [i[0] for i in test_data.Ticket.astype("str")]<feature_engineering>
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']
train_data['Ticket'] = train_data['Ticket'].apply(lambda x: x if x in ['S','P','C','A','W','F','L'] else 'G' )<feature_engineering>
df_train.isnull().sum()
test_data['Ticket'] = test_data['Ticket'].apply(lambda x: x if x in ['S','P','C','A','W','F','L'] else 'G' )<data_type_conversions>
df_train.tiprel_1mes.value_counts()
train_data.Cabin = [i[0] for i in train_data.Cabin.astype("str")]
test_data.Cabin = [i[0] for i in test_data.Cabin.astype("str")]<count_unique_values>
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 )
def most_common(lst):
return max(set(lst), key=lst.count)
 def fix_cabin(blob):
temp = blob.tolist()
temp1 = []
for i in temp :
if i == 'n':
continue
else:
temp1.append(i)
 if temp1 == [] :
return 'Z'
else:
temp1 = most_common(temp1)
 return temp1<categorify>
df_train["renta"] = pd.to_numeric(df_train["renta"], errors="coerce")
 df_test["renta"] = pd.to_numeric(df_test["renta"], errors="coerce" )
train_data['Cabin'] = train_data['Cabin'].groupby(train_data['FamilyName'] ).transform(fix_cabin)
 test_data['Cabin'] = test_data['Cabin'].groupby(test_data['FamilyName'] ).transform(fix_cabin )<drop_column>
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
del train_data['PassengerId']<import_modules>
df_test.renta.fillna(df_test["renta"].median() , inplace=True )
from sklearn.pipeline import Pipeline , FeatureUnion
from sklearn.preprocessing import FunctionTransformer
from sklearn.feature_extraction import DictVectorizer<define_variables>
df_train.isnull().sum()
list_of_obj = []
list_of_num = []
for i in train_data.columns :
if train_data[i].dtypes == 'object':
list_of_obj.append(i)
 else:
if i == 'Survived':
continue
else:
list_of_num.append(i )<split>
df_test.isnull().sum()
def return_text(df):
return df[list_of_obj]<feature_engineering>
replace_mapping = {
"sexo": {"V":0,'H':1},
}
df_train.replace(replace_mapping, inplace= True )
get_text = FunctionTransformer(func=return_text,validate=False )<count_values>
dummy_col = ['sexo','canal_entrada','cod_prov','segmento']
def return_num(df):
return df[list_of_num]<feature_engineering>
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])
 print(use_col)
 for item in df_train[col].unique() :
if item not in use_col:
row_index = df_train[col] == item
print(row_index)
 df_train.loc[row_index,col] = np.nan
print(df_train.loc[row_index,col])
 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
get_numerical = FunctionTransformer(func=return_num,validate=False )<choose_model_class>
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 )
num_pipeline = Pipeline([ 
('numerical',get_numerical),
] )<categorify>
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 )
def return_dict(blob):
return blob.to_dict("records" )<define_variables>
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 = ensemble.RandomForestClassifier(n_estimators=60, n_jobs=-1,max_depth=10, min_samples_split=10, verbose=1)
 clf.fit(x_train, y_train)
 p_train1 = clf.predict_proba(x_train)[:,1]
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)
 print(roc_auc_score(y_train, p_train2))
text_pipeline = Pipeline([ 
('textual',get_text), 
('dictifier',FunctionTransformer(func=return_dict,validate=False)) , 
('vectorizer',DictVectorizer(sort=False)) ,
] )<import_modules>
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' )
from sklearn.model_selection import train_test_split<import_modules>
df_recent = pd.read_csv('.. /input/santander-product-recommendation/train_ver2.csv',usecols=['ncodpers'] + product_col)
from sklearn.model_selection import train_test_split<split>
sample = pd.read_csv('.. /input/santander-product-recommendation/sample_submission.csv' )
X_train, X_test, y_train, y_test = train_test_split(
...train_data.drop(['Survived'],axis=1), train_data['Survived'], test_size=0.2, random_state=42 )<import_modules>
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))
from sklearn.metrics import confusion_matrix , classification_report, roc_auc_score<import_modules>
sample['added_products'] = test_preds
import xgboost as xgb<choose_model_class>
sample.to_csv('RForest_demographic_sub.csv', index=False)
 print(datetime.datetime.now() -start_time)