Kaggle competition: Quora Insincere Questions Classification
<SOS> metric: FScore_1 Kaggle data source: quora-insincere-questions-classification<predict_on_test>
tqdm.pandas(desc='Progress')
%%time
cnt = 0
EPOCHS = 800
for tr_idx, val_idx in kf.split(z):
cnt += 1
print(f"FOLD {cnt}")
 net = make_model(nh)
 net.fit(z[tr_idx], y[tr_idx], batch_size=BATCH_SIZE, epochs=EPOCHS,
validation_data=(z[val_idx], y[val_idx]), verbose=0)
 print("train", net.evaluate(z[tr_idx], y[tr_idx], verbose=0, batch_size=BATCH_SIZE))
print("val", net.evaluate(z[val_idx], y[val_idx], verbose=0, batch_size=BATCH_SIZE))
print("predict val...")
 pred[val_idx] = net.predict(z[val_idx], batch_size=BATCH_SIZE, verbose=0)
 print("predict test...")
 pe += net.predict(ze, batch_size=BATCH_SIZE, verbose=0)/ NFOLD<compute_test_metric>
embed_size = 300
max_features = 120000
maxlen = 80
batch_size = 512
n_epochs = 5
n_splits = 5
debug = 0
num_embeddings = 2
sigma_opt = mean_absolute_error(y, pred[:, 1])
 unc = pred[:,2] - pred[:, 0]
sigma_mean = np.mean(unc)
 print(sigma_opt, sigma_mean )<prepare_output>
puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', '
'·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…',
'“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾', '═', '¦', '║', '―', '¥', '▓', '—', '‹', '─',
'▒', '：', '¼', '⊕', '▼', '▪', '†', '■', '’', '▀', '¨', '▄', '♫', '☆', 'é', '¯', '♦', '¤', '▲', 'è', '¸', '¾', 'Ã', '⋅', '‘', '∞',
'∙', '）', '↓', '、', '│', '（', '»', '，', '♪', '╩', '╚', '³', '・', '╦', '╣', '╔', '╗', '▬', '❤', 'ï', 'Ø', '¹', '≤', '‡', '√', ]
sub['FVC1'] = 1.*pe[:, 1]
sub['Confidence1'] = pe[:, 2] - pe[:, 0]
subm = sub[['Patient_Week','FVC','Confidence','FVC1','Confidence1']].copy()
subm.loc[~subm.FVC1.isnull() ].head(10 )<feature_engineering>
mispell_dict = {"aren't" : "are not",
"can't" : "cannot",
"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",
"i'd" : "I would",
"i'd" : "I had",
"i'll" : "I will",
"i'm" : "I am",
"isn't" : "is not",
"it's" : "it is",
"it'll":"it will",
"i've" : "I have",
"let's" : "let us",
"mightn't" : "might not",
"mustn't" : "must not",
"shan't" : "shall not",
"she'd" : "she would",
"she'll" : "she will",
"she's" : "she is",
"shouldn't" : "should not",
"that's" : "that is",
"there's" : "there is",
"they'd" : "they would",
"they'll" : "they will",
"they're" : "they are",
"they've" : "they have",
"we'd" : "we would",
"we're" : "we are",
"weren't" : "were not",
"we've" : "we have",
"what'll" : "what will",
"what're" : "what are",
"what's" : "what is",
"what've" : "what have",
"where's" : "where is",
"who'd" : "who would",
"who'll" : "who will",
"who're" : "who are",
"who's" : "who is",
"who've" : "who have",
"won't" : "will not",
"wouldn't" : "would not",
"you'd" : "you would",
"you'll" : "you will",
"you're" : "you are",
"you've" : "you have",
"'re": " are",
"wasn't": "was not",
"we'll":" will",
"didn't": "did not",
"tryin'":"trying"}
subm.loc[~subm.FVC1.isnull() ,'FVC'] = subm.loc[~subm.FVC1.isnull() ,'FVC1']
if sigma_mean<70:
subm['Confidence'] = sigma_opt
else:
subm.loc[~subm.FVC1.isnull() ,'Confidence'] = subm.loc[~subm.FVC1.isnull() ,'Confidence1']<load_from_csv>
first_word_mispell_dict = {
'whta': 'what', 'howdo': 'how do', 'Whatare': 'what are', 'howcan': 'how can', 'howmuch': 'how much',
'howmany': 'how many', 'whydo': 'why do', 'doi': 'do i', 'howdoes': 'how does', "whst": 'what',
'shoupd': 'should', 'whats': 'what is', "im": "i am", "whatis": "what is", "iam": "i am", "wat": "what",
"wht": "what","whts": "what is", "whtwh": "what", "whtat": "what", "whtlat": "what", "dueto to": "due to",
"dose": "does", "wha": "what", 'hw': "how", "its": "it is", "whay": "what", "ho": "how", "whart": "what",
"woe": "wow", "wt": "what", "ive": "i have","wha": "what", "wich": "which", "whic": "which", "whys": "why",
"doe": "does", "wjy": "why", "wgat": "what", "hiw": "how","howto": "how to", "lets": "let us", "haw": "how",
"witch": "which", "wy": "why", "girlfriend": "girl friend", "hows": "how is","whyis": "why is", "whois": "who is",
"dont": "do not", "hat": "what", "whos": "who is", "whydoes": "why does", "whic": "which","hy": "why", "w? hy": "why",
"ehat": "what", "whate": "what", "whai": "what", "whichis": "which is", "whi": "which", "isit": "is it","ca": "can",
"wwhat": "what", "wil": "will", "wath": "what", "plz": "please", "ww": "how", "hou": "how", "whch": "which",
"ihave": "i have", "cn": "can", "doesnt": "does not", "shoul": "should", "whatdo": "what do", "isnt": "is not",
"whare": "what are","whick": "which", "whatdoes": "what does", "hwo": "how", "howdid": "how did", "why dose": "why does"
}
otest = pd.read_csv('.. /input/osic-pulmonary-fibrosis-progression/test.csv')
 for i in range(len(otest)) :
subm.loc[subm['Patient_Week']==otest.Patient[i]+'_'+str(otest.Weeks[i]), 'FVC'] = otest.FVC[i]
subm.loc[subm['Patient_Week']==otest.Patient[i]+'_'+str(otest.Weeks[i]), 'Confidence'] = 0.1<save_to_csv>
def clean_text(x):
x = str(x)
 for punct in puncts:
if punct in x:
x = x.replace(punct, f' {punct} ')
 return x
