Kaggle competition: Jigsaw Unintended Bias in Toxicity Classification
<SOS> metric: JigsawBiasAUC Kaggle data source: jigsaw-unintended-bias-in-toxicity-classification<load_from_csv>
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,CuDNNLSTM, Concatenate, 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
test = pd.read_csv(".. /input/test.csv")
 IDtest = test["PassengerId"] 
<drop_column>
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_data.drop(['PassengerId','Ticket'], axis=1, inplace = True)
<count_missing_values>
df = pd.concat([train[['id','comment_text']], test], axis=0)
 del(train, test)
 gc.collect()
train_data.isnull().sum()<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_data["Embarked"] = train_data["Embarked"].fillna("C")
 test["Embarked"] = test["Embarked"].fillna("C")
 train_data['Fare'].fillna(train_data['Fare'].median() , inplace = True)
 test['Fare'].fillna(test['Fare'].median() , inplace = True)
 train_data.Cabin.fillna("N", inplace=True)
 test.Cabin.fillna("N", inplace=True )<count_missing_values>
gc.collect()
train_data.isnull().sum()<feature_engineering>
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_title = [i.split(",")[1].split(".")[0].strip() for i in train_data["Name"]]
train_data["Title"] = pd.Series(train_title)
 train_data["Title"].head()<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
test_title = [i.split(",")[1].split(".")[0].strip() for i in test["Name"]]
test["Title"] = pd.Series(test_title)
 test["Title"].head()<categorify>
df['comment_text'] = df['comment_text'].apply(lambda x: x.lower())
 gc.collect()
