Kaggle competition: Jigsaw Unintended Bias in Toxicity Classification
<SOS> metric: JigsawBiasAUC Kaggle data source: jigsaw-unintended-bias-in-toxicity-classification<filter>
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, Bidirectional, SpatialDropout1D, Conv1D, GlobalAveragePooling1D, GlobalMaxPooling1D
from keras.optimizers import RMSprop, Adam
from keras.models import Model
from keras.callbacks import EarlyStopping
import seaborn as sns
train_dataset[train_dataset['Embarked'].isnull() ]<filter>
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()
train_dataset[(train_dataset['Pclass'] == 1)&(train_dataset['Survived']==1)].mean() ['Fare']<groupby>
df = pd.concat([train[['id','comment_text']], test], axis=0)
 del(train, test)
 gc.collect()
train_dataset.groupby(['Embarked','Pclass'] ).mean()<data_type_conversions>
ft_common_crawl = '.. /input/fasttext-crawl-300d-2m/crawl-300d-2M.vec'
embeddings_index = KeyedVectors.load_word2vec_format(ft_common_crawl )
train_dataset['Embarked'] = train_dataset['Embarked'].fillna('C')
 train_dataset['Embarked'].isnull().sum() 
<drop_column>
gc.collect()
train_dataset.drop('Cabin',axis=1,inplace=True)
 test_dataset.drop('Cabin',axis=1,inplace=True )<count_missing_values>
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
train_dataset['Age'].isnull().sum()<feature_engineering>
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
train_dataset['Ageband'] = pd.cut(train_dataset['Age'], 5)
 train_dataset.head()<feature_engineering>
df['comment_text'] = df['comment_text'].apply(lambda x: x.lower())
 gc.collect()
test_dataset['Ageband'] = pd.cut(test_dataset['Age'], 5)
 test_dataset.head()<count_values>
vocab = build_vocab(df['comment_text'])
 oov = check_coverage(vocab, embeddings_index)
 oov[:10]
print(train_dataset['Ageband'].value_counts())
 print("---"*40)
 print(test_dataset['Ageband'].value_counts() )<feature_engineering>
gc.collect()
train_dataset.loc[train_dataset['Age']<= 16,'Age']=0
train_dataset.loc[(train_dataset['Age']>16)&(train_dataset['Age']<=32),'Age']=1
train_dataset.loc[(train_dataset['Age']>32)&(train_dataset['Age']<=48),'Age']=2
train_dataset.loc[(train_dataset['Age']>48)&(train_dataset['Age']<=64),'Age']=3
train_dataset.loc[(train_dataset['Age']>64),'Age']=4
train_dataset.head()<data_type_conversions>
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" }
train_dataset.Age = train_dataset.Age.astype(int )<feature_engineering>
del(vocab,oov)
 gc.collect()
test_dataset.loc[test_dataset['Age']<= 16,'Age']=0
test_dataset.loc[(test_dataset['Age']>16)&(test_dataset['Age']<=32),'Age']=1
test_dataset.loc[(test_dataset['Age']>32)&(test_dataset['Age']<=48),'Age']=2
test_dataset.loc[(test_dataset['Age']>48)&(test_dataset['Age']<=64),'Age']=3
test_dataset.loc[(test_dataset['Age']>64),'Age']=4
test_dataset.head()<data_type_conversions>
def known_contractions(embed):
known = []
for contract in contraction_mapping:
if contract in embed:
known.append(contract)
 return known
test_dataset.Age = test_dataset.Age.astype(int )<feature_engineering>
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_dataset['Family']= train_dataset['SibSp']+train_dataset['Parch']+1
train_dataset.head()<feature_engineering>
df['comment_text'] = df['comment_text'].apply(lambda x: clean_contractions(x, contraction_mapping))
test_dataset['Family']= test_dataset['SibSp']+test_dataset['Parch']+1
test_dataset.head()<feature_engineering>
vocab = build_vocab(df['comment_text'])
 oov = check_coverage(vocab, embeddings_index)
 oov[:10]
train_dataset['IsAlone']=0
train_dataset.loc[train_dataset.Family == 1,'IsAlone']=1
test_dataset['IsAlone']=0
test_dataset.loc[test_dataset.Family == 1,'IsAlone']=1<feature_engineering>
del(vocab,oov)
 gc.collect()
test_dataset['Fareband'] = pd.qcut(test_dataset['Fare'],4)
 test_dataset.head(10 )<count_values>
def unknown_punct(embed, punct):
unknown = ''
for p in punct:
if p not in embed:
unknown += p
unknown += ' '
return unknown
print(train_dataset['Fareband'].value_counts())
 print("---"*40)
 print(test_dataset['Fareband'].value_counts() )<feature_engineering>