def clean_numbers(x):
if bool(re.search(r'\d', x)) :
x = re.sub('[0-9]{5,}', '
x = re.sub('[0-9]{4}', '
x = re.sub('[0-9]{3}', '
x = re.sub('[0-9]{2}', '
return x
subm[["Patient_Week","FVC","Confidence"]].to_csv("submission_regression.csv", index=False )<prepare_output>
def _get_mispell(mispell_dict):
mispell_re = re.compile('(%s)' % '|'.join(mispell_dict.keys()))
return mispell_dict, mispell_re
mispellings, mispellings_re = _get_mispell(mispell_dict)
 def replace_typical_misspell(text):
def replace(match):
return mispellings[match.group(0)]
return mispellings_re.sub(replace, text)
 def correct_first_word(x):
for key in first_word_mispell_dict.keys() :
if x.startswith(key + " "):
x = x.replace(key + " ", first_word_mispell_dict[key] + " ")
 break
return x
reg_sub = subm[["Patient_Week","FVC","Confidence"]].copy()<sort_values>
def add_features(df):
df['question_text'] = df['question_text'].progress_apply(lambda x:str(x))
df["lower_question_text"] = df["question_text"].apply(lambda x: x.lower())
 df['total_length'] = df['question_text'].progress_apply(len)
 df['capitals'] = df['question_text'].progress_apply(lambda comment: sum(1 for c in comment if c.isupper()))
df['caps_vs_length'] = df.progress_apply(lambda row: float(row['capitals'])/float(row['total_length']),
axis=1)
 df['num_words'] = df.question_text.str.count('\S+')
 df['num_unique_words'] = df['question_text'].progress_apply(lambda comment: len(set(w for w in comment.split())))
 df['words_vs_unique'] = df['num_unique_words'] / df['num_words']
return df
df1 = img_sub.sort_values(by=['Patient_Week'], ascending=True ).reset_index(drop=True)
 df2 = reg_sub.sort_values(by=['Patient_Week'], ascending=True ).reset_index(drop=True )<feature_engineering>
def parallelize_apply(df,func,colname,num_process,newcolnames):
pool =Pool(processes=num_process)
 arraydata = pool.map(func,tqdm(df[colname].values))
pool.close()
newdf = pd.DataFrame(arraydata,columns = newcolnames)
 df = pd.concat([df,newdf],axis=1)
 return df
def parallelize_dataframe(df, func):
df_split = np.array_split(df, 4)
 pool = Pool(4)
 df = pd.concat(pool.map(func, df_split))
pool.close()
pool.join()
return df
df = df1[['Patient_Week']].copy()
df['FVC'] = 0.25*df1['FVC'] + 0.75*df2['FVC']
df['Confidence'] = 0.26*df1['Confidence'] + 0.74*df2['Confidence']
df.head()<save_to_csv>
if debug:
train_df = pd.read_csv(".. /input/quora-insincere-questions-classification/train.csv")[:800]
test_df = pd.read_csv(".. /input/quora-insincere-questions-classification/test.csv")[:200]
else:
train_df = pd.read_csv(".. /input/quora-insincere-questions-classification/train.csv")
 test_df = pd.read_csv(".. /input/quora-insincere-questions-classification/test.csv")
 print("Train shape : ",train_df.shape)
 print("Test shape : ",test_df.shape )
df.to_csv('submission.csv', index=False )<define_variables>
train = parallelize_dataframe(train_df, add_features)
 test = parallelize_dataframe(test_df, add_features )
package_dir = ".. /input/ppbert/pytorch-pretrained-bert/pytorch-pretrained-BERT"
sys.path.append(package_dir )<set_options>
train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: x.lower())
 test_df["question_text"] = test_df["question_text"].progress_apply(lambda x: x.lower() )
warnings.filterwarnings(action='once')
 device = torch.device('cuda' )<string_transform>
train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: clean_text(x))
test_df["question_text"] = test_df["question_text"].progress_apply(lambda x: clean_text(x))
def convert_lines(example, max_seq_length,tokenizer):
max_seq_length -=2
all_tokens = []
longer = 0
for text in tqdm(example):
tokens_a = tokenizer.tokenize(text)
 if len(tokens_a)>max_seq_length:
tokens_a = tokens_a[:max_seq_length]
longer += 1
one_token = tokenizer.convert_tokens_to_ids(["[CLS]"]+tokens_a+["[SEP]"])+[0] *(max_seq_length - len(tokens_a))
all_tokens.append(one_token)
 return np.array(all_tokens )<load_pretrained>
train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: clean_numbers(x))
test_df["question_text"] = test_df["question_text"].progress_apply(lambda x: clean_numbers(x))
MAX_SEQUENCE_LENGTH = 220
SEED = 1234
BATCH_SIZE = 32
BERT_MODEL_PATH = '.. /input/bert-pretrained-models/uncased_l-12_h-768_a-12/uncased_L-12_H-768_A-12/'
np.random.seed(SEED)
 torch.manual_seed(SEED)
 torch.cuda.manual_seed(SEED)
 torch.backends.cudnn.deterministic = True
bert_config = BertConfig('.. /input/bert-inference/bert/bert_config.json')
 tokenizer = BertTokenizer.from_pretrained(BERT_MODEL_PATH, cache_dir=None,do_lower_case=True )<load_from_csv>
train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: replace_typical_misspell(x))
test_df["question_text"] = test_df["question_text"].progress_apply(lambda x: replace_typical_misspell(x))
test_df = pd.read_csv(".. /input/jigsaw-unintended-bias-in-toxicity-classification/test.csv")
 test_df['comment_text'] = test_df['comment_text'].astype(str)
 X_test = convert_lines(test_df["comment_text"].fillna("DUMMY_VALUE"), MAX_SEQUENCE_LENGTH, tokenizer )<load_pretrained>
train_X = train_df["question_text"].fillna("_
test_X = test_df["question_text"].fillna("_
model = BertForSequenceClassification(bert_config, num_labels=1)
 model.load_state_dict(torch.load(".. /input/bert-inference/bert/bert_pytorch.bin"))
model.to(device)
 for param in model.parameters() :
param.requires_grad = False
model.eval()<categorify>
def tokenize_and_split(train_X,test_X):
tokenizer = Tokenizer(num_words=max_features,oov_token = 'xxunk',filters='')
 tokenizer.fit_on_texts(list(train_X))
train_X = tokenizer.texts_to_sequences(train_X)
 test_X = tokenizer.texts_to_sequences(test_X)
 train_X = pad_sequences(train_X, maxlen=maxlen)
 test_X = pad_sequences(test_X, maxlen=maxlen)
 train_y = train_df['target'].values
trn_idx = np.random.permutation(len(train_X))
train_X = train_X[trn_idx]
train_y = train_y[trn_idx]
features, test_features = make_stat_features()
train_features = features[trn_idx]
return train_X, test_X, train_y, train_features, test_features ,tokenizer.word_index
test_preds = np.zeros(( len(X_test)))
 test = torch.utils.data.TensorDataset(torch.tensor(X_test, dtype=torch.long))
test_loader = torch.utils.data.DataLoader(test, batch_size=32, shuffle=False)
 tk0 = tqdm(test_loader)
 for i,(x_batch,)in enumerate(tk0):
pred = model(x_batch.to(device), attention_mask=(x_batch > 0 ).to(device), labels=None)
 test_preds[i * 32:(i + 1)* 32] = pred[:, 0].detach().cpu().squeeze().numpy()
test_pred = torch.sigmoid(torch.tensor(test_preds)).numpy().ravel()<save_to_csv>
def make_stat_features() :
train_features = train[['num_unique_words','words_vs_unique','total_length','capitals',
'caps_vs_length','num_words']].fillna(0)
 test_features = test[['num_unique_words','words_vs_unique','total_length','capitals',
'caps_vs_length','num_words']].fillna(0)
 ss = StandardScaler()
ss.fit(np.vstack(( train_features, test_features)))
 train_features = ss.transform(train_features)
 test_features = ss.transform(test_features)
 return train_features, test_features
submission = pd.DataFrame.from_dict({
'id': test_df['id'],
'prediction': test_pred
})
 submission.to_csv('submission.csv', index=False )<import_modules>
x_train, x_test, y_train, train_features, test_features , word_index = tokenize_and_split(train_X,test_X )
import gc
import re
import operator
import numpy as np
import pandas as pd
import seaborn as sns
from gensim.models import KeyedVectors
from sklearn import model_selection
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Embedding, Input, Dense, CuDNNLSTM, CuDNNGRU,concatenate, Bidirectional, SpatialDropout1D, Conv1D, GlobalAveragePooling1D, GlobalMaxPooling1D
from keras.layers import add, Dropout
from keras.optimizers import RMSprop, Adam
from keras.models import Model
from keras.callbacks import EarlyStopping, LearningRateScheduler
from keras.preprocessing import text, sequence
from keras import callbacks
from sklearn.model_selection import train_test_split<load_from_csv>
def load_embedding(path, word_index,emb_mean, emb_std):
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
 embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(path, encoding="utf8", errors='ignore')if len(o)>100)
 all_embs = np.stack(embeddings_index.values())
 embed_size = all_embs.shape[1]
nb_words = min(max_features, len(word_index))
embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size))
for word, i in word_index.items() :
if i >= max_features: continue
embedding_vector = embeddings_index.get(word)
 if embedding_vector is not None: embedding_matrix[i] = embedding_vector