train_data["Title"] = train_data["Title"].replace(['Lady', 'the Countess','Countess','Capt', 'Col','Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')
 train_data["Title"] = train_data["Title"].map({"Master":0, "Miss":1, "Ms" : 1 , "Mme":1, "Mlle":1, "Mrs":1, "Mr":2, "Rare":3})
 train_data["Title"] = train_data["Title"].astype(int )<categorify>
vocab = build_vocab(df['comment_text'])
 oov = check_coverage(vocab, embeddings_index)
 oov[:10]
test["Title"] = test["Title"].replace(['Lady', 'the Countess','Countess','Capt', 'Col','Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')
 test["Title"] = test["Title"].map({"Master":0, "Miss":1, "Ms" : 1 , "Mme":1, "Mlle":1, "Mrs":1, "Mr":2, "Rare":3})
 test["Title"] = test["Title"].astype(int )<feature_engineering>
gc.collect()
train_data["Family_size"] = train_data["SibSp"] + train_data["Parch"] + 1
test["Family_size"] = test["SibSp"] + test["Parch"] + 1 
<feature_engineering>
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_data['survived_dead'] = train_data['Survived'].apply(lambda x : 'Survived' if x == 1 else 'Dead' )<categorify>
del(vocab,oov)
 gc.collect()
lbl = LabelEncoder()
lbl.fit(list(train_data['Embarked'].values))
train_data['Embarked'] = lbl.transform(list(train_data['Embarked'].values))
lbl.fit(list(test['Embarked'].values))
test['Embarked'] = lbl.transform(list(test['Embarked'].values))<categorify>
def known_contractions(embed):
known = []
for contract in contraction_mapping:
if contract in embed:
known.append(contract)
 return known
def encode(x): return 1 if x == 'female' else 0
train_data['enc_sex'] = train_data.Sex.apply(encode)
 test['enc_sex'] = test.Sex.apply(encode )<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_data["has_cabin"] = [0 if i == 'N'else 1 for i in train_data.Cabin]
test["has_cabin"] = [0 if i == 'N'else 1 for i in test.Cabin]<feature_engineering>
df['comment_text'] = df['comment_text'].apply(lambda x: clean_contractions(x, contraction_mapping))
def detect_outliers(train_data,n,features):

 outlier_indices = []
for col in features:
Q1 = np.percentile(train_data[col], 25)
 Q3 = np.percentile(train_data[col],75)
 IQR = Q3 - Q1
outlier_step = 1.5 * IQR
outlier_list_col = train_data[(train_data[col] < Q1 - outlier_step)|(train_data[col] > Q3 + outlier_step)].index
outlier_indices.extend(outlier_list_col)
 outlier_indices = Counter(outlier_indices)
 multiple_outliers = list(k for k, v in outlier_indices.items() if v > n)
 return multiple_outliers
Outliers_to_drop = detect_outliers(train_data,2,["Age","SibSp","Parch","Fare"])
<filter>
vocab = build_vocab(df['comment_text'])
 oov = check_coverage(vocab, embeddings_index)
 oov[:10]
train_data.loc[Outliers_to_drop]<drop_column>
del(vocab,oov)
 gc.collect()
train_data = train_data.drop(Outliers_to_drop, axis = 0 ).reset_index(drop=True )<prepare_x_and_y>
def unknown_punct(embed, punct):
unknown = ''
for p in punct:
if p not in embed:
unknown += p
unknown += ' '
return unknown
y_train = train_data["Survived"]
X_train = data.drop(labels = ["Survived"],axis = 1 )<concatenate>
punct_mapping = {"_":" ", "`":" "}
test = test.select_dtypes(include=[np.number] ).interpolate().dropna()
test = test[X_train.columns] 
<normalization>
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
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
 test = sc.transform(test )<choose_model_class>
df['comment_text'] = df['comment_text'].apply(lambda x: clean_special_chars(x, punct, punct_mapping))
kfold = StratifiedKFold(n_splits=10 )<define_search_space>
vocab = build_vocab(df['comment_text'])
 oov = check_coverage(vocab, embeddings_index)
ExtC = ExtraTreesClassifier()
ex_param_grid = {"max_depth": [n for n in range(9, 14)],
"max_features": [1, 3, 10],
"min_samples_split": [n for n in range(4, 11)],
"min_samples_leaf": [n for n in range(2, 5)],
"bootstrap": [False],
"n_estimators" :[n for n in range(10, 60, 10)],
"criterion": ["gini"]}
gsExtC = GridSearchCV(ExtC,param_grid = ex_param_grid, cv=kfold, scoring="accuracy", n_jobs= 4, verbose = 1)
 gsExtC.fit(X_train,y_train)
 ExtC_best = gsExtC.best_estimator_
gsExtC.best_score_<define_search_space>
del(vocab,oov)
 gc.collect()
RFC = RandomForestClassifier()
rf_param_grid = {"max_depth": [n for n in range(9, 14)],
"max_features": [1, 3, 10],
"min_samples_split": [n for n in range(4, 11)],
"min_samples_leaf": [n for n in range(2, 5)],
"bootstrap": [False],
"n_estimators" :[n for n in range(10, 60, 10)],
"criterion": ["gini"]}
gsRFC = GridSearchCV(RFC,param_grid = rf_param_grid, cv=kfold, scoring="accuracy", n_jobs= 1, verbose = 1)
 gsRFC.fit(X_train,y_train)
 RFC_best = gsRFC.best_estimator_
gsRFC.best_score_<choose_model_class>
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 '
]
DTC = DecisionTreeClassifier()
adaDTC = AdaBoostClassifier(DTC, random_state=7)
 ada_param_grid = {"base_estimator__criterion" : ["gini", "entropy"],
"base_estimator__splitter" : ["best", "random"],
"algorithm" : ["SAMME","SAMME.R"],
"n_estimators" :[30],
"learning_rate": [0.0001, 0.001, 0.01, 0.1, 0.2, 0.3,1.5]}
gsadaDTC = GridSearchCV(adaDTC,param_grid = ada_param_grid, cv=kfold, scoring="accuracy", n_jobs= 4, verbose = 1)
 gsadaDTC.fit(X_train,y_train)
 ada_best = gsadaDTC.best_estimator_
gsadaDTC.best_score_<train_on_grid>
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
SVMC = SVC(probability=True)
 svc_param_grid = {'kernel': ['rbf'],
'gamma': [ 0.001, 0.01, 0.1, 1],
'C': [1, 10, 50, 100,200,300, 1000]}
gsSVMC = GridSearchCV(SVMC,param_grid = svc_param_grid, cv=kfold, scoring="accuracy", n_jobs= 4, verbose = 1)
 gsSVMC.fit(X_train,y_train)
 SVMC_best = gsSVMC.best_estimator_
gsSVMC.best_score_<define_search_space>
def handle_swears(text):
text = re.sub(replace_with_fuck, ' fuck ', text)
 return text
GBC = GradientBoostingClassifier()
gb_param_grid = {'loss' : ["deviance"],
'n_estimators' : [n for n in range(10, 60, 10)],
'learning_rate': [0.1, 0.05, 0.01],
'max_depth': [n for n in range(9, 14)],
'min_samples_leaf': [n for n in range(2, 5)],
'max_features': [0.3, 0.1]
}
gsGBC = GridSearchCV(GBC,param_grid = gb_param_grid, cv=kfold, scoring="accuracy", n_jobs= 4, verbose = 1)
 gsGBC.fit(X_train,y_train)
 GBC_best = gsGBC.best_estimator_
gsGBC.best_score_<train_model>
df['comment_text'] = df['comment_text'].apply(lambda x: handle_swears(x))
gc.collect()
votingC = VotingClassifier(estimators=[('rfc', RFC_best),('extc', ExtC_best),('svm',SVMC_best), 
('gbc',GBC_best)], voting='soft', n_jobs=4)
 votingC = votingC.fit(X_train, y_train)
<save_to_csv>
train = df.iloc[:1804874,:]
test = df.iloc[1804874:,:]
train.head()
test_Survived = pd.Series(votingC.predict(test), name="Survived")
 Submission = pd.concat([IDtest,test_Survived],axis=1)
 Submission.to_csv("submission.csv",index=False )<set_options>
del(df)
 gc.collect()
warnings.filterwarnings('ignore' )<load_from_csv>
train_orig = pd.read_csv(".. /input/jigsaw-unintended-bias-in-toxicity-classification/train.csv")
 train_orig.head()
train = pd.read_csv('.. /input/train.csv', index_col='Id' )<data_type_conversions>
train = pd.concat([train,train_orig[['target']]],axis=1)
 train.head()
no_features = ['Alley', 'BsmtQual', 'BsmtCond',
'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2',
'FireplaceQu', 'GarageType', 'GarageFinish',
'GarageQual', 'GarageYrBlt', 'GarageCond', 'PoolQC',
'Fence', 'MiscFeature']
train[no_features] = train[no_features].fillna('No')
 train.loc[:, "LotFrontage_NA"] = train.LotFrontage.isnull() * 1
train.loc[:, "LotFrontage_NA"] = train.loc[:, "LotFrontage_NA"].astype("object" )<feature_engineering>
del(train_orig)
 gc.collect()
def HasFeat(var):
hasf = var
hasf[hasf != 'No'] = 1
hasf[hasf == 'No'] = 0
return hasf
def feat_eng(tr):
tr.GarageQual[tr['GarageQual'] == 'No'] = 0
tr.GarageQual[tr['GarageQual'] == 'Po'] = 1
tr.GarageQual[tr['GarageQual'] == 'Fa'] = 2
tr.GarageQual[tr['GarageQual'] == 'TA'] = 3
tr.GarageQual[tr['GarageQual'] == 'Gd'] = 4
tr.GarageQual[tr['GarageQual'] == 'Ex'] = 5
tr.GarageQual = tr.GarageQual.astype('float32')
 tr.GarageCond[tr['GarageCond'] == 'No'] = 0
tr.GarageCond[tr['GarageCond'] == 'Po'] = 1
tr.GarageCond[tr['GarageCond'] == 'Fa'] = 2
tr.GarageCond[tr['GarageCond'] == 'TA'] = 3
tr.GarageCond[tr['GarageCond'] == 'Gd'] = 4
tr.GarageCond[tr['GarageCond'] == 'Ex'] = 5
tr.GarageCond = tr.GarageCond.astype('float32')
 tr.GarageYrBlt[tr['GarageYrBlt'] == 'No'] = 0
tr.GarageYrBlt = tr.GarageYrBlt.astype('float32')
 tr.Functional[tr['Functional'] == 'Typ'] = 7
tr.Functional[tr['Functional'] == 'Min1'] = 6
tr.Functional[tr['Functional'] == 'Min2'] = 5
tr.Functional[tr['Functional'] == 'Mod'] = 4
tr.Functional[tr['Functional'] == 'Maj1'] = 3
tr.Functional[tr['Functional'] == 'Maj2'] = 2
tr.Functional[tr['Functional'] == 'Sev'] = 1
tr.Functional[tr['Functional'] == 'Sal'] = 0
tr.Functional = tr.Functional.astype('float32')
 tr.Fence[tr['Fence'] == 'No'] = 0
tr.Fence[tr['Fence'] == 'MnWw'] = 1
tr.Fence[tr['Fence'] == 'GdWo'] = 2
tr.Fence[tr['Fence'] == 'MnPrv'] = 3
tr.Fence[tr['Fence'] == 'GdPrv'] = 4
tr.Fence = tr.Fence.astype('float32')
 tr.KitchenQual[tr['KitchenQual'] == 'Po'] = 1
tr.KitchenQual[tr['KitchenQual'] == 'Fa'] = 2
tr.KitchenQual[tr['KitchenQual'] == 'TA'] = 3
tr.KitchenQual[tr['KitchenQual'] == 'Gd'] = 4
tr.KitchenQual[tr['KitchenQual'] == 'Ex'] = 5
tr.KitchenQual = tr.KitchenQual.astype('float32')
 tr.HeatingQC[tr['HeatingQC'] == 'Po'] = 1
tr.HeatingQC[tr['HeatingQC'] == 'Fa'] = 2
tr.HeatingQC[tr['HeatingQC'] == 'TA'] = 3
tr.HeatingQC[tr['HeatingQC'] == 'Gd'] = 4
tr.HeatingQC[tr['HeatingQC'] == 'Ex'] = 5
tr.HeatingQC = tr.HeatingQC.astype('float32')
 tr.ExterQual[tr['ExterQual'] == 'Po'] = 1
tr.ExterQual[tr['ExterQual'] == 'Fa'] = 2
tr.ExterQual[tr['ExterQual'] == 'TA'] = 3
tr.ExterQual[tr['ExterQual'] == 'Gd'] = 4
tr.ExterQual[tr['ExterQual'] == 'Ex'] = 5
tr.ExterQual = tr.ExterQual.astype('float32')
 tr.BsmtQual[tr['BsmtQual'] == 'No'] = 0
tr.BsmtQual[tr['BsmtQual'] == 'Po'] = 1
tr.BsmtQual[tr['BsmtQual'] == 'Fa'] = 2
tr.BsmtQual[tr['BsmtQual'] == 'TA'] = 3
tr.BsmtQual[tr['BsmtQual'] == 'Gd'] = 4
tr.BsmtQual[tr['BsmtQual'] == 'Ex'] = 5
tr.BsmtQual = tr.BsmtQual.astype('float32')
 tr.BsmtFinType1[tr['BsmtFinType1'] == 'No'] = 0
tr.BsmtFinType1[tr['BsmtFinType1'] == 'Unf'] = 1
tr.BsmtFinType1[tr['BsmtFinType1'] == 'LwQ'] = 2
tr.BsmtFinType1[tr['BsmtFinType1'] == 'Rec'] = 3
tr.BsmtFinType1[tr['BsmtFinType1'] == 'BLQ'] = 4
tr.BsmtFinType1[tr['BsmtFinType1'] == 'ALQ'] = 5
tr.BsmtFinType1[tr['BsmtFinType1'] == 'GLQ'] = 6
tr.BsmtFinType1 = tr.BsmtFinType1.astype('float32')
 tr.BsmtFinType2[tr['BsmtFinType2'] == 'No'] = 0
tr.BsmtFinType2[tr['BsmtFinType2'] == 'Unf'] = 1
tr.BsmtFinType2[tr['BsmtFinType2'] == 'LwQ'] = 2
tr.BsmtFinType2[tr['BsmtFinType2'] == 'Rec'] = 3
tr.BsmtFinType2[tr['BsmtFinType2'] == 'BLQ'] = 4
tr.BsmtFinType2[tr['BsmtFinType2'] == 'ALQ'] = 5
tr.BsmtFinType2[tr['BsmtFinType2'] == 'GLQ'] = 6
tr.BsmtFinType2 = tr.BsmtFinType2.astype('float32')
 tr['TotalArea'] = tr['TotalBsmtSF'] + tr['1stFlrSF'] + tr['2ndFlrSF']
tr['BsmtFinArea'] =(tr['BsmtFinSF1'] + tr['BsmtFinSF2'])/(tr['BsmtFinSF1'] + tr['BsmtFinSF2'] + tr['BsmtUnfSF'])
 tr['MSSubClass'] = tr['MSSubClass'].astype('object')
 return tr
train = feat_eng(train )<categorify>
train['target'] = np.where(train['target'] >= 0.5, True, False )
def boxcox(a, f):
if sp.skew(a)not in range(-1,1)or sp.kurtosis(a)not in range(-1,1):
a = boxcox1p(a, 0.05)
 print(f, 'transformed.')
 return a
transformed_feats = []
for f in train.keys() :
if train[f].dtype == object:
train[f].fillna(value=train[f].value_counts().idxmax())
 train[f] = train[f].astype('category')
 else:
train[f] = train[f].fillna(value=np.mean(train[f]))
if f != 'SalePrice':
train[f] = boxcox(train[f], f)
 train[f + 'Sq'] =(train[f] ** 2)
 train[f + 'Cub'] =(train[f] ** 3)
 transformed_feats.append(f )<categorify>
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)) )
cols = train.columns
train = pd.get_dummies(train, drop_first=True )<drop_column>
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 )
all_features = train.keys()
train = train.drop(train.loc[:,(train==0 ).sum() >=1444],axis=1)
 train = train.drop(train.loc[:,(train==1 ).sum() >=1444],axis=1)
 remain_features = train.keys()