punct_mapping = {"_":" ", "`":" "}
train_dataset.loc[train_dataset['Fare']<=7.91,'Fare']=0
train_dataset.loc[(train_dataset['Fare']>7.91)&(train_dataset['Fare']<=14.454),'Fare']=1
train_dataset.loc[(train_dataset['Fare']>14.454)&(train_dataset['Fare']<=31),'Fare']=2
train_dataset.loc[(train_dataset['Fare']>31),'Fare']=3
train_dataset.Fare = train_dataset.Fare.astype(int)
 test_dataset.Fare = test_dataset.Fare.fillna(test_dataset.Fare.mean())
 test_dataset.loc[test_dataset['Fare']<=7.91,'Fare']=0
test_dataset.loc[(test_dataset['Fare']>7.91)&(test_dataset['Fare']<=14.454),'Fare']=1
test_dataset.loc[(test_dataset['Fare']>14.454)&(test_dataset['Fare']<=31),'Fare']=2
test_dataset.loc[(test_dataset['Fare']>31),'Fare']=3
test_dataset.Fare = test_dataset.Fare.astype(int)
<drop_column>
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
train_dataset.columns
test_dataset.columns
train_dataset.drop(['Name','SibSp','Parch','Ageband','Family','Fareband'],axis=1,inplace=True)
 test_dataset.drop(['Name','SibSp','Parch','Ageband','Family','Fareband'],axis=1,inplace=True )<drop_column>
df['comment_text'] = df['comment_text'].apply(lambda x: clean_special_chars(x, punct, punct_mapping))
train_pid = train_dataset['PassengerId']
train_dataset.drop('PassengerId',axis=1,inplace=True)
 test_pid = test_dataset['PassengerId']
test_dataset.drop('PassengerId',axis=1,inplace=True )<categorify>
vocab = build_vocab(df['comment_text'])
 oov = check_coverage(vocab, embeddings_index)
label_encoder = preprocessing.LabelEncoder()
train_dataset['Title'] = label_encoder.fit_transform(train_dataset['Title'])
 train_dataset['Sex'] = label_encoder.fit_transform(train_dataset['Sex'])
 train_dataset['Embarked'] = label_encoder.fit_transform(train_dataset['Embarked'] )<categorify>
del(vocab,oov)
 gc.collect()
label_encoder = preprocessing.LabelEncoder()
test_dataset['Title'] = label_encoder.fit_transform(test_dataset['Title'])
 test_dataset['Sex'] = label_encoder.fit_transform(test_dataset['Sex'])
 test_dataset['Embarked'] = label_encoder.fit_transform(test_dataset['Embarked'])
 test_dataset.head()<prepare_x_and_y>
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 '
]
X = train_dataset.drop('Survived',axis=1)
 Y = train_dataset['Survived']
Z = test_dataset<split>
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
X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.33,random_state=0 )<compute_train_metric>
def handle_swears(text):
text = re.sub(replace_with_fuck, ' fuck ', text)
 return text
