Kaggle competition: Quora Insincere Questions Classification
<SOS> metric: FScore_1 Kaggle data source: quora-insincere-questions-classification<save_to_csv>
import re
import time
import gc
import random
import os
from functools import wraps
import numpy as np
import pandas as pd
from tqdm import tqdm
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import f1_score
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
import torch
import torch.nn as nn
import torch.utils.data
from torch.nn import Parameter
model = Ridge(alpha=330)
 model.fit(X, Y)
 test_predicted = pd.DataFrame()
test_predicted['Id'] = test_data.Id
test_predicted['Prediction'] = model.predict(test_data.drop('Id', axis=1))
test_predicted.to_csv('submission-ridge-330.csv', index=False)
 test_predicted.describe()<save_to_csv>
embed_size = 300
max_features = 95000
maxlen = 72
n_splits = 4
batch_size = 512
train_epochs = 6
SEED = 1029
model = Lasso(alpha=200000)
 model.fit(X, Y)
 test_predicted = pd.DataFrame()
test_predicted['Id'] = test_data.Id
test_predicted['Prediction'] = model.predict(test_data.drop('Id', axis=1))
test_predicted.to_csv('submission-lasso-high-alpha.csv', index=False)
 test_predicted.describe()<count_unique_values>
def seed_torch(seed=1029):
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_torch(SEED )
for c in X.columns:
print(c, len(X[c].unique()))<drop_column>
puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', '
'·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…',
'“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾', '═', '¦', '║', '―', '¥', '▓', '—', '‹', '─',
'▒', '：', '¼', '⊕', '▼', '▪', '†', '■', '’', '▀', '¨', '▄', '♫', '☆', 'é', '¯', '♦', '¤', '▲', 'è', '¸', '¾', 'Ã', '⋅', '‘', '∞',
'∙', '）', '↓', '、', '│', '（', '»', '，', '♪', '╩', '╚', '³', '・', '╦', '╣', '╔', '╗', '▬', '❤', 'ï', 'Ø', '¹', '≤', '‡', '√', ]
def clean_text(x):
x = str(x)
 for punct in puncts:
x = x.replace(punct, f' {punct} ')
 return x
def clean_numbers(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
mispell_dict = {"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", 'colour': 'color', 'centre': 'center', 'favourite': 'favorite', 'travelling': 'traveling', 'counselling': 'counseling', 'theatre': 'theater', 'cancelled': 'canceled', 'labour': 'labor', 'organisation': 'organization', 'wwii': 'world war 2', 'citicise': 'criticize', 'youtu ': 'youtube ', 'Qoura': 'Quora', 'sallary': 'salary', 'Whta': 'What', 'narcisist': 'narcissist', 'howdo': 'how do', 'whatare': 'what are', 'howcan': 'how can', 'howmuch': 'how much', 'howmany': 'how many', 'whydo': 'why do', 'doI': 'do I', 'theBest': 'the best', 'howdoes': 'how does', 'mastrubation': 'masturbation', 'mastrubate': 'masturbate', "mastrubating": 'masturbating', 'pennis': 'penis', 'Etherium': 'Ethereum', 'narcissit': 'narcissist', 'bigdata': 'big data', '2k17': '2017', '2k18': '2018', 'qouta': 'quota', 'exboyfriend': 'ex boyfriend', 'airhostess': 'air hostess', "whst": 'what', 'watsapp': 'whatsapp', 'demonitisation': 'demonetization', 'demonitization': 'demonetization', 'demonetisation': 'demonetization'}
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 )
data['Time_Open'] = round(data['Days_Open'] / 700, 0)
 data = data.drop('Days_Open', axis=1)
 test_data['Time_Open'] = round(test_data['Days_Open'] / 700, 0)
 test_data = test_data.drop('Days_Open', axis=1 )<prepare_x_and_y>
