Kaggle competition: Santander Value Prediction Challenge
<SOS> metric: RMSLE Kaggle data source: santander-value-prediction-challenge<train_on_grid>
tqdm.pandas()
sns.set(style="white", color_codes=True)
 %matplotlib inline
oof_preds = np.zeros(( X_train.shape[0]))
test_preds = np.zeros(( X_test.shape[0]))
for fold in [0,1,2,3,4]:
K.clear_session()
tr_ind, val_ind = splits[fold]
es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=3)
 model = model_gru_atten_3()
model.fit(X_train[tr_ind],
y_train[tr_ind]>0.5,
batch_size=BATCH_SIZE,
epochs=NUM_EPOCHS,
validation_data=(X_train[val_ind], y_train[val_ind]>0.5),
callbacks = [es])
 oof_preds[val_ind] += model.predict(X_train[val_ind])[:,0]
test_preds += model.predict(X_test)[:,0]
test_preds /= 5
outputs.append([test_preds, '3 GRU w/ atten'])
 roc_auc_score(y_train>0.5,oof_preds )<define_variables>
train = pd.read_csv('.. /input/train.csv')
 test = pd.read_csv('.. /input/test.csv')
 train.head()
pred_test= np.mean([outputs[i][0] for i in range(len(outputs)) ], axis = 0 )<load_from_csv>
def aggregate_row(row):
non_zero_values = row.iloc[row.nonzero() ].astype(float)
 if non_zero_values.empty:
aggs = {
'non_zero_mean': np.nan,
'non_zero_std': np.nan,
'non_zero_max': np.nan,
'non_zero_min': np.nan,
'non_zero_sum': np.nan,
'non_zero_skewness': np.nan,
'non_zero_kurtosis': np.nan,
'non_zero_median': np.nan,
'non_zero_q1': np.nan,
'non_zero_q3': np.nan,
'non_zero_gmean': np.nan,
'non_zero_log_mean': np.nan,
'non_zero_log_std': np.nan,
'non_zero_log_max': np.nan,
'non_zero_log_min': np.nan,
'non_zero_log_sum': np.nan,
'non_zero_log_skewness': np.nan,
'non_zero_log_kurtosis': np.nan,
'non_zero_log_median': np.nan,
'non_zero_log_q1': np.nan,
'non_zero_log_q3': np.nan,
'non_zero_log_gmean': np.nan,
'non_zero_count': np.nan,
'non_zero_fraction': np.nan
}
else:
aggs = {
'non_zero_mean': non_zero_values.mean() ,
'non_zero_std': non_zero_values.std() ,
'non_zero_max': non_zero_values.max() ,
'non_zero_min': non_zero_values.min() ,
'non_zero_sum': non_zero_values.sum() ,
'non_zero_skewness': skew(non_zero_values),
'non_zero_kurtosis': kurtosis(non_zero_values),
'non_zero_median': non_zero_values.median() ,
'non_zero_q1': np.percentile(non_zero_values, q=25),
'non_zero_q3': np.percentile(non_zero_values, q=75),
'non_zero_gmean': gmean(non_zero_values),
'non_zero_log_mean': np.log1p(non_zero_values ).mean() ,
'non_zero_log_std': np.log1p(non_zero_values ).std() ,
'non_zero_log_max': np.log1p(non_zero_values ).max() ,
'non_zero_log_min': np.log1p(non_zero_values ).min() ,
'non_zero_log_sum': np.log1p(non_zero_values ).sum() ,
'non_zero_log_skewness': skew(np.log1p(non_zero_values)) ,
'non_zero_log_kurtosis': kurtosis(np.log1p(non_zero_values)) ,
'non_zero_log_median': np.log1p(non_zero_values ).median() ,
'non_zero_log_q1': np.percentile(np.log1p(non_zero_values), q=25),
'non_zero_log_q3': np.percentile(np.log1p(non_zero_values), q=75),
'non_zero_log_gmean': gmean(np.log1p(non_zero_values)) ,
'non_zero_count': non_zero_values.count() ,
'non_zero_fraction': non_zero_values.count() / row.count()
}
return pd.Series(aggs, index=list(aggs.keys()))
submission = pd.read_csv('.. /input/jigsaw-unintended-bias-in-toxicity-classification/sample_submission.csv', index_col='id')
 submission['prediction'] = pred_test