return embedding_matrix
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')
 TEXT_COLUMN = 'comment_text'
TARGET_COLUMN = 'target'
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']
EMBEDDING_FILES = [
'.. /input/fasttext-crawl-300d-2m/crawl-300d-2M.vec',
'.. /input/glove840b300dtxt/glove.840B.300d.txt'
]<correct_missing_values>
if debug:
paragram_embeddings = np.random.randn(120000,300)
 glove_embeddings = np.random.randn(120000,300)
 else:
glove_embeddings = load_embedding('.. /input/quora-insincere-questions-classification/embeddings/glove.840B.300d/glove.840B.300d.txt',word_index,-0.005838499,0.48782197)
 paragram_embeddings = load_embedding('.. /input/quora-insincere-questions-classification/embeddings/paragram_300_sl999/paragram_300_sl999.txt',word_index,-0.0053247833,0.49346462)
 embedding_matrix = np.concatenate(( glove_embeddings, paragram_embeddings), axis=1 )
train_df = train_df.dropna()
len(train_df )<feature_engineering>
class AttentionBlock(nn.Module):
def __init__(self, feature_dim, step_dim, bias=True, **kwargs):
super(AttentionBlock, self ).__init__(**kwargs)
 self.supports_masking = True
self.bias = bias
self.feature_dim = feature_dim
self.step_dim = step_dim
self.features_dim = 0
weight = torch.zeros(feature_dim, 1)
 nn.init.xavier_uniform_(weight)
 self.weight = nn.Parameter(weight)
 if bias:
self.b = nn.Parameter(torch.zeros(step_dim))
def forward(self, x, mask=None):
feature_dim = self.feature_dim
step_dim = self.step_dim
eij = torch.mm(
 x.contiguous().view(-1, feature_dim),
self.weight
).view(-1, step_dim)
 if self.bias:
eij = eij + self.b
eij = torch.tanh(eij)
 a = torch.exp(eij)
 if mask is not None:
a = a * mask
a = a / torch.sum(a, 1, keepdim=True)+ 1e-10
weighted_input = x * torch.unsqueeze(a, -1)
 return torch.sum(weighted_input, 1 )
def build_vocab(texts):
sentences = texts.apply(lambda x: x.split() ).values
vocab = {}
for sentence in sentences:
for word in sentence:
try:
vocab[word] += 1
except KeyError:
vocab[word] = 1
return vocab
def check_coverage(vocab, embeddings_index):
known_words = {}
unknown_words = {}
nb_known_words = 0
nb_unknown_words = 0
for word in vocab.keys() :
try:
known_words[word] = embeddings_index[word]
nb_known_words += vocab[word]
except:
unknown_words[word] = vocab[word]
nb_unknown_words += vocab[word]
pass
print('Found embeddings for {:.3%} of vocab'.format(len(known_words)/ len(vocab)))
 print('Found embeddings for {:.3%} of all text'.format(nb_known_words /(nb_known_words + nb_unknown_words)))
 unknown_words = sorted(unknown_words.items() , key=operator.itemgetter(1)) [::-1]
return unknown_words
ft_common_crawl = '.. /input/fasttext-crawl-300d-2m/crawl-300d-2M.vec'
embeddings_index = KeyedVectors.load_word2vec_format(ft_common_crawl )<compute_train_metric>
class EmbeddingDropout(nn.Module):
def __init__(self, embedding_matrix, max_features = 120000, embedding_size = 300):
super(EmbeddingDropout,self ).__init__()
self.embedding = nn.Embedding(max_features, embedding_size)
 self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32))
self.embedding.weight.requires_grad = False
self.embedding_drop = nn.Dropout2d(0.1)
 def forward(self,x):
h_embeddings = self.embedding(x)
 h_embeddings = h_embeddings.unsqueeze(0)
 h_embeddings = h_embeddings.permute(1,3,0,2)
 h_embeddings = self.embedding_drop(h_embeddings)
 h_embeddings = h_embeddings.permute(2,0,3,1)
 h_embeddings = h_embeddings.squeeze(0)
 return h_embeddings
vocab = build_vocab(train_df['comment_text'])
 oov = check_coverage(vocab, embeddings_index)
 print(oov[:10] )<define_variables>
class Body(nn.Module):
def __init__(self, embedding_size= 300, hidden_size= 128):
super(Body,self ).__init__()
self.lstm = nn.LSTM(embedding_size*num_embeddings, hidden_size, bidirectional=True, batch_first=True)
 self.gru = nn.GRU(hidden_size*2, hidden_size, bidirectional=True, batch_first=True)
 self.hidden= hidden_size
for name, param in self.lstm.named_parameters() :
if 'bias' in name:
nn.init.constant_(param, 0.0)
 elif 'weight_ih' in name:
nn.init.kaiming_normal_(param)
 elif 'weight_hh' in name:
nn.init.orthogonal_(param)
 for name, param in self.gru.named_parameters() :
if 'bias' in name:
nn.init.constant_(param, 0.0)
 elif 'weight_ih' in name:
nn.init.kaiming_normal_(param)
 elif 'weight_hh' in name:
nn.init.orthogonal_(param)
 self.lstm_attention = AttentionBlock(hidden_size*2, maxlen)
 self.gru_attention = AttentionBlock(hidden_size*2, maxlen)
 def forward(self,x):
h_lstm, _ = self.lstm(x)
 h_gru, _ = self.gru(h_lstm)
 h_lstm_att = self.lstm_attention(h_lstm)
 h_gru_att = self.gru_attention(h_gru)
 return h_lstm_att, h_gru_att, h_lstm, h_gru