def load_and_prec() :
train_df = pd.read_csv(".. /input/train.csv")
 test_df = pd.read_csv(".. /input/test.csv")
 print("Train shape : ",train_df.shape)
 print("Test shape : ",test_df.shape)
 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())
 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))
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))
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))
train_X = train_df["question_text"].fillna("_
test_X = test_df["question_text"].fillna("_
tokenizer = Tokenizer(num_words=max_features)
 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
np.random.seed(SEED)
 trn_idx = np.random.permutation(len(train_X))
train_X = train_X[trn_idx]
train_y = train_y[trn_idx]
return train_X, test_X, train_y, tokenizer.word_index
X = data.drop(['Id', 'revenue'], axis=1)
 Y = data.revenue<save_to_csv>
def load_glove(word_index):
EMBEDDING_FILE = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
 embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE))
all_embs = np.stack(embeddings_index.values())
 emb_mean,emb_std = all_embs.mean() , all_embs.std()
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
def load_para(word_index):
EMBEDDING_FILE = '.. /input/embeddings/paragram_300_sl999/paragram_300_sl999.txt'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
 embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE, encoding="utf8", errors='ignore')if len(o)>100)
 all_embs = np.stack(embeddings_index.values())
 emb_mean,emb_std = all_embs.mean() , all_embs.std()
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
model = Ridge(alpha=330)
 model.fit(X, Y)
 test_predicted = pd.DataFrame()
test_predicted['Id'] = test_data.Id
test_predicted['Prediction'] = model.predict(test_data.drop('Id', axis=1))
test_predicted.to_csv('submission-ridge-330-div-700.csv', index=False)
 test_predicted.describe()<save_to_csv>
tqdm.pandas()
start_time = time.time()
train_X, test_X, train_y, word_index = load_and_prec()
embedding_matrix_1 = load_glove(word_index)
 embedding_matrix_2 = load_para(word_index)
 total_time =(time.time() - start_time)/ 60
print("Took {:.2f} minutes".format(total_time))
embedding_matrix = np.mean([embedding_matrix_1, embedding_matrix_2], axis=0)
 print(np.shape(embedding_matrix))
del embedding_matrix_1, embedding_matrix_2
gc.collect()
model = Lasso(alpha=200000)
 model.fit(X, Y)
 test_predicted = pd.DataFrame()
test_predicted['Id'] = test_data.Id
test_predicted['Prediction'] = model.predict(test_data.drop('Id', axis=1))
test_predicted.to_csv('submission-lasso-high-alpha-div-700.csv', index=False)
 test_predicted.describe()<load_from_csv>
class Attention(nn.Module):
def __init__(self, feature_dim, step_dim, bias=True, **kwargs):
super(Attention, 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 )
trainData = pd.read_csv('.. /input/train.csv')
 testData = pd.read_csv('.. /input/test.csv')
 trainData = trainData.drop('Id', axis=1)
 testData = testData.drop('Id', axis=1 )<data_type_conversions>
splits = list(StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=SEED ).split(train_X, train_y))
trainData['Open Date'] = pd.to_datetime(trainData['Open Date'], format='%m/%d/%Y')
 testData['Open Date'] = pd.to_datetime(testData['Open Date'], format='%m/%d/%Y')
 trainData['OpenDays']=""
testData['OpenDays']=""
dateLastTrain = pd.DataFrame({'Date':np.repeat(['01/01/2015'],[len(trainData)])})
 dateLastTrain['Date'] = pd.to_datetime(dateLastTrain['Date'], format='%m/%d/%Y')
 dateLastTest = pd.DataFrame({'Date':np.repeat(['01/01/2015'],[len(testData)])})
 dateLastTest['Date'] = pd.to_datetime(dateLastTest['Date'], format='%m/%d/%Y')
 trainData['OpenDays'] = dateLastTrain['Date'] - trainData['Open Date']
testData['OpenDays'] = dateLastTest['Date'] - testData['Open Date']
trainData['OpenDays'] = trainData['OpenDays'].astype('timedelta64[D]' ).astype(int)
 testData['OpenDays'] = testData['OpenDays'].astype('timedelta64[D]' ).astype(int)
 trainData = trainData.drop('Open Date', axis=1)
 testData = testData.drop('Open Date', axis=1 )<categorify>