svc = SVC(C=4,gamma='auto')
 svc.fit(X_train, Y_train)
 y_svc = svc.predict(X_test)
 acc_svc = round(svc.score(X_train, Y_train)* 100, 2)
 print("accuracy score is = {0}
f-score is = {1}".format(acc_svc,f1_score(Y_test,y_svc)))
 sns.heatmap(confusion_matrix(Y_test,y_svc),annot=True,fmt='2.0f' )<find_best_params>
df['comment_text'] = df['comment_text'].apply(lambda x: handle_swears(x))
gc.collect()
accuracy_kscore = []
for k in range(3,10):
knn = KNeighborsClassifier(n_neighbors = k)
 knn.fit(X_train, Y_train)
 Y_pred = knn.predict(X_test)
 acc_knn = round(knn.score(X_train, Y_train)* 100, 2)
 accuracy_kscore.append([k,acc_knn])
 acc_knndf = pd.DataFrame(data=accuracy_kscore,columns=['k','accuracy'])
 sns.barplot(x=acc_knndf['k'],y=acc_knndf['accuracy'],data=acc_knndf)
 acc_knndf.sort_values(by='accuracy',ascending=False)
<compute_train_metric>
train = df.iloc[:1804874,:]
test = df.iloc[1804874:,:]
train.head()
knn = KNeighborsClassifier(n_neighbors = 3)
 knn.fit(X_train, Y_train)
 Y_knn = knn.predict(X_test)
 acc_knn = round(knn.score(X_train, Y_train)* 100, 2)
 print("accuracy score is = {0}
f-score is = {1}".format(acc_knn,f1_score(Y_test,Y_knn)))
 sns.heatmap(confusion_matrix(Y_test,Y_knn),annot=True,fmt='2.0f' )<predict_on_test>
del(df)
 gc.collect()
gaussian = GaussianNB()
gaussian.fit(X_train, Y_train)
 Y_gauss = gaussian.predict(X_test)
 acc_gaussian = round(gaussian.score(X_train, Y_train)* 100, 2)
 acc_gaussian<compute_train_metric>
train_orig = pd.read_csv(".. /input/jigsaw-unintended-bias-in-toxicity-classification/train.csv")
 train_orig.head()
decision_tree = DecisionTreeClassifier(max_depth=10)
 decision_tree.fit(X_train, Y_train)
 Y_decision = decision_tree.predict(X_test)
 acc_decision_tree = round(decision_tree.score(X_train, Y_train)* 100, 2)
 acc_decision_tree<compute_train_metric>
train = pd.concat([train,train_orig[['target']]],axis=1)
 train.head()
random_forest = RandomForestClassifier(n_estimators=400)
 random_forest.fit(X_train, Y_train)
 Y_random = random_forest.predict(X_test)
 Y_Pred = random_forest.predict(Z)
 random_forest.score(X_train, Y_train)
 acc_random_forest = round(random_forest.score(X_train, Y_train)* 100, 2)
 acc_random_forest 
<import_modules>
del(train_orig)
 gc.collect()
kfold = KFold(n_splits=10,random_state=10)
 classfy_mean = [];
accuracy_kfold = []
classifier = ['Logistic regression','SVC','KNN','Gaussian NB','Decision Tree','Random Forest']
models = [LogisticRegression() ,SVC(C=4,gamma='auto'),KNeighborsClassifier(n_neighbors=3),GaussianNB() ,
DecisionTreeClassifier(max_depth=10),RandomForestClassifier(n_estimators=100)]
for i in models:
model = i
cv_result = cross_val_score(model,X,Y,cv=kfold,scoring='accuracy')
 accuracy_kfold.append(cv_result)
 classfy_mean.append(cv_result.mean())
 classfy_mean
df = pd.DataFrame(data=classfy_mean,index=classifier,columns=['cross-accuracy'])
 df.sort_values(by='cross-accuracy',ascending=False )<save_to_csv>
train['target'] = np.where(train['target'] >= 0.5, True, False )
submission = pd.DataFrame({
"PassengerId": test_pid,
"Survived": Y_Pred
})
 submission
submission.to_csv("titanic_submission.csv", index=False )<load_from_csv>
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)) )
df_train = pd.read_csv('.. /input/train.csv')
 df_test = pd.read_csv('.. /input/test.csv' )<set_options>
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 )
warnings.filterwarnings('ignore')
 %matplotlib inline<define_variables>
gc.collect()
test_ID = df_test['Id']<drop_column>
EMBEDDINGS_DIMENSION = 300
embedding_matrix = np.zeros(( len(tokenizer.word_index)+ 1,EMBEDDINGS_DIMENSION))
del df_train['Id']
del df_test['Id']<concatenate>
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
all_data = pd.concat(( df_train, df_test)).reset_index(drop=True )<drop_column>
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]
all_data.drop(columns={'3SsnPorch','BedroomAbvGr','BsmtFinSF2','BsmtFullBath','BsmtHalfBath','BsmtUnfSF','EnclosedPorch','KitchenAbvGr','LotArea','LowQualFinSF','MSSubClass','MiscVal','MoSold','OverallCond','PoolArea','ScreenPorch','YrSold'},inplace=True )<create_dataframe>
gc.collect()
all_data_na =(all_data.isnull().sum() / len(all_data)) * 100
all_data_na = all_data_na.drop(all_data_na[all_data_na == 0].index ).sort_values(ascending=False)[:30]
missing_data = pd.DataFrame({'Missing Ratio' :all_data_na})
 missing_data.head(20 )<drop_column>
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(CuDNNGRU(64, return_sequences=True))(x)
 x = Conv1D(64, kernel_size = 2, padding = "valid", kernel_initializer = "he_uniform" )(x)
 avg_pool1 = GlobalAveragePooling1D()(x)
 max_pool1 = GlobalMaxPooling1D()(x)
 x = concatenate([avg_pool1, max_pool1])
 preds = Dense(1, activation='sigmoid' )(x)
 model = Model(sequence_input, preds)
 model.summary()
all_data.drop(columns={'PoolQC','MiscFeature','Alley','Fence','FireplaceQu'},inplace=True )<prepare_x_and_y>
model.compile(loss='binary_crossentropy',
optimizer=Adam() ,
metrics=['acc'] )
ntrain = df_train.shape[0]
ntest = df_test.shape[0]
y_train = df_train.SalePrice.values
all_data.drop(['SalePrice'], axis=1, inplace=True)
 print("all_data size is : {}".format(all_data.shape))<data_type_conversions>
BATCH_SIZE = 1024
NUM_EPOCHS = 100
all_data['GarageYrBlt']=all_data['GarageYrBlt'].fillna(0 )<data_type_conversions>
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)])
all_data['MasVnrType']=all_data['MasVnrType'].fillna('None')
 all_data['MasVnrArea']=all_data['MasVnrArea'].fillna(0 )<categorify>
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 )