remov_features = [st for st in all_features if st not in remain_features]
print(len(remov_features), 'features were removed:', remov_features )<drop_column>
gc.collect()
X = train.drop('SalePrice', axis=1 )<train_on_grid>
EMBEDDINGS_DIMENSION = 300
embedding_matrix = np.zeros(( len(tokenizer.word_index)+ 1,EMBEDDINGS_DIMENSION))
def scorer(estimator, X, y):
y_new = estimator.predict(X)
 return np.sqrt(mt.mean_squared_error(y, y_new))
est = sk.ElasticNet(l1_ratio=0, alpha=0.017, random_state=1)
 fsel = RFECV(est, step=1, cv=15, n_jobs=-1, scoring=scorer)
 fsel = fsel.fit(X, y)
 important_feat = list(X.loc[:, fsel.ranking_<=130].columns)
 X = train.loc[:, important_feat].values
print("Most important features:", important_feat )<train_on_grid>
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
def cv_train(X, y, k):
param = {'learning_rate' : [0.1],
'n_estimators' : [600],
'max_depth' : [2]}
gbm = GradientBoostingRegressor(loss='huber', random_state=1)
 cv1 = GridSearchCV(gbm, param, cv=k, scoring='neg_mean_squared_error')
 cv1.fit(X, y)
 lasso = sk.ElasticNet(random_state=1)
 param = {'l1_ratio' : [0],
'alpha' : [0.017]}
cv2 = GridSearchCV(lasso, param, cv=k, scoring='neg_mean_squared_error')
 cv2.fit(X, y)
 print('GBM:', np.sqrt(cv1.best_score_*-1),
'Lasso:', np.sqrt(cv2.best_score_*-1),
'Mean:', np.sqrt(((cv1.best_score_+cv2.best_score_)/2)*-1),
'Pond Mean(0.8):', np.sqrt(((cv1.best_score_*0.2)+(cv2.best_score_*(0.8)))*-1))
return cv1, cv2<compute_test_metric>
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]
cv1, cv2 = cv_train(X, y, 20 )<load_from_csv>
gc.collect()
test = pd.read_csv('.. /input/test.csv')
 Id = test.loc[:, "Id"]<data_type_conversions>
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)
 x1 = Bidirectional(CuDNNLSTM(256, return_sequences=True))(x)
 x2 = Bidirectional(CuDNNGRU(128, return_sequences=True))(x1)
 max_pool1 = GlobalMaxPooling1D()(x1)
 max_pool2 = GlobalMaxPooling1D()(x2)
 x = Concatenate()([max_pool1, max_pool2])
 preds = Dense(1, activation='sigmoid' )(x)
 model = Model(sequence_input, preds)
 model.summary()
