Kaggle competition: Jigsaw Unintended Bias in Toxicity Classification
<SOS> metric: JigsawBiasAUC Kaggle data source: jigsaw-unintended-bias-in-toxicity-classification<feature_engineering>
import gc
import re
import operator
import numpy as np
import pandas as pd
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, CuDNNGRU,concatenate, Dropout, Bidirectional,CuDNNLSTM, SpatialDropout1D, Conv1D, GlobalAveragePooling1D, GlobalMaxPooling1D
from keras.optimizers import RMSprop, Adam
from keras.models import Model
from keras.callbacks import EarlyStopping
import seaborn as sns
<feature_engineering>
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")
 print("Train shape : ",train.shape)
 print("Test shape : ",test.shape)
 train.head()
<feature_engineering>
df = pd.concat([train[['id','comment_text']], test], axis=0)
 del(train, test)
 gc.collect()
test.loc[(test.Sex == 0)&(test.Age.isna())&(test.Pclass == 1), "Age"] = 34.6
test.loc[(test.Sex == 0)&(test.Age.isna())&(test.Pclass == 2), "Age"] = 28.7
test.loc[(test.Sex == 0)&(test.Age.isna())&(test.Pclass == 3), "Age"] = 21.7
test.loc[(test.Sex == 1)&(test.Age.isna())&(test.Pclass == 1), "Age"] = 41.2
test.loc[(test.Sex == 1)&(test.Age.isna())&(test.Pclass == 2), "Age"] = 30.7
test.loc[(test.Sex == 1)&(test.Age.isna())&(test.Pclass == 3), "Age"] = 26.5<feature_engineering>
ft_common_crawl = '.. /input/fasttext-crawl-300d-2m/crawl-300d-2M.vec'
embeddings_index = KeyedVectors.load_word2vec_format(ft_common_crawl )
<data_type_conversions>
gc.collect()
for i in range(len(test)) :
if test.loc[i, "SibSp"] + test.loc[i, "Parch"] == 0:
test.loc[i, "Alone"] = 1
else:
test.loc[i, "Alone"] = 0
test.Alone = test.Alone.astype(int )<concatenate>
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
test_new = pd.concat([test, test_Embarked], axis=1)
 test_new.head()<prepare_x_and_y>
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
testX = test_new[feature_name]<normalization>
df['comment_text'] = df['comment_text'].apply(lambda x: x.lower())
 gc.collect()
testX = scaler.transform(testX )<prepare_output>
vocab = build_vocab(df['comment_text'])
 oov = check_coverage(vocab, embeddings_index)
 oov[:10]
testX = pd.DataFrame(testX, columns=feature_name)
 testX.head()<predict_on_test>
gc.collect()
predict = model.predict_classes(testX )<save_to_csv>
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" }
my_submission = pd.DataFrame({'PassengerId': test.PassengerId, 'Survived': predict})
 my_submission.to_csv('submission.csv', index=False )<set_options>
del(vocab,oov)
 gc.collect()
warnings.filterwarnings('ignore')
<load_from_csv>
def known_contractions(embed):
known = []
for contract in contraction_mapping:
if contract in embed:
known.append(contract)
 return known
train = pd.read_csv('.. /input/nlp-getting-started/train.csv')
 test = pd.read_csv('.. /input/nlp-getting-started/test.csv')
 train.head()<define_variables>
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
sentences = ['The weather is sunny', 'The weather is partly sunny and partly cloudy.']<train_on_grid>
df['comment_text'] = df['comment_text'].apply(lambda x: clean_contractions(x, contraction_mapping))
vectorizer = CountVectorizer()
vectorizer.fit(sentences)
 vectorizer.vocabulary_<categorify>
vocab = build_vocab(df['comment_text'])
 oov = check_coverage(vocab, embeddings_index)
 oov[:10]
vectorizer.transform(sentences ).toarray()<feature_engineering>
del(vocab,oov)
 gc.collect()
stopwords = stopwords.words('english')
 count_vectorizer = CountVectorizer(stop_words = stopwords)
 count_vectorizer.fit(train['text'])
 train_vectors = count_vectorizer.transform(train['text'])
 test_vectors = count_vectorizer.transform(test['text'])
 train_vectors.shape<feature_engineering>