contraction_mapping1 = {
"Trump's" : 'trump is',"'cause": 'because',',cause': 'because',';cause': 'because',"ain't": 'am not','ain,t': 'am not',
'ain;t': 'am not','ain´t': 'am not','ain’t': 'am not',"aren't": 'are not',
'aren,t': 'are not','aren;t': 'are not','aren´t': 'are not','aren’t': 'are not',"can't": 'cannot',"can't've": 'cannot have','can,t': 'cannot','can,t,ve': 'cannot have',
'can;t': 'cannot','can;t;ve': 'cannot have',
'can´t': 'cannot','can´t´ve': 'cannot have','can’t': 'cannot','can’t’ve': 'cannot have',
"could've": 'could have','could,ve': 'could have','could;ve': 'could have',"couldn't": 'could not',"couldn't've": 'could not have','couldn,t': 'could not','couldn,t,ve': 'could not have','couldn;t': 'could not',
'couldn;t;ve': 'could not have','couldn´t': 'could not',
'couldn´t´ve': 'could not have','couldn’t': 'could not','couldn’t’ve': 'could not have','could´ve': 'could have',
'could’ve': 'could have',"didn't": 'did not','didn,t': 'did not','didn;t': 'did not','didn´t': 'did not',
'didn’t': 'did not',"doesn't": 'does not','doesn,t': 'does not','doesn;t': 'does not','doesn´t': 'does not',
'doesn’t': 'does not',"don't": 'do not','don,t': 'do not','don;t': 'do not','don´t': 'do not','don’t': 'do not',
"hadn't": 'had not',"hadn't've": 'had not have','hadn,t': 'had not','hadn,t,ve': 'had not have','hadn;t': 'had not',
'hadn;t;ve': 'had not have','hadn´t': 'had not','hadn´t´ve': 'had not have','hadn’t': 'had not','hadn’t’ve': 'had not have',"hasn't": 'has not','hasn,t': 'has not','hasn;t': 'has not','hasn´t': 'has not','hasn’t': 'has not',
"haven't": 'have not','haven,t': 'have not','haven;t': 'have not','haven´t': 'have not','haven’t': 'have not',"he'd": 'he would',
"he'd've": 'he would have',"he'll": 'he will',
"he's": 'he is','he,d': 'he would','he,d,ve': 'he would have','he,ll': 'he will','he,s': 'he is','he;d': 'he would',
'he;d;ve': 'he would have','he;ll': 'he will','he;s': 'he is','he´d': 'he would','he´d´ve': 'he would have','he´ll': 'he will',
'he´s': 'he is','he’d': 'he would','he’d’ve': 'he would have','he’ll': 'he will','he’s': 'he is',"how'd": 'how did',"how'll": 'how will',
"how's": 'how is','how,d': 'how did','how,ll': 'how will','how,s': 'how is','how;d': 'how did','how;ll': 'how will',
'how;s': 'how is','how´d': 'how did','how´ll': 'how will','how´s': 'how is','how’d': 'how did','how’ll': 'how will',
'how’s': 'how is',"i'd": 'i would',"i'll": 'i will',"i'm": 'i am',"i've": 'i have','i,d': 'i would','i,ll': 'i will',
'i,m': 'i am','i,ve': 'i have','i;d': 'i would','i;ll': 'i will','i;m': 'i am','i;ve': 'i have',"isn't": 'is not',
'isn,t': 'is not','isn;t': 'is not','isn´t': 'is not','isn’t': 'is not',"it'd": 'it would',"it'll": 'it will',"It's":'it is',
"it's": 'it is','it,d': 'it would','it,ll': 'it will','it,s': 'it is','it;d': 'it would','it;ll': 'it will','it;s': 'it is','it´d': 'it would','it´ll': 'it will','it´s': 'it is',
'it’d': 'it would','it’ll': 'it will','it’s': 'it is',
'i´d': 'i would','i´ll': 'i will','i´m': 'i am','i´ve': 'i have','i’d': 'i would','i’ll': 'i will','i’m': 'i am',
'i’ve': 'i have',"let's": 'let us','let,s': 'let us','let;s': 'let us','let´s': 'let us',
'let’s': 'let us',"ma'am": 'madam','ma,am': 'madam','ma;am': 'madam',"mayn't": 'may not','mayn,t': 'may not','mayn;t': 'may not',
'mayn´t': 'may not','mayn’t': 'may not','ma´am': 'madam','ma’am': 'madam',"might've": 'might have','might,ve': 'might have','might;ve': 'might have',"mightn't": 'might not','mightn,t': 'might not','mightn;t': 'might not','mightn´t': 'might not',
'mightn’t': 'might not','might´ve': 'might have','might’ve': 'might have',"must've": 'must have','must,ve': 'must have','must;ve': 'must have',
"mustn't": 'must not','mustn,t': 'must not','mustn;t': 'must not','mustn´t': 'must not','mustn’t': 'must not','must´ve': 'must have',
'must’ve': 'must have',"needn't": 'need not','needn,t': 'need not','needn;t': 'need not','needn´t': 'need not','needn’t': 'need not',"oughtn't": 'ought not','oughtn,t': 'ought not','oughtn;t': 'ought not',
'oughtn´t': 'ought not','oughtn’t': 'ought not',"sha'n't": 'shall not','sha,n,t': 'shall not','sha;n;t': 'shall not',"shan't": 'shall not',
'shan,t': 'shall not','shan;t': 'shall not','shan´t': 'shall not','shan’t': 'shall not','sha´n´t': 'shall not','sha’n’t': 'shall not',
"she'd": 'she would',"she'll": 'she will',"she's": 'she is','she,d': 'she would','she,ll': 'she will',
'she,s': 'she is','she;d': 'she would','she;ll': 'she will','she;s': 'she is','she´d': 'she would','she´ll': 'she will',
'she´s': 'she is','she’d': 'she would','she’ll': 'she will','she’s': 'she is',"should've": 'should have','should,ve': 'should have','should;ve': 'should have',
"shouldn't": 'should not','shouldn,t': 'should not','shouldn;t': 'should not','shouldn´t': 'should not','shouldn’t': 'should not','should´ve': 'should have',
'should’ve': 'should have',"that'd": 'that would',"that's": 'that is','that,d': 'that would','that,s': 'that is','that;d': 'that would',
'that;s': 'that is','that´d': 'that would','that´s': 'that is','that’d': 'that would','that’s': 'that is',"there'd": 'there had',
"there's": 'there is','there,d': 'there had','there,s': 'there is','there;d': 'there had','there;s': 'there is',
'there´d': 'there had','there´s': 'there is','there’d': 'there had','there’s': 'there is',
"they'd": 'they would',"they'll": 'they will',"they're": 'they are',"they've": 'they have',
'they,d': 'they would','they,ll': 'they will','they,re': 'they are','they,ve': 'they have','they;d': 'they would','they;ll': 'they will','they;re': 'they are',
'they;ve': 'they have','they´d': 'they would','they´ll': 'they will','they´re': 'they are','they´ve': 'they have','they’d': 'they would','they’ll': 'they will',
'they’re': 'they are','they’ve': 'they have',"wasn't": 'was not','wasn,t': 'was not','wasn;t': 'was not','wasn´t': 'was not',
'wasn’t': 'was not',"we'd": 'we would',"we'll": 'we will',"we're": 'we are',"we've": 'we have','we,d': 'we would','we,ll': 'we will',
'we,re': 'we are','we,ve': 'we have','we;d': 'we would','we;ll': 'we will','we;re': 'we are','we;ve': 'we have',
"weren't": 'were not','weren,t': 'were not','weren;t': 'were not','weren´t': 'were not','weren’t': 'were not','we´d': 'we would','we´ll': 'we will',
'we´re': 'we are','we´ve': 'we have','we’d': 'we would','we’ll': 'we will','we’re': 'we are','we’ve': 'we have',"what'll": 'what will',"what're": 'what are',"what's": 'what is',
"what've": 'what have','what,ll': 'what will','what,re': 'what are','what,s': 'what is','what,ve': 'what have','what;ll': 'what will','what;re': 'what are',
'what;s': 'what is','what;ve': 'what have','what´ll': 'what will',
'what´re': 'what are','what´s': 'what is','what´ve': 'what have','what’ll': 'what will','what’re': 'what are','what’s': 'what is',
'what’ve': 'what have',"where'd": 'where did',"where's": 'where is','where,d': 'where did','where,s': 'where is','where;d': 'where did',
'where;s': 'where is','where´d': 'where did','where´s': 'where is','where’d': 'where did','where’s': 'where is',
"who'll": 'who will',"who's": 'who is','who,ll': 'who will','who,s': 'who is','who;ll': 'who will','who;s': 'who is',
'who´ll': 'who will','who´s': 'who is','who’ll': 'who will','who’s': 'who is',"won't": 'will not','won,t': 'will not','won;t': 'will not',
'won´t': 'will not','won’t': 'will not',"wouldn't": 'would not','wouldn,t': 'would not','wouldn;t': 'would not','wouldn´t': 'would not',
'wouldn’t': 'would not',"you'd": 'you would',"you'll": 'you will',"you're": 'you are','you,d': 'you would','you,ll': 'you will',
'you,re': 'you are','you;d': 'you would','you;ll': 'you will',
'you;re': 'you are','you´d': 'you would','you´ll': 'you will','you´re': 'you are','you’d': 'you would','you’ll': 'you will','you’re': 'you are',
'´cause': 'because','’cause': 'because',"you've": "you have","could'nt": 'could not',
"havn't": 'have not',"here’s": "here is",'i""m': 'i am',"i'am": 'i am',"i'l": "i will","i'v": 'i have',"wan't": 'want',"was'nt": "was not","who'd": "who would",
"who're": "who are","who've": "who have","why'd": "why would","would've": "would have","y'all": "you all","y'know": "you know","you.i": "you i",
"your'e": "you are","arn't": "are not","agains't": "against","c'mon": "common","doens't": "does not",'don""t': "do not","dosen't": "does not",
"dosn't": "does not","shoudn't": "should not","that'll": "that will","there'll": "there will","there're": "there are",
"this'll": "this all","u're": "you are", "ya'll": "you all","you'r": "you are","you’ve": "you have","d'int": "did not","did'nt": "did not","din't": "did not","dont't": "do not","gov't": "government",
"i'ma": "i am","is'nt": "is not","‘I":'I',
'ᴀɴᴅ':'and','ᴛʜᴇ':'the','ʜᴏᴍᴇ':'home','ᴜᴘ':'up','ʙʏ':'by','ᴀᴛ':'at','…and':'and','civilbeat':'civil beat',\
'TrumpCare':'Trump care','Trumpcare':'Trump care', 'OBAMAcare':'Obama care','ᴄʜᴇᴄᴋ':'check','ғᴏʀ':'for','ᴛʜɪs':'this','ᴄᴏᴍᴘᴜᴛᴇʀ':'computer',\
'ᴍᴏɴᴛʜ':'month','ᴡᴏʀᴋɪɴɢ':'working','ᴊᴏʙ':'job','ғʀᴏᴍ':'from','Sᴛᴀʀᴛ':'start','gubmit':'submit','CO₂':'carbon dioxide','ғɪʀsᴛ':'first',\
'ᴇɴᴅ':'end','ᴄᴀɴ':'can','ʜᴀᴠᴇ':'have','ᴛᴏ':'to','ʟɪɴᴋ':'link','ᴏғ':'of','ʜᴏᴜʀʟʏ':'hourly','ᴡᴇᴇᴋ':'week','ᴇɴᴅ':'end','ᴇxᴛʀᴀ':'extra',\
'Gʀᴇᴀᴛ':'great','sᴛᴜᴅᴇɴᴛs':'student','sᴛᴀʏ':'stay','ᴍᴏᴍs':'mother','ᴏʀ':'or','ᴀɴʏᴏɴᴇ':'anyone','ɴᴇᴇᴅɪɴɢ':'needing','ᴀɴ':'an','ɪɴᴄᴏᴍᴇ':'income',\
'ʀᴇʟɪᴀʙʟᴇ':'reliable','ғɪʀsᴛ':'first','ʏᴏᴜʀ':'your','sɪɢɴɪɴɢ':'signing','ʙᴏᴛᴛᴏᴍ':'bottom','ғᴏʟʟᴏᴡɪɴɢ':'following','Mᴀᴋᴇ':'make',\
'ᴄᴏɴɴᴇᴄᴛɪᴏɴ':'connection','ɪɴᴛᴇʀɴᴇᴛ':'internet','financialpost':'financial post', 'ʜaᴠᴇ':' have ', 'ᴄaɴ':' can ', 'Maᴋᴇ':' make ', 'ʀᴇʟɪaʙʟᴇ':' reliable ', 'ɴᴇᴇᴅ':' need ',
'ᴏɴʟʏ':' only ', 'ᴇxᴛʀa':' extra ', 'aɴ':' an ', 'aɴʏᴏɴᴇ':' anyone ', 'sᴛaʏ':' stay ', 'Sᴛaʀᴛ':' start', 'SHOPO':'shop',
}<define_variables>
class Extractor(nn.Module):
def __init__(self,maxlen= 70,hidden_size= 128,out= 64,len_feats= 6):
super(Extractor,self ).__init__()
self.conv = nn.Conv1d(maxlen,out,kernel_size= 1,stride= 2)
 self.stat = nn.Linear(len_feats,hidden_size)
 def forward(self,h_lstm,h_gru,stat_features):