def sigmoid(x):
return 1 /(1 + np.exp(-x))
def threshold_search(y_true, y_proba):
best_threshold = 0
best_score = 0
for threshold in [i * 0.01 for i in range(100)]:
score = f1_score(y_true=y_true, y_pred=y_proba > threshold)
 if score > best_score:
best_threshold = threshold
best_score = score
search_result = {'threshold': best_threshold, 'f1': best_score}
return search_result
cityPerc = trainData[["City Group", "revenue"]].groupby(['City Group'],as_index=False ).mean()
citygroupDummy = pd.get_dummies(trainData['City Group'])
 trainData = trainData.join(citygroupDummy)
 citygroupDummyTest = pd.get_dummies(testData['City Group'])
 testData = testData.join(citygroupDummyTest)
 trainData = trainData.drop('City Group', axis=1)
 testData = testData.drop('City Group', axis=1 )<prepare_x_and_y>
x_test_cuda = torch.tensor(test_X, 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 )
sns.set_context("notebook", font_scale=1.1)
 sns.set_style("ticks")
 xTrain = pd.DataFrame({'OpenDays':trainData['OpenDays'].apply(numpy.log),
'Big Cities':trainData['Big Cities'], 'Other':trainData['Other'],
'P2':trainData['P2'], 'P8':trainData['P8'], 'P22':trainData['P22'],
'P24':trainData['P24'], 'P28':trainData['P28'], 'P26':trainData['P26']})
 yTrain = trainData['revenue'].apply(numpy.log)
 xTest = pd.DataFrame({'OpenDays':testData['OpenDays'].apply(numpy.log),
'Big Cities':testData['Big Cities'], 'Other':testData['Other'],
'P2':testData['P2'], 'P8':testData['P8'], 'P22':testData['P22'],
'P24':testData['P24'], 'P28':testData['P28'], 'P26':testData['P26']})
 cls = RandomForestRegressor(n_estimators=150)
 cls.fit(xTrain, yTrain)
 pred = cls.predict(xTest)
 pred = numpy.exp(pred)
 cls.score(xTrain, yTrain )<predict_on_test>
class BackHook(torch.nn.Module):
def __init__(self, hook):
super(BackHook, self ).__init__()
self._hook = hook
self.register_backward_hook(self._backward)
 def forward(self, *inp):
return inp
@staticmethod
def _backward(self, grad_in, grad_out):
self._hook()
return None
class WeightDrop(torch.nn.Module):

 def __init__(self, module, weights, dropout=0, variational=False):
super(WeightDrop, self ).__init__()
self.module = module
self.weights = weights
self.dropout = dropout
self.variational = variational
self._setup()
self.hooker = BackHook(lambda: self._backward())
 def _setup(self):
for name_w in self.weights:
print('Applying weight drop of {} to {}'.format(self.dropout, name_w))
w = getattr(self.module, name_w)
 self.register_parameter(name_w + '_raw', Parameter(w.data))
def _setweights(self):
for name_w in self.weights:
raw_w = getattr(self, name_w + '_raw')
 mask = raw_w.new_ones(( raw_w.size(0), 1))
mask = torch.nn.functional.dropout(mask, p=self.dropout, training=True)
 w = mask.expand_as(raw_w)* raw_w
rnn_w = getattr(self.module, name_w)
 rnn_w.data.copy_(w)
 setattr(self, name_w + "_mask", mask)
 def _backward(self):
for name_w in self.weights:
raw_w = getattr(self, name_w + '_raw')
 rnn_w = getattr(self.module, name_w)
 raw_w.grad = rnn_w.grad * getattr(self, name_w + "_mask")
 def forward(self, *args):
self._setweights()
return self.module(*self.hooker(*args))
pred = cls.predict(xTest)
 pred = numpy.exp(pred )<feature_engineering>
class NeuralNet(nn.Module):
def __init__(self):
super(NeuralNet, self ).__init__()
hidden_size = 60
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.lstm = WeightDrop(nn.LSTM(embed_size, hidden_size, bidirectional=True, batch_first=True), ['weight_hh_l0'], dropout=0.1)
 self.gru = WeightDrop(nn.GRU(hidden_size*2, hidden_size, bidirectional=True, batch_first=True), ['weight_hh_l0'], dropout=0.1)
 self.lstm_attention = Attention(hidden_size*2, maxlen)
 self.gru_attention = Attention(hidden_size*2, maxlen)
 self.linear = WeightDrop(nn.Linear(hidden_size*8, 24), ['weight'], dropout=0.1)
 self.relu = nn.ReLU()