def unknown_punct(embed, punct):
unknown = ''
for p in punct:
if p not in embed:
unknown += p
unknown += ' '
return unknown
count_vectorizer = CountVectorizer(stop_words = stopwords, min_df=2 ,max_df=0.8)
 count_vectorizer.fit(train['text'])
 train_vectors = count_vectorizer.transform(train['text'])
 test_vectors = count_vectorizer.transform(test['text'] )<categorify>
punct_mapping = {"_":" ", "`":" "}
def custom_preprocessor(text):

 text = text.lower()
text = re.sub('\[.*?\]', '', text)
 text = re.sub("\\W"," ",text)
 text = re.sub('https?://\S+|www\.\S+', '', text)
 text = re.sub('<.*?>+', '', text)
 text = re.sub('[%s]' % re.escape(string.punctuation), '', text)
 text = re.sub('
', '', text)
 text = re.sub('\w*\d\w*', '', text)
 return text 
<feature_engineering>
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
count_vectorizer = CountVectorizer(list(train['text']),preprocessor=custom_preprocessor)
 train_vectors = count_vectorizer.fit_transform(list(train['text']))
test_vectors = count_vectorizer.transform(list(test['text'])) 
<feature_engineering>
df['comment_text'] = df['comment_text'].apply(lambda x: clean_special_chars(x, punct, punct_mapping))
count_vectorizer = CountVectorizer(list(train['text']),preprocessor=custom_preprocessor,ngram_range=(1,2))
train_vectors = count_vectorizer.fit_transform(list(train['text']))
test_vectors = count_vectorizer.transform(list(test['text']))
list(count_vectorizer.vocabulary_)[:10]<feature_engineering>
vocab = build_vocab(df['comment_text'])
 oov = check_coverage(vocab, embeddings_index)
count_vectorizer = CountVectorizer(list(train['text']),preprocessor=custom_preprocessor,ngram_range=(2,2),
analyzer='char_wb')
 train_vectors = count_vectorizer.fit_transform(list(train['text']))
test_vectors = count_vectorizer.transform(list(test['text']))
print(list(count_vectorizer.vocabulary_)[:20] )<feature_engineering>
del(vocab,oov)
 gc.collect()
count_vectorizer = CountVectorizer(token_pattern=r'\w{1,}',
ngram_range=(1, 2), stop_words = stopwords,preprocessor=custom_preprocessor)
 count_vectorizer.fit(train['text'])
 train_vectors = count_vectorizer.transform(train['text'])
 test_vectors = count_vectorizer.transform(test['text'] )<compute_train_metric>
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 '
]
clf = LogisticRegression(C=1.0)
 scores = model_selection.cross_val_score(clf, train_vectors, train["target"], cv=5, scoring="f1")
 scores<train_model>
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)
 replace_with_fuck
clf.fit(train_vectors, train["target"] )<save_to_csv>
def handle_swears(text):
text = re.sub(replace_with_fuck, ' fuck ', text)
 return text
sample_submission = pd.read_csv(".. /input/nlp-getting-started/sample_submission.csv")
 sample_submission["target"] = clf.predict(test_vectors)
 sample_submission.to_csv("submission.csv", index=False )<feature_engineering>
df['comment_text'] = df['comment_text'].apply(lambda x: handle_swears(x))
gc.collect()
tfidf = TfidfVectorizer(analyzer='word',token_pattern=r'\w{1,}',max_features=5000)
 train_tfidf = tfidf.fit_transform(train['text'])
 test_tfidf = tfidf.transform(test["text"] )<feature_engineering>
train = df.iloc[:1804874,:]
test = df.iloc[1804874:,:]
train.head()
tfidf = TfidfVectorizer(analyzer='word',ngram_range=(2,3),token_pattern=r'\w{1,}',max_features=5000)
 train_tfidf = tfidf.fit_transform(train['text'])
 test_tfidf = tfidf.transform(test["text"] )<feature_engineering>
del(df)
 gc.collect()
tfidf = TfidfVectorizer(analyzer='char',ngram_range=(2,3),token_pattern=r'\w{1,}',max_features=5000)
 train_tfidf = tfidf.fit_transform(train['text'])
 test_tfidf = tfidf.transform(test["text"])