conv_out = self.conv(h_lstm)
 l_maxpool, _ = torch.max(conv_out,1)
 g_avgpool = torch.mean(h_gru,1)
 statistical_features = self.stat(stat_features)
 return l_maxpool, g_avgpool, statistical_features
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" }
contraction_mapping.update(contraction_mapping1)
 print("number of contraction",len(contraction_mapping))
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
train_df['comment_text'] = train_df['comment_text'].apply(lambda x: clean_contractions(x, contraction_mapping))
test_df['comment_text'] = test_df['comment_text'].apply(lambda x: clean_contractions(x, contraction_mapping))
vocab = build_vocab(train_df['comment_text'])
 oov = check_coverage(vocab, embeddings_index)
 print(oov[:10] )<feature_engineering>
class Head(nn.Module):
def __init__(self,embedding_size= 300,intermediate_layer=64,maxlen=70,hidden_size=128):
super(Head,self ).__init__()
self.linear = nn.Linear(hidden_size*8,intermediate_layer)
 self.dropout = nn.Dropout(0.15)
 self.bn = nn.BatchNorm1d(intermediate_layer)
 self.output = nn.Linear(intermediate_layer, 1)
 def forward(self,x):
return self.output(self.bn(self.dropout(self.linear(x))))
def clean_special_chars(text, punct, mapping):
for p in mapping:
text = text.replace(p, mapping[p])
 for p in punct:
text = text.replace(p, f' {p} ')
 return text
punct = "/-'?!.,
punct_mapping = {"_":" ", "`":" "}
train_df['comment_text'] = train_df['comment_text'].apply(lambda x: clean_special_chars(x, punct, punct_mapping))
test_df['comment_text'] = test_df['comment_text'].apply(lambda x: clean_special_chars(x, punct, punct_mapping))
vocab = build_vocab(train_df['comment_text'])
 oov = check_coverage(vocab, embeddings_index)
 print(oov[:10] )<define_variables>
class NeuralNet(nn.Module):
def __init__(self, embedding_matrix,max_features=120000,embedding_size=300,
maxlen=70, hidden_size=128, len_feats = 6):
super(NeuralNet,self ).__init__()
self.embedding = EmbeddingDropout(embedding_matrix,max_features= max_features,embedding_size= embedding_size)
 self.stem = Body(embedding_size,hidden_size)
 self.extractor = Extractor(maxlen= maxlen,hidden_size= hidden_size, out= 64, len_feats= len_feats)
 self.head = Head(embedding_size= embedding_size,maxlen= maxlen,hidden_size = hidden_size)
 def forward(self,x,stat_features):
embedding_output = self.embedding(x)
 h_lstm_att, h_gru_att, h_lstm, h_gru = self.stem(embedding_output)
 l_maxpool, g_avgpool, extracted_feats = self.extractor(h_lstm, h_gru, stat_features)
 features = torch.cat(( h_lstm_att, h_gru_att, l_maxpool, g_avgpool, extracted_feats),1)
 out = self.head(features)
 return out
