Kaggle competition: Santander Value Prediction Challenge
<SOS> metric: RMSLE Kaggle data source: santander-value-prediction-challenge<sort_values>
sub1 = pd.read_csv('.. /input/best-ensemble-score-made-available-0-68/SHAZ13_ENS_LEAKS.csv')
 sub3 = pd.read_csv('.. /input/feature-scoring-vs-zeros/leaky_submission.csv')
 sub2 = pd.read_csv('.. /input/feature-scoring-vs-zeros/leaky_submission.csv')
 train = pd.read_csv('.. /input/santander-value-prediction-challenge/train.csv')
 test = pd.read_csv('.. /input/santander-value-prediction-challenge/test.csv')
 print(train.shape, test.shape )
print('Most common words and weights:
')
 print(sorted(weights.items() , key=lambda x: x[1] if x[1] > 0 else 9999)[:10])
 print('
Least common words and weights: ')
(sorted(weights.items() , key=lambda x: x[1], reverse=True)[:10] )<feature_engineering>
leak_col = []
for c in col:
leak1 = np.sum(( train[c]==train['target'] ).astype(int))
leak2 = np.sum(((( train[c] - train['target'])/ train['target'])< 0.05 ).astype(int))
if leak1 > 30 and leak2 > 3500:
leak_col.append(c)
 print(len(leak_col))
def tfidf_word_match_share(row):
q1words = {}
q2words = {}
for word in str(row['question1'] ).lower().split() :
if word not in stops:
q1words[word] = 1
for word in str(row['question2'] ).lower().split() :
if word not in stops:
q2words[word] = 1
if len(q1words)== 0 or len(q2words)== 0:
return 0
shared_weights = [weights.get(w, 0)for w in q1words.keys() if w in q2words] + [weights.get(w, 0)for w in q2words.keys() if w in q1words]
total_weights = [weights.get(w, 0)for w in q1words] + [weights.get(w, 0)for w in q2words]
R = np.sum(shared_weights)/ np.sum(total_weights)
 return R<compute_test_metric>
col = list(leak_col)
 train = train[col + ['ID', 'target']]
test = test[col + ['ID']]
print('Original AUC:', roc_auc_score(df_train['is_duplicate'], train_word_match))
print(' TFIDF AUC:', roc_auc_score(df_train['is_duplicate'], tfidf_train_word_match.fillna(0)) )<prepare_x_and_y>
train["nz_mean"] = train[col].apply(lambda x: x[x!=0].mean() , axis=1)
 train["nz_max"] = train[col].apply(lambda x: x[x!=0].max() , axis=1)
 train["nz_min"] = train[col].apply(lambda x: x[x!=0].min() , axis=1)
 train["ez"] = train[col].apply(lambda x: len(x[x==0]), axis=1)
 train["mean"] = train[col].apply(lambda x: x.mean() , axis=1)
 train["max"] = train[col].apply(lambda x: x.max() , axis=1)
 train["min"] = train[col].apply(lambda x: x.min() , axis=1)
 test["nz_mean"] = test[col].apply(lambda x: x[x!=0].mean() , axis=1)
 test["nz_max"] = test[col].apply(lambda x: x[x!=0].max() , axis=1)
 test["nz_min"] = test[col].apply(lambda x: x[x!=0].min() , axis=1)
 test["ez"] = test[col].apply(lambda x: len(x[x==0]), axis=1)
 test["mean"] = test[col].apply(lambda x: x.mean() , axis=1)
 test["max"] = test[col].apply(lambda x: x.max() , axis=1)
 test["min"] = test[col].apply(lambda x: x.min() , axis=1)
 col += ['nz_mean', 'nz_max', 'nz_min', 'ez', 'mean', 'max', 'min']
x_train = pd.DataFrame()
x_test = pd.DataFrame()
x_train['word_match'] = train_word_match
x_train['tfidf_word_match'] = tfidf_train_word_match
x_test['word_match'] = df_test.apply(word_match_share, axis=1, raw=True)
 x_test['tfidf_word_match'] = df_test.apply(tfidf_word_match_share, axis=1, raw=True)
 y_train = df_train['is_duplicate'].values<concatenate>
for i in range(2, 100):
train['index'+str(i)] =(( train.index + 2)% i == 0 ).astype(int)
 test['index'+str(i)] =(( test.index + 2)% i == 0 ).astype(int)
 col.append('index'+str(i))
pos_train = x_train[y_train == 1]
neg_train = x_train[y_train == 0]
p = 0.165
scale =(( len(pos_train)/(len(pos_train)+ len(neg_train)))/ p)- 1
while scale > 1:
neg_train = pd.concat([neg_train, neg_train])
 scale -=1
neg_train = pd.concat([neg_train, neg_train[:int(scale * len(neg_train)) ]])
 print(len(pos_train)/(len(pos_train)+ len(neg_train)))
 x_train = pd.concat([pos_train, neg_train])
 y_train =(np.zeros(len(pos_train)) + 1 ).tolist() + np.zeros(len(neg_train)).tolist()
del pos_train, neg_train<split>
test = pd.merge(test, sub1, how='left', on='ID', )
x_train, x_valid, y_train, y_valid = train_test_split(x_train, y_train, test_size=0.2, random_state=4242 )<train_model>
train = train.replace(0, np.nan)
 test = test.replace(0, np.nan)
 train = pd.concat(( train, test), axis=0, ignore_index=True )
params = {}
params['objective'] = 'binary:logistic'
params['eval_metric'] = 'logloss'
params['eta'] = 0.02
params['max_depth'] = 4
d_train = xgb.DMatrix(x_train, label=y_train)
 d_valid = xgb.DMatrix(x_valid, label=y_valid)
 watchlist = [(d_train, 'train'),(d_valid, 'valid')]
bst = xgb.train(params, d_train, 400, watchlist, early_stopping_rounds=50, verbose_eval=10 )<save_to_csv>
test['target'] = 0.0
folds = 5
for fold in range(folds):
x1, x2, y1, y2 = model_selection.train_test_split(train[col], np.log1p(train.target.values), test_size=0.20, random_state=fold)
 params = {'learning_rate': 0.02, 'max_depth': 7, 'boosting': 'gbdt', 'objective': 'regression', 'metric': 'rmse', 'is_training_metric': True, 'feature_fraction': 0.9, 'bagging_fraction': 0.8, 'bagging_freq': 5, 'seed':fold}
model = lgb.train(params, lgb.Dataset(x1, label=y1), 3000, lgb.Dataset(x2, label=y2), verbose_eval=200, early_stopping_rounds=100)
 test['target'] += np.expm1(model.predict(test[col], num_iteration=model.best_iteration))
test['target'] /= folds
test[['ID', 'target']].to_csv('submission.csv', index=False )
d_test = xgb.DMatrix(x_test)
 p_test = bst.predict(d_test)
 sub = pd.DataFrame()
sub['test_id'] = df_test['test_id']
sub['is_duplicate'] = p_test
sub.to_csv('simple_xgb.csv', index=False )<load_from_csv>
b1 = sub1.rename(columns={'target':'dp1'})
 b2 = pd.read_csv('submission.csv' ).rename(columns={'target':'dp2'})
 b1 = pd.merge(b1, b2, how='left', on='ID')
 b1['target'] =(b1['dp1'] * 0.8)+(b1['dp2'] * 0.2)
 b1[['ID','target']].to_csv('blend01.csv', index=False )
df_train = pd.read_csv('.. /input/train.csv')
 df_train.head()<save_to_csv>
b1 = sub2.rename(columns={'target':'dp1'})
 b2 = pd.read_csv('blend01.csv' ).rename(columns={'target':'dp2'})
 b1 = pd.merge(b1, b2, how='left', on='ID')
 b1['target'] =(b1['dp1'] * 0.8)+(b1['dp2'] * 0.2)
 b1[['ID','target']].to_csv('blend02.csv', index=False )
p = df_train['is_duplicate'].mean()
print('Predicted score:', log_loss(df_train['is_duplicate'], np.zeros_like(df_train['is_duplicate'])+ p))
df_test = pd.read_csv('.. /input/test.csv')
 sub = pd.DataFrame({'test_id': df_test['test_id'], 'is_duplicate': p})
 sub.to_csv('naive_submission.csv', index=False)
 sub.head()<load_from_csv>
b1 = sub2.rename(columns={'target':'dp1'})
 b2 = pd.read_csv('blend02.csv' ).rename(columns={'target':'dp2'})
 b1 = pd.merge(b1, b2, how='left', on='ID')
 b1['target'] =(b1['dp1'] * 0.5)+(b1['dp2'] * 0.5)
 b1[['ID','target']].to_csv('blend03.csv', index=False )
df_test = pd.read_csv('.. /input/test.csv')
 df_test.head()<define_variables>
b1 = sub3.rename(columns={'target':'dp1'})
 b2 = pd.read_csv('blend03.csv' ).rename(columns={'target':'dp2'})
 b1 = pd.merge(b1, b2, how='left', on='ID')
 b1['target'] =(b1['dp1'] * 0.6)+(b1['dp2'] * 0.4)
 b1[['ID','target']].to_csv('blend04.csv', index=False )