<feature_engineering>
train_orig = pd.read_csv(".. /input/jigsaw-unintended-bias-in-toxicity-classification/train.csv")
 train_orig.head()
tfidf_vectorizer = TfidfVectorizer(min_df=3, max_features=None,analyzer='word',token_pattern=r'\w{1,}',
ngram_range=(1, 3), use_idf=1,smooth_idf=1,sublinear_tf=1,
stop_words = stopwords)
 train_tfidf = tfidf.fit_transform(train['text'])
 test_tfidf = tfidf.transform(test["text"])
<compute_train_metric>
train = pd.concat([train,train_orig[['target']]],axis=1)
 train.head()
clf = LogisticRegression(C=1.0)
 scores = model_selection.cross_val_score(clf, train_tfidf, train["target"], cv=5, scoring="f1")
 scores<train_model>
del(train_orig)
 gc.collect()
clf.fit(train_tfidf, train["target"] )<train_on_grid>
train['target'] = np.where(train['target'] >= 0.5, True, False )
hash_vectorizer = HashingVectorizer(n_features=10000,norm=None,alternate_sign=False)
 hash_vectorizer.fit(train['text'])
<feature_engineering>
train_df, validate_df = model_selection.train_test_split(train, test_size=0.1)
 print('%d train comments, %d validate comments' %(len(train_df), len(validate_df)) )
train_vectors = hash_vectorizer.transform(train['text'])
 test_vectors = hash_vectorizer.transform(test['text'] )<compute_train_metric>
MAX_NUM_WORDS = 100000
TOXICITY_COLUMN = 'target'
TEXT_COLUMN = 'comment_text'
tokenizer = Tokenizer(num_words=MAX_NUM_WORDS)
 tokenizer.fit_on_texts(train_df[TEXT_COLUMN])
 MAX_SEQUENCE_LENGTH = 256
def pad_text(texts, tokenizer):
return pad_sequences(tokenizer.texts_to_sequences(texts), maxlen=MAX_SEQUENCE_LENGTH )
clf = LogisticRegression(C=1.0)
 scores = model_selection.cross_val_score(clf, train_vectors, train["target"], cv=5, scoring="f1")
 scores<train_model>
gc.collect()
clf.fit(train_vectors, train["target"] )<set_options>
EMBEDDINGS_DIMENSION = 300
embedding_matrix = np.zeros(( len(tokenizer.word_index)+ 1,EMBEDDINGS_DIMENSION))
sns.set(style = 'whitegrid')
 sns.distributions._has_statsmodels = False<load_from_csv>
num_words_in_embedding = 0
for word, i in tokenizer.word_index.items() :
if word in embeddings_index.vocab:
embedding_vector = embeddings_index[word]
embedding_matrix[i] = embedding_vector
num_words_in_embedding += 1
data_train = pd.read_csv('.. /input/titanic/train.csv')
 data_test = pd.read_csv('.. /input/titanic/test.csv' )<create_dataframe>
train_text = pad_text(train_df[TEXT_COLUMN], tokenizer)
 train_labels = train_df[TOXICITY_COLUMN]
validate_text = pad_text(validate_df[TEXT_COLUMN], tokenizer)
 validate_labels = validate_df[TOXICITY_COLUMN]
train = data_train.copy()
test = data_test.copy()<feature_engineering>
gc.collect()
train['Cabin'] = train['Cabin'].str.get(0)
 test['Cabin'] = test['Cabin'].str.get(0 )<define_variables>
def dot_product(x, kernel):

 if K.backend() == 'tensorflow':
return K.squeeze(K.dot(x, K.expand_dims(kernel)) , axis=-1)
 else:
return K.dot(x, kernel)
 class AttentionWithContext(Layer):

 def __init__(self,
W_regularizer=None, u_regularizer=None, b_regularizer=None,
W_constraint=None, u_constraint=None, b_constraint=None,
bias=True, **kwargs):
self.supports_masking = True
self.init = initializers.get('glorot_uniform')
 self.W_regularizer = regularizers.get(W_regularizer)
 self.u_regularizer = regularizers.get(u_regularizer)
 self.b_regularizer = regularizers.get(b_regularizer)
 self.W_constraint = constraints.get(W_constraint)
 self.u_constraint = constraints.get(u_constraint)
 self.b_constraint = constraints.get(b_constraint)
 self.bias = bias