swear_words = [
' 4r5e ',' 5h1t ',' 5hit ',' a55 ',' anal ',' anus ',' ar5e ',' arrse ',' arse ',' ass ',' ass-fucker ',' asses ',' assfucker ',' assfukka ',' asshole ',' assholes ',' asswhole ',' a_s_s ',' b!tch ',' b00bs ',' b17ch ',' b1tch ',' ballbag ',' balls ',' ballsack ',' bastard ',' beastial ',' beastiality ',' bellend ',' bestial ',' bestiality ',' biatch ',' bitch ',' bitcher ',' bitchers ',' bitches ',' bitchin ',' bitching ',' bloody ',' blow job ',' blowjob ',' blowjobs ',' boiolas ',' bollock ',' bollok ',' boner ',' boob ',' boobs ',' booobs ',' boooobs ',' booooobs ',' booooooobs ',' breasts ',' buceta ',' bugger ',' bum ',' bunny fucker ',' butt ',' butthole ',' buttmuch ',' buttplug ',' c0ck ',' c0cksucker ',' carpet muncher ',' cawk ',' chink ',' cipa ',' cl1t ',' clit ',' clitoris ',' clits ',' cnut ',' cock ',' cock-sucker ',' cockface ',' cockhead ',' cockmunch ',' cockmuncher ',' cocks ',' cocksuck ',' cocksucked ',' cocksucker ',' cocksucking ',' cocksucks ',' cocksuka ',' cocksukka ',' cok ',' cokmuncher ',' coksucka ',' coon ',' cox ',' crap ',' cum ',' cummer ',' cumming ',' cums ',' cumshot ',' cunilingus ',' cunillingus ',' cunnilingus ',' cunt ',' cuntlick ',' cuntlicker ',' cuntlicking ',' cunts ',' cyalis ',' cyberfuc ',' cyberfuck ',' cyberfucked ',' cyberfucker ',' cyberfuckers ',' cyberfucking ',' d1ck ',' damn ',' dick ',' dickhead ',' dildo ',' dildos ',' dink ',' dinks ',' dirsa ',' dlck ',' dog-fucker ',' doggin ',' dogging ',' donkeyribber ',' doosh ',' duche ',' dyke ',' ejaculate ',' ejaculated ',' ejaculates ',' ejaculating ',' ejaculatings ',' ejaculation ',' ejakulate ',' f u c k ',' f u c k e r ',' f4nny ',' fag ',' fagging ',' faggitt ',' faggot ',' faggs ',' fagot ',' fagots ',' fags ',' fanny ',' fannyflaps ',' fannyfucker ',' fanyy ',' fatass ',' fcuk ',' fcuker ',' fcuking ',' feck ',' fecker ',' felching ',' fellate ',' fellatio ',' fingerfuck ',' fingerfucked ',' fingerfucker ',' fingerfuckers ',' fingerfucking ',' fingerfucks ',' fistfuck ',' fistfucked ',' fistfucker ',' fistfuckers ',' fistfucking ',' fistfuckings ',' fistfucks ',' flange ',' fook ',' fooker ',' fuck ',' fucka ',' fucked ',' fucker ',' fuckers ',' fuckhead ',' fuckheads ',' fuckin ',' fucking ',' fuckings ',' fuckingshitmotherfucker ',' fuckme ',' fucks ',' fuckwhit ',' fuckwit ',' fudge packer ',' fudgepacker ',' fuk ',' fuker ',' fukker ',' fukkin ',' fuks ',' fukwhit ',' fukwit ',' fux ',' fux0r ',' f_u_c_k ',' gangbang ',' gangbanged ',' gangbangs ',' gaylord ',' gaysex ',' goatse ',' God ',' god-dam ',' god-damned ',' goddamn ',' goddamned ',' hardcoresex ',' hell ',' heshe ',' hoar ',' hoare ',' hoer ',' homo ',' hore ',' horniest ',' horny ',' hotsex ',' jack-off ',' jackoff ',' jap ',' jerk-off ',' jism ',' jiz ',' jizm ',' jizz ',' kawk ',' knob ',' knobead ',' knobed ',' knobend ',' knobhead ',' knobjocky ',' knobjokey ',' kock ',' kondum ',' kondums ',' kum ',' kummer ',' kumming ',' kums ',' kunilingus ',' l3itch ',' labia ',' lmfao ',' lust ',' lusting ',' m0f0 ',' m0fo ',' m45terbate ',' ma5terb8 ',' ma5terbate ',' masochist ',' master-bate ',' masterb8 ',' masterbat3 ',' masterbate ',' masterbation ',' masterbations ',' masturbate ',' mo-fo ',' mof0 ',' mofo ',' mothafuck ',' mothafucka ',' mothafuckas ',' mothafuckaz ',' mothafucked ',' mothafucker ',' mothafuckers ',' mothafuckin ',' mothafucking ',' mothafuckings ',' mothafucks ',' mother fucker ',' motherfuck ',' motherfucked ',' motherfucker ',' motherfuckers ',' motherfuckin ',' motherfucking ',' motherfuckings ',' motherfuckka ',' motherfucks ',' muff ',' mutha ',' muthafecker ',' muthafuckker ',' muther ',' mutherfucker ',' n1gga ',' n1gger ',' nazi ',' nigg3r ',' nigg4h ',' nigga ',' niggah ',' niggas ',' niggaz ',' nigger ',' niggers ',' nob ',' nob jokey ',' nobhead ',' nobjocky ',' nobjokey ',' numbnuts ',' nutsack ',' orgasim ',' orgasims ',' orgasm ',' orgasms ',' p0rn ',' pawn ',' pecker ',' penis ',' penisfucker ',' phonesex ',' phuck ',' phuk ',' phuked ',' phuking ',' phukked ',' phukking ',' phuks ',' phuq ',' pigfucker ',' pimpis ',' piss ',' pissed ',' pisser ',' pissers ',' pisses ',' pissflaps ',' pissin ',' pissing ',' pissoff ',' poop ',' porn ',' porno ',' pornography ',' pornos ',' prick ',' pricks ',' pron ',' pube ',' pusse ',' pussi ',' pussies ',' pussy ',' pussys ',' rectum ',' retard ',' rimjaw ',' rimming ',' s hit ',' s.o.b.',' sadist ',' schlong ',' screwing ',' scroat ',' scrote ',' scrotum ',' semen ',' sex ',' sh!t ',' sh1t ',' shag ',' shagger ',' shaggin ',' shagging ',' shemale ',' shit ',' shitdick ',' shite ',' shited ',' shitey ',' shitfuck ',' shitfull ',' shithead ',' shiting ',' shitings ',' shits ',' shitted ',' shitter ',' shitters ',' shitting ',' shittings ',' shitty ',' skank ',' slut ',' sluts ',' smegma ',' smut ',' snatch ',' son-of-a-bitch ',' spac ',' spunk ',' s_h_i_t ',' t1tt1e5 ',' t1tties ',' teets ',' teez ',' testical ',' testicle ',' tit ',' titfuck ',' tits ',' titt ',' tittie5 ',' tittiefucker ',' titties ',' tittyfuck ',' tittywank ',' titwank ',' tosser ',' turd ',' tw4t ',' twat ',' twathead ',' twatty ',' twunt ',' twunter ',' v14gra ',' v1gra ',' vagina ',' viagra ',' vulva ',' w00se ',' wang ',' wank ',' wanker ',' wanky ',' whoar ',
' whore ',' willies ',' willy ',' xrated ',' xxx '
]
replace_with_fuck = []
for swear in swear_words:
if swear[1:(len(swear)-1)] not in embeddings_index:
replace_with_fuck.append(swear)
 replace_with_fuck = '|'.join(replace_with_fuck)
 def handle_swears(text):
text = re.sub(replace_with_fuck, ' fuck ', text)
 return text
train_df['comment_text'] = train_df['comment_text'].apply(lambda x: handle_swears(x))
test_df['comment_text'] = test_df['comment_text'].apply(lambda x: handle_swears(x))
vocab = build_vocab(train_df['comment_text'])
 oov = check_coverage(vocab, embeddings_index)
 print(oov[:10] )<define_variables>
loss_fn = torch.nn.BCEWithLogitsLoss(reduction='sum')
 step_size = 300