submission.reset_index(drop=False, inplace=True)
 submission.head() 
<save_to_csv>
eng_features = train.iloc[:, 2:].progress_apply(aggregate_row, axis=1)
 eng_features_test = test.iloc[:, 1:].progress_apply(aggregate_row, axis=1 )
submission.to_csv('submission.csv', index=False )<save_to_csv>
train_matrix = np.hstack([
eng_features.values
])
 test_matrix = np.hstack([
eng_features_test.values
] )
submission.to_csv('submission.csv', index=False )<import_modules>
lgb_params = {
'objective': 'binary',
'metric': 'auc',
'learning_rate': 0.1,
'num_leaves': 16,
'max_depth': -1,
'min_child_samples': 1,
'max_bin': 300,
'subsample': 1.0,
'subsample_freq': 1,
'colsample_bytree': 0.5,
'min_child_weight': 10,
'reg_lambda': 0.1,
'reg_alpha': 0.0,
'scale_pos_weight': 1,
'zero_as_missing': False,
'num_threads': -1,
}
adversarial_x = np.vstack([
train_matrix,
test_matrix
])
 adversarial_y = np.ones(len(adversarial_x))
adversarial_y[:len(train_matrix)] = 0
cv = KFold(n_splits=5, random_state=100, shuffle=True)
 train_preds = np.zeros(( len(adversarial_x)))
 for i,(train_index, valid_index)in enumerate(cv.split(adversarial_y)) :
print(f'Fold {i}')
 dtrain = lgb.Dataset(adversarial_x[train_index],
label=adversarial_y[train_index])
 dvalid = lgb.Dataset(adversarial_x[valid_index],
label=adversarial_y[valid_index])
 evals_result = {}
model = lgb.train(lgb_params, dtrain,
num_boost_round=10000,
valid_sets=[dtrain, dvalid],
valid_names=['train', 'valid'],
early_stopping_rounds=100,
verbose_eval=2000,
evals_result=evals_result)
 valid_preds = model.predict(adversarial_x[valid_index])
 train_preds[valid_index] = valid_preds
print('Overall ROC AUC', roc_auc_score(adversarial_y, train_preds))
import numpy as np
import pandas as pd
from keras.models import Model
from keras.layers import Input, Dense, Embedding, SpatialDropout1D, add, concatenate
from keras.layers import CuDNNLSTM, Bidirectional, GlobalMaxPooling1D, GlobalAveragePooling1D
from keras.preprocessing import text, sequence
from keras.callbacks import LearningRateScheduler<define_variables>
np.save('weights.npy', predictions.values )
NUM_MODELS = 2
BATCH_SIZE = 512
LSTM_UNITS = 128
DENSE_HIDDEN_UNITS = 4 * LSTM_UNITS
EPOCHS = 4
MAX_LEN = 220
IDENTITY_COLUMNS = [
'male', 'female', 'homosexual_gay_or_lesbian', 'christian', 'jewish',
'muslim', 'black', 'white', 'psychiatric_or_mental_illness'
]
AUX_COLUMNS = ['target', 'severe_toxicity', 'obscene', 'identity_attack', 'insult', 'threat']
TEXT_COLUMN = 'comment_text'
TARGET_COLUMN = 'target'
CHARS_TO_REMOVE = '!"
“”’'∞θ÷α•à−β∅³π‘₹´°£€\×™√²—'<categorify>
weights = predictions + 0.1
weights = weights / weights.mean()
def weighted_rmsle(y_true, y_pred, index):
errors =(np.log1p(y_true)- np.log1p(y_pred)) ** 2
errors = errors * weights[index]
return np.sqrt(np.mean(errors))
def rmsle(y_true, y_pred):
errors =(np.log1p(y_true)- np.log1p(y_pred)) ** 2
return np.sqrt(np.mean(errors))
def get_coefs(word, *arr):
return word, np.asarray(arr, dtype='float32')
 def load_embeddings(path):
with open(path)as f:
return dict(get_coefs(*line.strip().split(' ')) for line in f)
 def build_matrix(word_index, path):
embedding_index = load_embeddings(path)
 embedding_matrix = np.zeros(( len(word_index)+ 1, 300))
