Kaggle competition: Jigsaw Unintended Bias in Toxicity Classification
gbr_model = GradientBoostingRegressor(n_estimators=4780, learning_rate=0.01,
max_depth=10, max_features='sqrt',
min_samples_leaf=1, min_samples_split=250,
loss='huber', random_state =6 ).fit(X_train,y_train)
 gbr_preds = gbr_model.predict(X_test)
 print('The accuracy of the Gradient boost is',r2_score(y_test,gbr_preds))
print('RMSE is:
', mean_squared_error(y_test,gbr_preds))<choose_model_class>
import numpy as np
import pandas as pd
import os
import time
import gc
import random
from tqdm._tqdm_notebook import tqdm_notebook as tqdm
from keras.preprocessing import text, sequence
import torch
from torch import nn
from torch.utils import data
from torch.nn import functional as F
from fastai.train import Learner
from fastai.train import DataBunch
from fastai.callbacks import *
from fastai.basic_data import DatasetType
lgbm_model = LGBMRegressor(objective='regression',
num_leaves=4,
learning_rate=0.05,
n_estimators=1250,
max_bin=75,
bagging_fraction=0.8,
bagging_freq=9,
feature_fraction=0.45,
feature_fraction_seed=9,
bagging_seed=12,
min_data_in_leaf=3,
min_sum_hessian_in_leaf=2 ).fit(X_train, y_train)
 lgbm_preds = lgbm_model.predict(X_test)
 print('The accuracy of the lgbm Regressor is',r2_score(y_test,lgbm_preds))
print('RMSE is:
', mean_squared_error(y_test,lgbm_preds))<find_best_params>
def seed_everything(seed=123):
random.seed(seed)
 os.environ['PYTHONHASHSEED'] = str(seed)
 np.random.seed(seed)
 torch.manual_seed(seed)
 torch.cuda.manual_seed(seed)
 torch.backends.cudnn.deterministic = True
seed_everything()
r_alphas = [0.05, 0.1, 0.3, 1, 3, 5, 10, 15, 30]
ridge_model = make_pipeline(RobustScaler() , RidgeCV(alphas = r_alphas, cv =3)).fit(X_train, y_train)
 ridge_preds = ridge_model.predict(X_test)
 print('The accuracy of the ridge Regressor is',r2_score(y_test,ridge_preds))
print('RMSE is:
', mean_squared_error(y_test,ridge_preds)) 
<train_model>
CRAWL_EMBEDDING_PATH = '.. /input/fasttext-crawl-300d-2m/crawl-300d-2M.vec'
GLOVE_EMBEDDING_PATH = '.. /input/glove840b300dtxt/glove.840B.300d.txt'
NUM_MODELS = 2
LSTM_UNITS = 128
DENSE_HIDDEN_UNITS = 4 * LSTM_UNITS
MAX_LEN = 220
alpha_lasso = np.logspace(-3, -1, 30)
 lasso_model = make_pipeline(RobustScaler() ,
LassoCV(max_iter=1e6,
alphas = alpha_lasso,
random_state = 1)).fit(X_train, y_train)
 lasso_preds = lasso_model.predict(X_test)
 print('The accuracy of the lasso Regressor is',r2_score(y_test,lasso_preds))
print('RMSE is:
', mean_squared_error(y_test,lasso_preds)) 
<train_on_grid>
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 tqdm(f))
e_alphas = np.logspace(-3 -2, 30)
 e_l1ratio = [0.8, 0.85, 0.9, 0.95, 0.99, 1]
elastic_model= make_pipeline(RobustScaler() ,
ElasticNetCV(max_iter=1e6, alphas=e_alphas,
l1_ratio=e_l1ratio)).fit(X_train, y_train)
 elastic_preds = elastic_model.predict(X_test)
 print('The accuracy of the Elastic Net CV is',r2_score(y_test,elastic_preds))
print('RMSE is:
', mean_squared_error(y_test,elastic_preds)) 
<train_model>
def build_matrix(word_index, path):
embedding_index = load_embeddings(path)
 embedding_matrix = np.zeros(( len(word_index)+ 1, 300))
unknown_words = []
for word, i in word_index.items() :
try:
embedding_matrix[i] = embedding_index[word]
except KeyError:
unknown_words.append(word)
 return embedding_matrix, unknown_words
ridge = make_pipeline(RobustScaler() ,
RidgeCV(alphas = r_alphas))
lasso = make_pipeline(RobustScaler() ,
LassoCV(max_iter=1e6,
alphas = alpha_lasso,
random_state = 1)).fit(X_train,y_train)
 elasticnet = make_pipeline(RobustScaler() ,
ElasticNetCV(max_iter=1e6, alphas=e_alphas,
l1_ratio=e_l1ratio)).fit(X_train,y_train)
 lgbm_model = LGBMRegressor(objective='regression',
num_leaves=4,
learning_rate=0.05,
n_estimators=1250,
max_bin=75,
bagging_fraction=0.8,
bagging_freq=9,
feature_fraction=0.45,
feature_fraction_seed=9,
bagging_seed=12,
min_data_in_leaf=3,
min_sum_hessian_in_leaf=2 ).fit(X_train,y_train)
 gbr_model = GradientBoostingRegressor(n_estimators=4780, learning_rate=0.01,
max_depth=10, max_features='sqrt',
min_samples_leaf=1, min_samples_split=250,
loss='huber', random_state =6 ).fit(X_train,y_train)
 stack_gen = StackingCVRegressor(regressors=(ridge,
lasso, elasticnet, gbr_model,
lgbm_model),
meta_regressor=gbr_model,
use_features_in_secondary=True)
 stackX = np.array(X_train)
 stacky = np.array(y_train)
 stack_gen_model = stack_gen.fit(stackX, stacky )<predict_on_test>
def sigmoid(x):
return 1/(1 + np.exp(-x))
em_preds = elastic_model.predict(X_test)
 lasso_preds = lasso_model.predict(X_test)
 ridge_preds = ridge_model.predict(X_test)
 stack_gen_preds = stack_gen_model.predict(X_test)
 lgbm_preds = lgbm_model.predict(X_test)
 gbr_preds = gbr_model.predict(X_test )<compute_test_metric>
def train_model(learn,test,output_dim,lr=0.0003,
batch_size=512, n_epochs=8,
enable_checkpoint_ensemble=True):
all_test_preds = []
checkpoint_weights = [2 ** epoch for epoch in range(n_epochs)]
test_loader = torch.utils.data.DataLoader(test, batch_size=batch_size, shuffle=False)
 n = len(learn.data.train_dl)
 phases = [(TrainingPhase(n ).schedule_hp('lr', lr *(0.6**(i)))) for i in range(n_epochs)]
sched = GeneralScheduler(learn, phases)
 learn.callbacks.append(sched)
 for epoch in range(n_epochs):
learn.fit(1)
 test_preds = np.zeros(( len(test), output_dim))
for i, x_batch in enumerate(test_loader):
X = x_batch[0].cuda()
y_pred = sigmoid(learn.model(X ).detach().cpu().numpy())
 test_preds[i * batch_size:(i+1)* batch_size, :] = y_pred
all_test_preds.append(test_preds)
 if enable_checkpoint_ensemble:
test_preds = np.average(all_test_preds, weights=checkpoint_weights, axis=0)
 else:
test_preds = all_test_preds[-1]
return test_preds
print('RMSE is:
', mean_squared_error(y_test,stack_gen_preds))
print('The accuracy of the stack is',r2_score(y_test,stack_gen_preds)) 
<compute_test_metric>
class SpatialDropout(nn.Dropout2d):
def forward(self, x):
x = x.unsqueeze(2)
 x = x.permute(0, 3, 2, 1)
 x = super(SpatialDropout, self ).forward(x)
 x = x.permute(0, 3, 2, 1)
 x = x.squeeze(2)
 return x
stack_preds_1 =(( 0.1*em_preds)+(0.1*lasso_preds)+(0.1*ridge_preds)+(0.1 * gbr_preds)
 +(0.1*lgbm_preds)+(0.5*stack_gen_preds))
print('The accuracy of the stack Regressor is',r2_score(y_test,stack_preds_1))
print('RMSE is:
', mean_squared_error(y_test,stack_preds_1)) 
<drop_column>
class NeuralNet(nn.Module):
def __init__(self, embedding_matrix, num_aux_targets):
super(NeuralNet, self ).__init__()
embed_size = embedding_matrix.shape[1]
self.embedding = nn.Embedding(max_features, embed_size)
 self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32))
self.embedding.weight.requires_grad = False
self.embedding_dropout = SpatialDropout(0.3)
 self.lstm1 = nn.LSTM(embed_size, LSTM_UNITS, bidirectional=True, batch_first=True)
 self.lstm2 = nn.LSTM(LSTM_UNITS * 2, LSTM_UNITS, bidirectional=True, batch_first=True)
 self.linear1 = nn.Linear(DENSE_HIDDEN_UNITS, DENSE_HIDDEN_UNITS)
 self.linear2 = nn.Linear(DENSE_HIDDEN_UNITS, DENSE_HIDDEN_UNITS)
 self.linear_out = nn.Linear(DENSE_HIDDEN_UNITS, 1)
 self.linear_aux_out = nn.Linear(DENSE_HIDDEN_UNITS, num_aux_targets)
 def forward(self, x):
h_embedding = self.embedding(x)
 h_embedding = self.embedding_dropout(h_embedding)
 h_lstm1, _ = self.lstm1(h_embedding)
 h_lstm2, _ = self.lstm2(h_lstm1)
 avg_pool = torch.mean(h_lstm2, 1)
 max_pool, _ = torch.max(h_lstm2, 1)
 h_conc = torch.cat(( max_pool, avg_pool), 1)
 h_conc_linear1 = F.relu(self.linear1(h_conc))
h_conc_linear2 = F.relu(self.linear2(h_conc))
hidden = h_conc + h_conc_linear1 + h_conc_linear2
result = self.linear_out(hidden)
 aux_result = self.linear_aux_out(hidden)
 out = torch.cat([result, aux_result], 1)
 return out
def preprocess(data):

 punct = "/-'?!.,
def clean_special_chars(text, punct):
for p in punct:
text = text.replace(p, ' ')
 return text
data = data.astype(str ).apply(lambda x: clean_special_chars(x, punct))
return data
feats = test.drop(['Id'], axis=1)
 feats = feats[X_train.columns]<predict_on_test>
train = pd.read_csv('.. /input/jigsaw-unintended-bias-in-toxicity-classification/train.csv')
 test = pd.read_csv('.. /input/jigsaw-unintended-bias-in-toxicity-classification/test.csv')
 x_train = preprocess(train['comment_text'])
 y_aux_train = train[['target', 'severe_toxicity', 'obscene', 'identity_attack', 'insult', 'threat']]
x_test = preprocess(test['comment_text'] )
lasso_preds = lasso_model.predict(feats)
 em_preds = elastic_model.predict(feats)
 ridge_preds = ridge_model.predict(feats)
 stack_gen_preds = stack_gen_model.predict(feats)
 lgbm_preds = lgbm_model.predict(feats)
 gbr_preds = gbr_model.predict(feats )<define_variables>
identity_columns = [
'male', 'female', 'homosexual_gay_or_lesbian', 'christian', 'jewish',
'muslim', 'black', 'white', 'psychiatric_or_mental_illness']
stack_preds =(( 0.1*em_preds)+(0.1*lasso_preds)+(0.1*ridge_preds)+(0.1 * gbr_preds)
 +(0.1*lgbm_preds)+(0.5*stack_gen_preds))<predict_on_test>
weights = np.ones(( len(x_train),)) / 4
weights +=(train[identity_columns].fillna(0 ).values>=0.5 ).sum(axis=1 ).astype(bool ).astype(np.int)/ 4
weights +=(((train['target'].values>=0.5 ).astype(bool ).astype(np.int)+ 
(train[identity_columns].fillna(0 ).values<0.5 ).sum(axis=1 ).astype(bool ).astype(np.int)) > 1 ).astype(bool ).astype(np.int)/ 4
weights +=(((train['target'].values<0.5 ).astype(bool ).astype(np.int)+ 
(train[identity_columns].fillna(0 ).values>=0.5 ).sum(axis=1 ).astype(bool ).astype(np.int)) > 1 ).astype(bool ).astype(np.int)/ 4
loss_weight = 1.0 / weights.mean()
y_train = np.vstack([(train['target'].values>=0.5 ).astype(np.int),weights] ).T
max_features = None
tokenizer = text.Tokenizer()
tokenizer.fit_on_texts(list(x_train)+ list(x_test))
final_predictions = np.exp(stack_preds)
 print("Original predictions are:
", stack_preds[:5], "
")
 print("Final predictions are:
", final_predictions[:5] )<save_to_csv>
x_train = tokenizer.texts_to_sequences(x_train)
 x_test = tokenizer.texts_to_sequences(x_test)
 x_train = sequence.pad_sequences(x_train, maxlen=MAX_LEN)
 x_test = sequence.pad_sequences(x_test, maxlen=MAX_LEN )
submission = pd.DataFrame()
submission['Id'] = test.Id
submission['SalePrice'] = final_predictions
submission.to_csv('submission1.csv', index=False )<import_modules>
embedding_matrix = np.concatenate([crawl_matrix, glove_matrix], axis=-1)
 embedding_matrix.shape
del crawl_matrix
del glove_matrix
gc.collect()
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import random
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier
from sklearn.model_selection import GridSearchCV
from mlxtend.classifier import StackingCVClassifier<load_from_csv>
x_train_torch = torch.tensor(x_train, dtype=torch.long)
 y_train_torch = torch.tensor(np.hstack([y_train, y_aux_train]), dtype=torch.float32)
 x_test_torch = torch.tensor(x_test, dtype=torch.long)
 batch_size = 512
train_dataset = data.TensorDataset(x_train_torch, y_train_torch)
 valid_dataset = data.TensorDataset(x_train_torch[:batch_size], y_train_torch[:batch_size])
 test_dataset = data.TensorDataset(x_test_torch)
 train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
 valid_loader = torch.utils.data.DataLoader(valid_dataset, batch_size=batch_size, shuffle=False)
 databunch = DataBunch(train_dl=train_loader,valid_dl=valid_loader )
train_data = pd.read_csv('/kaggle/input/titanic/train.csv')
 train_data.head()<load_from_csv>
def custom_loss(data, targets):

 bce_loss_1 = nn.BCEWithLogitsLoss(weight=targets[:,1:2] )(data[:,:1],targets[:,:1])
 bce_loss_2 = nn.BCEWithLogitsLoss()(data[:,1:],targets[:,2:])
 return(bce_loss_1 * loss_weight)+ bce_loss_2
all_test_preds = []
for model_idx in range(NUM_MODELS):
print('Model ', model_idx)
 seed_everything(1 + model_idx)
 model = NeuralNet(embedding_matrix, y_aux_train.shape[-1])
 learn = Learner(databunch,model,loss_func=custom_loss)
 test_preds = train_model(learn,test_dataset,output_dim=7)
 all_test_preds.append(test_preds )
test_data = pd.read_csv('/kaggle/input/titanic/test.csv')
 test_data.head()<filter>
submission = pd.DataFrame.from_dict({
'id': test['id'],
'prediction': np.mean(all_test_preds, axis=0)[:, 0]})
 submission.to_csv('submission.csv', index=False )