mispell_dict1 = {'SB91':'senate bill','tRump':'trump','utmterm':'utm term','FakeNews':'fake news','Gʀᴇat':'great','ʙᴏᴛtoᴍ':'bottom','washingtontimes':'washington times','garycrum':'gary crum','htmlutmterm':'html utm term','RangerMC':'car','TFWs':'tuition fee waiver','SJWs':'social justice warrior','Koncerned':'concerned','Vinis':'vinys','Yᴏᴜ':'you','Trumpsters':'trump','Trumpian':'trump','bigly':'big league','Trumpism':'trump','Yoyou':'you','Auwe':'wonder','Drumpf':'trump','utmterm':'utm term','Brexit':'british exit','utilitas':'utilities','ᴀ':'a', '😉':'wink','😂':'joy','😀':'stuck out tongue', 'theguardian':'the guardian','deplorables':'deplorable', 'theglobeandmail':'the globe and mail', 'justiciaries': 'justiciary','creditdation': 'Accreditation','doctrne':'doctrine','fentayal': 'fentanyl','designation-': 'designation','CONartist' : 'con-artist','Mutilitated' : 'Mutilated','Obumblers': 'bumblers','negotiatiations': 'negotiations','dood-': 'dood','irakis' : 'iraki','cooerate': 'cooperate','COx':'cox','racistcomments':'racist comments','envirnmetalists': 'environmentalists',}
mispell_dict = {'whattsup': 'WhatsApp', 'whatasapp':'WhatsApp', 'whatsupp':'WhatsApp','whatcus':'what cause', 'arewhatsapp': 'are WhatsApp', 'Hwhat':'what','Whwhat': 'What', 'whatshapp':'WhatsApp', 'howhat':'how that','Whybis':'Why is', 'laowhy86':'Foreigners who do not respect China','Whyco-education':'Why co-education',"Howddo":"How do", 'Howeber':'However', 'Showh':'Show',"Willowmagic":'Willow magic', 'WillsEye':'Will Eye', 'Williby':'will by','pretextt':'pre text','aɴᴅ':'and','amette':'annette','aᴛ':'at','Tridentinus':'mushroom','dailycaller':'daily caller', "™":'trade mark'}
mispell_dict.update(mispell_dict1)
 print("number of mispell",len(mispell_dict))
def correct_spelling(x, dic):
for word in dic.keys() :
if word in x:
x = x.replace(word, dic[word])
 return x
train_df['comment_text'] = train_df['comment_text'].apply(lambda x: correct_spelling(x, mispell_dict))
test_df['comment_text'] = test_df['comment_text'].apply(lambda x: correct_spelling(x, mispell_dict))
vocab = build_vocab(train_df['comment_text'])
 oov = check_coverage(vocab, embeddings_index)
 print(oov[:10] )<feature_engineering>
class MyDataset(Dataset):
def __init__(self,dataset):
self.dataset = dataset
def __getitem__(self,index):
data,target = self.dataset[index]
return data,target,index
def __len__(self):
return len(self.dataset )
def remove_space(text):

 for space in spaces:
text = text.replace(space, ' ')
 text = text.strip()
text = re.sub('\s+', ' ', text)
 return text
spaces = ['\u200b', '\u200e', '\u202a', '\u202c', '\ufeff', '\uf0d8', '\u2061', '\x10', '\x7f', '\x9d', '\xad', '\xa0']
train_df['comment_text'] = train_df['comment_text'].apply(lambda x: remove_space(x))
test_df['comment_text'] = test_df['comment_text'].apply(lambda x: remove_space(x))
vocab = build_vocab(train_df['comment_text'])
 oov = check_coverage(vocab, embeddings_index)
 print(oov[:10] )<prepare_x_and_y>
def sigmoid(x):
return 1 /(1 + np.exp(-x))
if debug :
x_test_cuda = torch.tensor(x_test, dtype=torch.long)
 else :
x_test_cuda = torch.tensor(x_test, dtype=torch.long ).cuda()
test = torch.utils.data.TensorDataset(x_test_cuda)
 test_loader = torch.utils.data.DataLoader(test, batch_size=batch_size, shuffle=False )
x_train = train_df[TEXT_COLUMN].astype(str)
 y_train = train_df[TARGET_COLUMN].values
y_aux_train = train_df[AUX_COLUMNS].values
x_test = test_df[TEXT_COLUMN].astype(str )<string_transform>
def kfold_train(x_train,y_train,x_test, model_obj, train_features, test_features,clip = True):
avg_losses_f = []
avg_val_losses_f = []
train_preds = np.zeros(( len(x_train)))
 test_preds = np.zeros(( len(x_test)))
 splits = list(StratifiedKFold(n_splits=n_splits, shuffle=True ).split(x_train, y_train))
for i,(train_idx, valid_idx)in tqdm(enumerate(splits)) :
x_train = np.array(x_train)
 y_train = np.array(y_train)
 x_train_fold = torch.tensor(x_train[train_idx.astype(int)], dtype=torch.long ).cuda()
y_train_fold = torch.tensor(y_train[train_idx.astype(int), np.newaxis], dtype=torch.float32 ).cuda()
x_val_fold = torch.tensor(x_train[valid_idx.astype(int)], dtype=torch.long ).cuda()
y_val_fold = torch.tensor(y_train[valid_idx.astype(int), np.newaxis], dtype=torch.float32 ).cuda()
feature_train_fold = train_features[train_idx.astype(int)]
feature_valid_fold = train_features[valid_idx.astype(int)]
model = copy.deepcopy(model_obj)
 model.cuda()
train_ds = MyDataset(torch.utils.data.TensorDataset(x_train_fold, y_train_fold))
valid_ds = MyDataset(torch.utils.data.TensorDataset(x_val_fold, y_val_fold))
train_dl = torch.utils.data.DataLoader(train_ds, batch_size=batch_size, shuffle=True)
 valid_dl = torch.utils.data.DataLoader(valid_ds, batch_size=batch_size, shuffle=False)
 optimizer = torch.optim.Adam(model.parameters())
 scheduler = optim.lr_scheduler.ExponentialLR(optimizer,0.01)
 print('Fold %d'%i)
 for epoch in tqdm(range(n_epochs)) :
start_time = time.time()
avg_loss = 0.
 model.train()
for i,(x_batch, y_batch, index)in enumerate(train_dl):
y_pred = model(x_batch,torch.FloatTensor(feature_train_fold[index] ).cuda())
 loss = loss_fn(y_pred, y_batch)
 optimizer.zero_grad()
loss.backward()
if clip:
nn.utils.clip_grad_norm_(model.parameters() ,1)
 optimizer.step()
avg_loss += loss.item() / len(train_dl)
 model.eval()
valid_preds_fold = np.zeros(( x_val_fold.size(0)))
 test_preds_fold = np.zeros(( len(x_test)))
 avg_val_loss = 0.
 for i,(x_batch, y_batch,index)in enumerate(valid_dl):
y_pred = model(x_batch,torch.FloatTensor(feature_valid_fold[index] ).cuda() ).detach()
avg_val_loss += loss_fn(y_pred, y_batch ).item() / len(valid_dl)
 valid_preds_fold[index] = sigmoid(y_pred.cpu().numpy())[:, 0]
elapsed_time = time.time() - start_time
print('Epoch {}/{} \t loss={:.4f} \t val_loss={:.4f} \t time={:.2f}s' 
.format(epoch + 1, n_epochs, avg_loss, avg_val_loss, elapsed_time))
avg_losses_f.append(avg_loss)
 avg_val_losses_f.append(avg_val_loss)
 for i,(x_batch,)in enumerate(test_loader):
y_pred = model(x_batch,torch.FloatTensor(test_features[i * batch_size:(i+1)* batch_size] ).cuda())
 test_preds_fold[i * batch_size:(i+1)* batch_size] = sigmoid(y_pred.detach().cpu().numpy())[:, 0]