self.out = nn.Linear(24, 1)
 def forward(self, x):
h_embedding = self.embedding(x)
 h_lstm, _ = self.lstm(h_embedding)
 h_gru, _ = self.gru(h_lstm)
 h_lstm_atten = self.lstm_attention(h_lstm)
 h_gru_atten = self.gru_attention(h_gru)
 avg_pool = torch.mean(h_gru, 1)
 max_pool, _ = torch.max(h_gru, 1)
 conc = torch.cat(( h_lstm_atten, h_gru_atten, avg_pool, max_pool), 1)
 conc = self.relu(self.linear(conc))
out = self.out(conc)
 return out
pred2 = []
for i in range(len(pred)) :
if pred[i] != float('Inf'):
pred2.append(pred[i])
 m = sum(pred2)/ float(len(pred2))
for i in range(len(pred)) :
if pred[i] == float('Inf'):
print("haha")
 pred[i] = m<save_to_csv>
train_preds = np.zeros(( len(train_X)))
 test_preds = np.zeros(( len(test_X)))
 for i,(train_idx, valid_idx)in enumerate(splits):
x_train_fold = torch.tensor(train_X[train_idx], dtype=torch.long ).cuda()
y_train_fold = torch.tensor(train_y[train_idx, np.newaxis], dtype=torch.float32 ).cuda()
x_val_fold = torch.tensor(train_X[valid_idx], dtype=torch.long ).cuda()
y_val_fold = torch.tensor(train_y[valid_idx, np.newaxis], dtype=torch.float32 ).cuda()
model = NeuralNet()
model.cuda()
loss_fn = torch.nn.BCEWithLogitsLoss(reduction="sum")
 optimizer = torch.optim.Adam(model.parameters())
 train = torch.utils.data.TensorDataset(x_train_fold, y_train_fold)
 valid = torch.utils.data.TensorDataset(x_val_fold, y_val_fold)
 train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True)
 valid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False)
 print(f'Fold {i + 1}')
 for epoch in range(train_epochs):
start_time = time.time()
model.train()
avg_loss = 0.
 for x_batch, y_batch in tqdm(train_loader, disable=True):
y_pred = model(x_batch)
 loss = loss_fn(y_pred, y_batch)
 optimizer.zero_grad()
loss.backward()
optimizer.step()
avg_loss += loss.item() / len(train_loader)
 model.eval()
valid_preds_fold = np.zeros(( x_val_fold.size(0)))
 test_preds_fold = np.zeros(len(test_X))
avg_val_loss = 0.
 for i,(x_batch, y_batch)in enumerate(valid_loader):
y_pred = model(x_batch ).detach()
avg_val_loss += loss_fn(y_pred, y_batch ).item() / len(valid_loader)
 valid_preds_fold[i * batch_size:(i+1)* batch_size] = 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, train_epochs, avg_loss, avg_val_loss, elapsed_time))
for i,(x_batch,)in enumerate(test_loader):
y_pred = model(x_batch ).detach()
test_preds_fold[i * batch_size:(i+1)* batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0]
train_preds[valid_idx] = valid_preds_fold
test_preds += test_preds_fold / len(splits )
testData = pd.read_csv(".. /input/test.csv")
 submission = pd.DataFrame({
"Id": testData["Id"],
"Prediction": pred
})
 submission.to_csv('RandomForestSimple.csv',header=True, index=False )<import_modules>
search_result = threshold_search(train_y, train_preds)
 search_result
import os
from pathlib import Path
from PIL import Image<load_from_csv>
sub = pd.read_csv('.. /input/sample_submission.csv')
 sub.prediction = test_preds > search_result['threshold']
sub.to_csv("submission.csv", index=False)
 print(sub.groupby("prediction" ).size() )