for word, i in word_index.items() :
try:
embedding_matrix[i] = embedding_index[word]
except KeyError:
pass
return embedding_matrix
def build_model(embedding_matrix, num_aux_targets):
words = Input(shape=(None,))
x = Embedding(*embedding_matrix.shape, weights=[embedding_matrix], trainable=False )(words)
 x = SpatialDropout1D(0.2 )(x)
 x = Bidirectional(CuDNNLSTM(LSTM_UNITS, return_sequences=True))(x)
 x = Bidirectional(CuDNNLSTM(LSTM_UNITS, return_sequences=True))(x)
 hidden = concatenate([
GlobalMaxPooling1D()(x),
GlobalAveragePooling1D()(x),
])
 hidden = add([hidden, Dense(DENSE_HIDDEN_UNITS, activation='relu' )(hidden)])
 hidden = add([hidden, Dense(DENSE_HIDDEN_UNITS, activation='relu' )(hidden)])
 result = Dense(1, activation='sigmoid' )(hidden)
 aux_result = Dense(num_aux_targets, activation='sigmoid' )(hidden)
 model = Model(inputs=words, outputs=[result, aux_result])
 model.compile(loss='binary_crossentropy', optimizer='adam')
 return model<load_from_csv>
x_train = train.iloc[:, 2:].values
x_test = test.iloc[:, 1:].values
y_train = np.log(train['target'])
 _, unique_indices = np.unique(x_train, return_index=True, axis=1)
 variance_greater_zero = x_train.var(axis=0)> 0
mask = np.zeros(x_train.shape[1], dtype=bool)
 mask[unique_indices] = True
mask[variance_greater_zero] = True
x_train = x_train[:, mask]
x_test = x_test[:, mask]
x_train.shape, x_test.shape
train_df = pd.read_csv('.. /input/jigsaw-unintended-bias-in-toxicity-classification/train.csv')
 test_df = pd.read_csv('.. /input/jigsaw-unintended-bias-in-toxicity-classification/test.csv' )<define_variables>
decomposer = FeatureUnion([ 
('svd', TruncatedSVD(n_components=50, random_state=100)) , 
('ica', FastICA(n_components=20, random_state=100))
])
 decomposed_train = decomposer.fit_transform(x_train)
 decomposed_test = decomposer.transform(x_test )
contraction_mapping = {"ain't": "is not", "aren't": "are not","can't": "cannot", "'cause": "because",
"could've": "could have", "couldn't": "could not", "didn't": "did not",
"doesn't": "does not", "don't": "do not", "hadn't": "had not",
"hasn't": "has not", "haven't": "have not", "he'd": "he would",
"he'll": "he will", "he's": "he is", "how'd": "how did",
"how'd'y": "how do you", "how'll": "how will", "how's": "how is",
"I'd": "I would", "I'd've": "I would have", "I'll": "I will",
"I'll've": "I will have","I'm": "I am", "I've": "I have",
"i'd": "i would", "i'd've": "i would have", "i'll": "i will",
"i'll've": "i will have","i'm": "i am", "i've": "i have", "isn't": "is not",
"it'd": "it would", "it'd've": "it would have", "it'll": "it will",
"it'll've": "it will have","it's": "it is", "let's": "let us",
"ma'am": "madam", "mayn't": "may not", "might've": "might have",
"mightn't": "might not","mightn't've": "might not have",
"must've": "must have", "mustn't": "must not", "mustn't've": "must not have",
"needn't": "need not", "needn't've": "need not have",
"o'clock": "of the clock", "oughtn't": "ought not",
"oughtn't've": "ought not have", "shan't": "shall not",
"sha'n't": "shall not", "shan't've": "shall not have", "she'd": "she would",
"she'd've": "she would have", "she'll": "she will",
"she'll've": "she will have", "she's": "she is", "should've": "should have",
"shouldn't": "should not", "shouldn't've": "should not have",
"so've": "so have","so's": "so as", "this's": "this is",
"that'd": "that would", "that'd've": "that would have", "that's": "that is",
"there'd": "there would", "there'd've": "there would have",
"there's": "there is", "here's": "here is","they'd": "they would",
"they'd've": "they would have", "they'll": "they will",
"they'll've": "they will have", "they're": "they are",
"they've": "they have", "to've": "to have", "wasn't": "was not",
"we'd": "we would", "we'd've": "we would have", "we'll":
"we will", "we'll've": "we will have", "we're": "we are", "we've": "we have",
"weren't": "were not", "what'll": "what will", "what'll've": "what will have",
"what're": "what are", "what's": "what is", "what've": "what have",
"when's": "when is", "when've": "when have", "where'd": "where did",
"where's": "where is", "where've": "where have", "who'll": "who will",
"who'll've": "who will have", "who's": "who is", "who've": "who have",
"why's": "why is", "why've": "why have", "will've": "will have",
"won't": "will not", "won't've": "will not have", "would've": "would have",
"wouldn't": "would not", "wouldn't've": "would not have", "y'all": "you all",
"y'all'd": "you all would","y'all'd've": "you all would have",
"y'all're": "you all are","y'all've": "you all have","you'd": "you would",
"you'd've": "you would have", "you'll": "you will",
"you'll've": "you will have", "you're": "you are", "you've": "you have" }<string_transform>
train_matrix = np.hstack([
eng_features.values,
decomposed_train
])
 test_matrix = np.hstack([
eng_features_test.values,
decomposed_test
] )
def clean_contractions(text, mapping):
specials = ["’", "‘", "´", "`"]
for s in specials:
text = text.replace(s, "'")
 text = ' '.join([mapping[t] if t in mapping else t for t in text.split(" ")])
 return text<drop_column>