train_preds[valid_idx] = valid_preds_fold
test_preds += test_preds_fold / len(splits)
 print('All \t loss={:.4f} \t val_loss={:.4f} \t '.format(np.average(avg_losses_f),np.average(avg_val_losses_f)))
 return train_preds, test_preds
CHARS_TO_REMOVE = '!"
“”’'∞θ÷α•à−β∅³π‘₹´°£€\×™√²—'
tokenizer = Tokenizer(filters=CHARS_TO_REMOVE)
 tokenizer.fit_on_texts(list(x_train)+ list(x_test))
x_train = tokenizer.texts_to_sequences(x_train)
 x_test = tokenizer.texts_to_sequences(x_test)
 MAX_LEN = 220
x_train = pad_sequences(x_train, maxlen=MAX_LEN)
 x_test = pad_sequences(x_test, maxlen=MAX_LEN )<feature_engineering>
def cpu_kfold_train(x_train,y_train,x_test, model_obj, train_features, test_features,clip = True):
avg_losses_f = []
avg_val_losses_f = []
train_preds = np.zeros(( len(x_train)))
 test_preds = np.zeros(( len(x_test)))
 splits = list(StratifiedKFold(n_splits=n_splits, shuffle=True ).split(x_train, y_train))
for i,(train_idx, valid_idx)in tqdm(enumerate(splits)) :
x_train = np.array(x_train)
 y_train = np.array(y_train)
 x_train_fold = torch.tensor(x_train[train_idx.astype(int)], dtype=torch.long)
 y_train_fold = torch.tensor(y_train[train_idx.astype(int), np.newaxis], dtype=torch.float32)
 x_val_fold = torch.tensor(x_train[valid_idx.astype(int)], dtype=torch.long)
 y_val_fold = torch.tensor(y_train[valid_idx.astype(int), np.newaxis], dtype=torch.float32)
 feature_train_fold = train_features[train_idx.astype(int)]
feature_valid_fold = train_features[valid_idx.astype(int)]
model = copy.deepcopy(model_obj)
 train_ds = MyDataset(torch.utils.data.TensorDataset(x_train_fold, y_train_fold))
valid_ds = MyDataset(torch.utils.data.TensorDataset(x_val_fold, y_val_fold))
train_dl = torch.utils.data.DataLoader(train_ds, batch_size=batch_size, shuffle=True)
 valid_dl = torch.utils.data.DataLoader(valid_ds, batch_size=batch_size, shuffle=False)
 optimizer = torch.optim.Adam(model.parameters())
 scheduler = optim.lr_scheduler.ExponentialLR(optimizer,0.01)
 print(f'Fold {i + 1}')
 for epoch in tqdm(range(n_epochs)) :
start_time = time.time()
avg_loss = 0.
 model.train()
for i,(x_batch, y_batch, index)in tqdm(enumerate(train_dl)) :
y_pred = model(x_batch,torch.FloatTensor(feature_train_fold[index]))
loss = loss_fn(y_pred, y_batch)
 optimizer.zero_grad()
loss.backward()
if clip:
nn.utils.clip_grad_norm_(model.parameters() ,1)
 optimizer.step()
avg_loss += loss.item() / len(train_dl)
 model.eval()
valid_preds_fold = np.zeros(( x_val_fold.size(0)))
 test_preds_fold = np.zeros(( len(x_test)))
 avg_val_loss = 0.
 for i,(x_batch, y_batch,index)in tqdm(enumerate(valid_dl)) :
y_pred = model(x_batch,torch.FloatTensor(feature_valid_fold[index])).detach()
avg_val_loss += loss_fn(y_pred, y_batch ).item() / len(valid_dl)
 valid_preds_fold[index] = sigmoid(y_pred.detach().numpy())[:, 0]
elapsed_time = time.time() - start_time
print('Epoch {}/{} \t loss={:.4f} \t val_loss={:.4f} \t time={:.2f}s'.format(epoch + 1, n_epochs, avg_loss, avg_val_loss, elapsed_time))
avg_losses_f.append(avg_loss)
 avg_val_losses_f.append(avg_val_loss)
 for i,(x_batch,)in tqdm(enumerate(test_loader)) :
y_pred = model(x_batch,torch.FloatTensor(test_features[i * batch_size:(i+1)* batch_size]))
test_preds_fold[i * batch_size:(i+1)* batch_size] = sigmoid(y_pred.detach().numpy())[:, 0]
train_preds[valid_idx] = valid_preds_fold
test_preds += test_preds_fold / len(splits)
 print('All \t loss={:.4f} \t val_loss={:.4f} \t '.format(np.average(avg_losses_f),np.average(avg_val_losses_f)))
 return train_preds, test_preds
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
embedding_matrix = np.concatenate([build_matrix(tokenizer.word_index, f)for f in EMBEDDING_FILES], axis=-1 )<choose_model_class>
model = NeuralNet(embedding_matrix,maxlen=maxlen,max_features=len(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
NUM_MODELS = 2
BATCH_SIZE = 512
LSTM_UNITS = 128
DENSE_HIDDEN_UNITS = 4 * LSTM_UNITS
EPOCHS = 4
for column in IDENTITY_COLUMNS + [TARGET_COLUMN]:
train_df[column] = np.where(train_df[column] >= 0.5, True, False)
 sample_weights = np.ones(len(x_train), dtype=np.float32)
 sample_weights += train_df[IDENTITY_COLUMNS].sum(axis=1)
 sample_weights += train_df[TARGET_COLUMN] *(~train_df[IDENTITY_COLUMNS] ).sum(axis=1)
 sample_weights +=(~train_df[TARGET_COLUMN])* train_df[IDENTITY_COLUMNS].sum(axis=1)
 sample_weights /= sample_weights.mean()
checkpoint_predictions = []
weights = []
for model_idx in range(NUM_MODELS):
model = build_model(embedding_matrix, y_aux_train.shape[-1])
 for global_epoch in range(EPOCHS):
model.fit(
 x_train,
[y_train, y_aux_train],
batch_size=BATCH_SIZE,
epochs=1,
verbose=2,
sample_weight=[sample_weights.values, np.ones_like(sample_weights)],
callbacks=[LearningRateScheduler(lambda _: 1e-3 *(0.55 ** global_epoch)) ] 
)
 checkpoint_predictions.append(model.predict(x_test, batch_size=2048)[0].flatten())
 weights.append(2 ** global_epoch)
 predictions = np.average(checkpoint_predictions, weights=weights, axis=0)
 submission = pd.DataFrame.from_dict({
'id': test_df.id,
'prediction': predictions
})
 submission.to_csv('submission.csv', index=False )<train_model>
if debug:
train_preds, test_preds = cpu_kfold_train(x_train,y_train,x_test,model,train_features,test_features)
 else :
train_preds, test_preds = kfold_train(x_train,y_train,x_test,model,train_features,test_features )
from fastai.train import Learner
from fastai.train import DataBunch
from fastai.callbacks import *
from fastai.basic_data import DatasetType<import_modules>
def findthreshold(y_train, train_preds):
best_f1= 0
best_thresh= 0
for thresh in tqdm(np.arange(0.1,0.501,0.01)) :
f1 = f1_score(y_train,(train_preds>thresh))
if f1 > best_f1:
best_thresh = thresh
best_f1 = f1
print('best threshold is {:.4f} with F1 score: {:.4f}'.format(best_thresh, best_f1))
return best_thresh, best_f1
threshold, score = findthreshold(y_train,train_preds )
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<set_options>
if debug:
df_test = pd.read_csv(".. /input/quora-insincere-questions-classification/test.csv")[:200]
else:
df_test = pd.read_csv(".. /input/quora-insincere-questions-classification/test.csv")
 submission = df_test[['qid']].copy()
submission['prediction'] =(test_preds > threshold ).astype(int)
 submission.to_csv('submission.csv', index=False )