test[no_features] = test[no_features].fillna('No')
 test.loc[:, "LotFrontage_NA"] = test.LotFrontage.isnull() * 1
test.loc[:, "LotFrontage_NA"] = test.loc[:, "LotFrontage_NA"].astype("object")
 test = feat_eng(test)
 for f in test.keys() :
if test[f].dtype == object:
test[f].fillna(value=test[f].value_counts().idxmax())
 test[f] = test[f].astype('category')
 else:
test[f] = test[f].fillna(value=np.mean(test[f]))
if f in transformed_feats and f != 'SalePrice':
test[f] = boxcox(test[f], f)
 test[f + 'Sq'] =(test[f] ** 2)
 test[f + 'Cub'] =(test[f] ** 3)
 test = pd.get_dummies(test, drop_first=True)
 test = test.loc[:, important_feat]
print(test.loc[:, np.sum(test.isnull())== len(test)].columns)
 for c in list(test.loc[:, np.sum(test.isnull())== len(test)].columns):
test.loc[:, c] = 0
print("NAs:", np.sum(np.sum(test.isnull())) )<save_to_csv>
model.compile(loss='binary_crossentropy',
optimizer=Adam() ,
metrics=['acc'] )
pred =(( math.e**cv2.predict(test)) *(0.8)) +(( math.e**cv1.predict(test)) *0.2)
 sub = pd.read_csv('.. /input/sample_submission.csv')
 pd.DataFrame({"Id": Id.values, "SalePrice": pred} ).to_csv("submission.csv", index=False )<load_from_csv>
BATCH_SIZE = 1024
NUM_EPOCHS = 100
warnings.filterwarnings('ignore')
 train = pd.read_csv(".. /input/train.csv")
 train_shape = train.shape
print(train_shape )<load_from_csv>
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)])
test = pd.read_csv(".. /input/test.csv")
 test_shape = test.shape
print(test_shape )<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()
def process_age(df, cut_points, label_names):
df["Age"] = df["Age"].fillna(-0.5)
 df["Age_categories"] = pd.cut(df["Age"], cut_points, labels=label_names)
 return df
cut_points = [-1, 0, 5, 12, 18, 35, 60, 100]
label_names = ["Missing", "Infant", "Child", "Teenager", "Young Adult", "Adult", "Senior"]
train = process_age(train, cut_points, label_names)
 test = process_age(test, cut_points, label_names )<count_values>
submission.to_csv('submission.csv', index=False )