super(AttentionWithContext, self ).__init__(**kwargs)
 def build(self, input_shape):
assert len(input_shape)== 3
self.W = self.add_weight(( input_shape[-1], input_shape[-1],),
initializer=self.init,
name='{}_W'.format(self.name),
regularizer=self.W_regularizer,
constraint=self.W_constraint)
 if self.bias:
self.b = self.add_weight(( input_shape[-1],),
initializer='zero',
name='{}_b'.format(self.name),
regularizer=self.b_regularizer,
constraint=self.b_constraint)
 self.u = self.add_weight(( input_shape[-1],),
initializer=self.init,
name='{}_u'.format(self.name),
regularizer=self.u_regularizer,
constraint=self.u_constraint)
 super(AttentionWithContext, self ).build(input_shape)
 def compute_mask(self, input, input_mask=None):
return None
def call(self, x, mask=None):
uit = dot_product(x, self.W)
 if self.bias:
uit += self.b
uit = K.tanh(uit)
 ait = dot_product(uit, self.u)
 a = K.exp(ait)
 if mask is not None:
a *= K.cast(mask, K.floatx())
 a /= K.cast(K.sum(a, axis=1, keepdims=True)+ K.epsilon() , K.floatx())
 a = K.expand_dims(a)
 weighted_input = x * a
return K.sum(weighted_input, axis=1)
 def compute_output_shape(self, input_shape):
return input_shape[0], input_shape[-1]
num_data = train[['Age', 'SibSp', 'Parch', 'Fare']]
cat_data = train[['Survived', 'Pclass', 'Sex', 'Cabin', 'Embarked']]<train_model>
sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32')
 embedding_layer = Embedding(len(tokenizer.word_index)+ 1,
EMBEDDINGS_DIMENSION,
weights=[embedding_matrix],
input_length=MAX_SEQUENCE_LENGTH,
trainable=False)
 x = embedding_layer(sequence_input)
 x = SpatialDropout1D(0.2 )(x)
 x = Bidirectional(CuDNNLSTM(128, return_sequences=True))(x)
 att = AttentionWithContext()(x)
 avg_pool1 = GlobalAveragePooling1D()(x)
 max_pool1 = GlobalMaxPooling1D()(x)
 x = concatenate([att, avg_pool1, max_pool1])
 x = Dense(256, activation='sigmoid' )(x)
 x = Dense(128, activation='sigmoid' )(x)
 x = Dense(64, activation='sigmoid' )(x)
 preds = Dense(1, activation='sigmoid' )(x)
 model = Model(sequence_input, preds)
 model.summary()
print('Train :
',train.isnull().sum())
 print('
')
 print('Test :
', test.isnull().sum() )<data_type_conversions>
model.compile(loss='binary_crossentropy',
optimizer=Adam() ,
metrics=['acc'] )
train['Age'].fillna(train['Age'].median() , inplace = True)
 test['Age'].fillna(train['Age'].median() , inplace = True)
 train['Fare'].fillna(train['Fare'].median() , inplace = True)
 test['Fare'].fillna(train['Fare'].median() , inplace = True)
 train.dropna(subset=['Embarked'] , inplace = True )<drop_column>
BATCH_SIZE = 1024
NUM_EPOCHS = 40
train.drop(['Cabin'], axis = 1, inplace = True)
 test.drop(['Cabin'], axis = 1, inplace = True )<train_model>
model.fit(
 train_text,
train_labels,
batch_size=BATCH_SIZE,
epochs=NUM_EPOCHS,
validation_data=(validate_text, validate_labels),
callbacks = [EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=3)])
print('Train :
',train.isnull().sum())
 print('
')
 print('Test :
', test.isnull().sum() )<feature_engineering>
submission = pd.read_csv('.. /input/jigsaw-unintended-bias-in-toxicity-classification/sample_submission.csv', index_col='id')
 submission['prediction'] = model.predict(pad_text(test[TEXT_COLUMN], tokenizer))
submission.reset_index(drop=False, inplace=True)
 submission.head()
<feature_engineering><EOS> 
submission.to_csv('submission.csv', index=False )