lgb_params = {
'objective': 'regression',
'metric': 'rmse',
'learning_rate': 0.01,
'num_leaves': 16,
'max_depth': -1,
'min_child_samples': 1,
'max_bin': 300,
'subsample': 1.0,
'subsample_freq': 1,
'colsample_bytree': 0.5,
'min_child_weight': 10,
'reg_lambda': 0.1,
'reg_alpha': 0.0,
'scale_pos_weight': 1,
'zero_as_missing': False,
'num_threads': -1,
}
train_df['comment_text'] = train_df['comment_text'].apply(lambda x: clean_contractions(x, contraction_mapping))<feature_engineering>
class KFoldByTargetValue(BaseCrossValidator):
def __init__(self, n_splits=3, shuffle=False, random_state=None):
self.n_splits = n_splits
self.shuffle = shuffle
self.random_state = random_state
def _iter_test_indices(self, X, y=None, groups=None):
n_samples = X.shape[0]
indices = np.arange(n_samples)
 sorted_idx_vals = sorted(zip(indices, X), key=lambda x: x[1])
 indices = [idx for idx, val in sorted_idx_vals]
for split_start in range(self.n_splits):
split_indeces = indices[split_start::self.n_splits]
yield split_indeces
def get_n_splits(self, X=None, y=None, groups=None):
return self.n_split
test_df['comment_text'] = test_df['comment_text'].apply(lambda x: clean_contractions(x, contraction_mapping))<prepare_x_and_y>
cv = KFoldByTargetValue(n_splits=5, shuffle=True, random_state=100)
 train_preds = np.zeros(( len(train)))
 test_preds = np.zeros(( len(test)))
 for i,(train_index, valid_index)in enumerate(cv.split(y_train)) :
print(f'Fold {i}')
 dtrain = lgb.Dataset(train_matrix[train_index],
label=y_train[train_index])
 dvalid = lgb.Dataset(train_matrix[valid_index],
label=y_train[valid_index])
 evals_result = {}
model = lgb.train(lgb_params, dtrain,
num_boost_round=10000,
valid_sets=[dtrain, dvalid],
valid_names=['train', 'valid'],
early_stopping_rounds=100,
verbose_eval=2000,
evals_result=evals_result)
 valid_preds = np.exp(model.predict(train_matrix[valid_index]))
test_preds += np.exp(model.predict(test_matrix)) / cv.n_splits
train_preds[valid_index] = valid_preds
print('RMSLE: ', rmsle(np.exp(y_train[valid_index]), valid_preds))
print('Weighted RMSLE: ', weighted_rmsle(np.exp(y_train[valid_index]), valid_preds, valid_index))
print()
print('Overall RMSLE: ', rmsle(np.exp(y_train), train_preds))
print('Overall Weighted RMSLE: ', weighted_rmsle(np.exp(y_train), train_preds, np.arange(len(train_preds))))
<feature_engineering><EOS> 
submission = pd.DataFrame()
submission['ID'] = test['ID']
submission['target'] = test_preds
submission.to_csv('submission.csv', index=False )