kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
13,563,857
import pandas as pd import numpy as np import re from sklearn.model_selection import train_test_split from sklearn.metrics import f1_score import torch from torch import nn from torch import optim import torch.nn.functional as F from torch.utils.data import TensorDataset, DataLoader import spacy from gensim.models impo...
df = pd.read_csv("/kaggle/input/titanic/train.csv", index_col="PassengerId") rows, cols = df.shape print(f"Original DataFrame has {rows} rows and {cols} columns") df.head()
Titanic - Machine Learning from Disaster
13,563,857
train_df = pd.read_csv(".. /input/train.csv") test_df = pd.read_csv(".. /input/test.csv") labels = np.array(train_df.target, dtype=int )<string_transform>
label_encoder = LabelEncoder() df["Sex"] = label_encoder.fit_transform(df["Sex"]) df["Family_Size"] = df["SibSp"] + df["Parch"] + 1 df["Fare_Per_Person"] = df["Fare"] / df["Family_Size"] df.tail()
Titanic - Machine Learning from Disaster
13,563,857
def n_upper(sentence): return len(re.findall(r'[A-Z]',sentence)) def n_unique_words(sentence): return len(set(sentence.split())) def n_question_mark(sentence): return len(re.findall(r'[?]',sentence)) def n_exclamation_mark(sentence): return len(re.findall(r'[!]',sentence)) def n_asterisk(sentence): return len(re.findal...
set1 = df.copy() set1 = set1[["Survived", "Pclass", "Sex", "Age", "SibSp", "Parch", "Fare"]] set1.dropna(axis=0, inplace=True) rows, cols = set1.shape print(f"set1 DataFrame has {rows} rows and {cols} columns") set1.tail()
Titanic - Machine Learning from Disaster
13,563,857
train_stat = get_stat(train_df.question_text) test_stat = get_stat(test_df.question_text )<string_transform>
y = set1["Age"] X = set1[["Survived", "Pclass", "Sex", "SibSp", "Parch", "Fare"]]
Titanic - Machine Learning from Disaster
13,563,857
train_list = list(train_df.question_text.apply(lambda s: s.lower())) test_list = list(test_df.question_text.apply(lambda s: s.lower())) train_text = ' '.join(train_list) test_text = ' '.join(test_list )<load_pretrained>
train_X, val_X, train_y, val_y = train_test_split(X, y, train_size=0.8, test_size=0.2, random_state=0) print(f"Training features shape: {train_X.shape}") print(f"Training labels shape: {train_y.shape}") print(f"Testing features shape: {val_X.shape}") print(f"Testing labels shape: {val_y.shape}" )
Titanic - Machine Learning from Disaster
13,563,857
nlp = spacy.load("en", disable=['tagger','parser','ner','textcat'] )<feature_engineering>
def get_mae1(max_leaf_nodes, train_X, val_X, train_y, val_y): age_model = DecisionTreeRegressor(max_leaf_nodes=max_leaf_nodes, random_state=0) age_model.fit(train_X, train_y) val_predictions = age_model.predict(val_X) return mean_absolute_error(val_y, val_predictions) for max_leaf_nodes in [5, 10, 15, 20, 50, 100]:...
Titanic - Machine Learning from Disaster
13,563,857
vocab = {} lemma_vocab = {} word_idx = 1 train_tokens = [] for doc in tqdm(nlp.pipe(train_list)) : curr_tokens = [] for token in doc: if token.text not in vocab: vocab[token.text] = word_idx lemma_vocab[token.text] = token.lemma_ word_idx += 1 curr_tokens.append(vocab[token.text]) train_tokens.append(np.array(curr_tok...
age_model = DecisionTreeRegressor(max_leaf_nodes=10, random_state=0) age_model.fit(X, y )
Titanic - Machine Learning from Disaster
13,563,857
def pad(questions, seq_length): features = np.zeros(( len(questions), seq_length+1), dtype=int) for i, sentence in enumerate(questions): if len(sentence)==0: continue features[i, 0] = len(sentence) features[i, -len(sentence):] = sentence return features<define_variables>
set2 = df.copy() columns = ["Survived", "Pclass", "Sex", "Age", "SibSp", "Parch", "Fare"] set2 = set2.loc[set2["Age"].isnull() , columns] rows, cols = set2.shape print(f"set2 DataFrame has {rows} rows and {cols} columns") set2.tail()
Titanic - Machine Learning from Disaster
13,563,857
seq_length = max(max(map(len, train_tokens)) , max(map(len, test_tokens)) )<categorify>
X = set2[["Survived", "Pclass", "Sex", "SibSp", "Parch", "Fare"]] set2["Age"] = age_model.predict(X) set2.head()
Titanic - Machine Learning from Disaster
13,563,857
train_tokens = pad(train_tokens, seq_length) test_tokens = pad(test_tokens, seq_length )<categorify>
set1 = set1.append(set2) rows, cols = set1.shape print(f"set1 DataFrame has {rows} rows and {cols} columns") set1.head()
Titanic - Machine Learning from Disaster
13,563,857
def get_embeddings(file): embeddings = {} with open(file, encoding="utf8", errors='ignore')as f: for line in tqdm(f): line_list = line.split(" ") if len(line_list)> 100: embeddings[line_list[0]] = np.array(line_list[1:], dtype='float32') return embeddings def get_embeddings_matrix(vocab, lemma_vocab, embeddings, keye...
y = set1["Survived"] X = set1[["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare"]]
Titanic - Machine Learning from Disaster
13,563,857
glove_file = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt' glove_emb = get_embeddings(glove_file) glove_emb_matrix = get_embeddings_matrix(vocab, lemma_vocab, glove_emb) del glove_emb gc.collect()<load_pretrained>
train_X, val_X, train_y, val_y = train_test_split(X, y, train_size=0.8, test_size=0.2, random_state=0) print(f"Training features shape: {train_X.shape}") print(f"Training labels shape: {train_y.shape}") print(f"Testing features shape: {val_X.shape}") print(f"Testing labels shape: {val_y.shape}" )
Titanic - Machine Learning from Disaster
13,563,857
fasttext_file = '.. /input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec' fasttext_emb = get_embeddings(fasttext_file) fasttext_emb_matrix = get_embeddings_matrix(vocab, lemma_vocab, fasttext_emb) del fasttext_emb gc.collect() <load_pretrained>
def get_mae2(max_leaf_nodes, train_X, val_X, train_y, val_y): survival_model = RandomForestClassifier(max_leaf_nodes=max_leaf_nodes, random_state=0) survival_model.fit(train_X, train_y) val_predictions = survival_model.predict(val_X) return mean_absolute_error(val_y, val_predictions) for max_leaf_nodes in [5, 8, 10...
Titanic - Machine Learning from Disaster
13,563,857
word2vec_file = '.. /input/embeddings/GoogleNews-vectors-negative300/GoogleNews-vectors-negative300.bin' word2vec_emb = KeyedVectors.load_word2vec_format(word2vec_file, binary=True) word2vec_emb_matrix = get_embeddings_matrix(vocab, lemma_vocab, word2vec_emb, keyedVector=True) del word2vec_emb gc.collect()<load_pretr...
survival_model = RandomForestClassifier(max_leaf_nodes=15, random_state=0) accuracy = survival_model.fit(X, y ).score(X, y) print(f"Accuracy value: {accuracy}" )
Titanic - Machine Learning from Disaster
13,563,857
paragram_file = '.. /input/embeddings/paragram_300_sl999/paragram_300_sl999.txt' paragram_emb = get_embeddings(paragram_file) paragram_emb_matrix = get_embeddings_matrix(vocab, lemma_vocab, paragram_emb) del paragram_emb gc.collect()<concatenate>
tdf = pd.read_csv("/kaggle/input/titanic/test.csv", index_col="PassengerId") rows, cols = tdf.shape print(f"Original Test DataFrame has {rows} rows and {cols} columns") tdf.head()
Titanic - Machine Learning from Disaster
13,563,857
emb_matrix = np.concatenate(( glove_emb_matrix, paragram_emb_matrix), axis=1) del glove_emb_matrix, fasttext_emb_matrix, word2vec_emb_matrix, paragram_emb_matrix gc.collect()<concatenate>
label_encoder = LabelEncoder() tdf["Sex"] = label_encoder.fit_transform(tdf["Sex"]) tdf["Family_Size"] = tdf["SibSp"] + tdf["Parch"] + 1 tdf["Fare_Per_Person"] = tdf["Fare"] / tdf["Family_Size"] tdf.tail()
Titanic - Machine Learning from Disaster
13,563,857
train_feat = np.concatenate(( train_stat, train_tokens), axis=1) test_feat = np.concatenate(( test_stat, test_tokens), axis=1 )<split>
tdf[tdf["Fare"].isnull() ]
Titanic - Machine Learning from Disaster
13,563,857
x_train, x_val, label_train, label_val = train_test_split(train_feat, labels, test_size=0.1, random_state=0) train_data = TensorDataset(torch.from_numpy(x_train), torch.from_numpy(label_train)) valid_data = TensorDataset(torch.from_numpy(x_val), torch.from_numpy(label_val)) test_data = TensorDataset(torch.from_numpy(t...
test_set1 = tdf.copy() filtr =(~test_set1["Fare"].isnull())&(~test_set1["Age"].isnull())&(test_set1["Pclass"] == 3) test_set1 = test_set1[filtr] rows, cols = test_set1.shape print(f"test_set1 DataFrame has {rows} rows and {cols} columns") test_set1.head()
Titanic - Machine Learning from Disaster
13,563,857
train_on_gpu=torch.cuda.is_available() if train_on_gpu: print('Training on GPU.') else: print('No GPU available, training on CPU.' )<choose_model_class>
y = test_set1["Fare"] X = test_set1[["Pclass", "Sex", "Age", "SibSp", "Parch"]] fare_model = DecisionTreeRegressor(random_state=1) r_squared = fare_model.fit(X, y ).score(X, y) print(f"R-Squared value: {r_squared}" )
Titanic - Machine Learning from Disaster
13,563,857
def init_emb_layer(self, embedding_matrix): embedding_matrix = torch.tensor(embedding_matrix, dtype=torch.float32) num_emb, emb_size = embedding_matrix.size() emb_layer = nn.Embedding.from_pretrained(embedding_matrix) return emb_layer class SelfAttention(nn.Module): def __init__(self, attention_size, batch_first=...
tdf.loc[1044, ["Fare"]] = fare_model.predict([[3, 1, 60.5, 0, 0]]) tdf.loc[1044, ["Fare_Per_Person"]] = fare_model.predict([[3, 1, 60.5, 0, 0]]) tdf.loc[1044]
Titanic - Machine Learning from Disaster
13,563,857
hidden_dim = 256 gru_layers = 1 dropout = 0.1 stat_layers_dim = [16, 8] hidden_layer_dim = 64 model = Quora_model(hidden_layer_dim, emb_matrix, hidden_dim, gru_layers, stat_layers_dim, dropout) model<choose_model_class>
test_set1 = tdf.copy() test_set1 = test_set1.loc[~tdf["Age"].isnull() ] rows, cols = test_set1.shape print(f"test_set1 DataFrame has {rows} rows and {cols} columns") test_set1.head()
Titanic - Machine Learning from Disaster
13,563,857
epochs = 4 print_every = 1000 early_stop = 20 clip = 5 lr=0.001 criterion = nn.BCELoss() optimizer = torch.optim.Adam(model.parameters() , lr=lr )<train_model>
y = test_set1["Age"] X = test_set1[["Pclass", "Sex", "SibSp", "Parch", "Fare"]]
Titanic - Machine Learning from Disaster
13,563,857
def train_model(model, train_loader, valid_loader, batch_size, epochs, optimizer, criterion, clip, print_every, early_stop): if(train_on_gpu): model.cuda() counter = 0 model.train() breaker = False for e in range(epochs): for inputs, labels in train_loader: counter += 1 if(train_on_gpu): inputs, labels = inputs.cuda() ...
train_X, val_X, train_y, val_y = train_test_split(X, y, train_size=0.8, test_size=0.2, random_state=0) print(f"Training features shape: {train_X.shape}") print(f"Training labels shape: {train_y.shape}") print(f"Testing features shape: {val_X.shape}") print(f"Testing labels shape: {val_y.shape}" )
Titanic - Machine Learning from Disaster
13,563,857
t0 = time.time() all_val_probs, all_val_labels = train_model(model, train_loader, valid_loader, batch_size, epochs, optimizer, criterion, clip, print_every, early_stop) tf = time.time() print(" Execution time: {:.2f}min".format(( tf-t0)/60))<find_best_params>
def get_mae3(max_leaf_nodes, train_X, val_X, train_y, val_y): age_model = DecisionTreeRegressor(max_leaf_nodes=max_leaf_nodes, random_state=0) age_model.fit(train_X, train_y) val_predictions = age_model.predict(val_X) return mean_absolute_error(val_y, val_predictions) for max_leaf_nodes in [5, 10, 15, 20, 50, 100]:...
Titanic - Machine Learning from Disaster
13,563,857
best_score = 0 for thr in np.arange(0.0, 0.5, 0.005): pred = np.array(all_val_probs > thr, dtype=int) score = f1_score(all_val_labels, pred) print("Threshold: {:.3f}...F1-score {:.3%}".format(thr, score)) if score > best_score: best_score = score best_thr = thr print(" Best threshold: {:.3f}...F1-score {:.3%}".format...
age_model = DecisionTreeRegressor(random_state=1) age_model.fit(X, y )
Titanic - Machine Learning from Disaster
13,563,857
model.eval() with torch.no_grad() : all_test_preds = [] for inputs in test_loader: inputs = inputs[0] if(train_on_gpu): inputs = inputs.cuda() test_h = model.init_hidden(batch_size) output = model(inputs, test_h) preds =(output.squeeze() > best_thr ).type(torch.IntTensor) preds = np.squeeze(preds.cpu().numpy()) all...
test_set2 = tdf.copy() test_set2 = test_set2.loc[tdf["Age"].isnull() ] rows, cols = test_set2.shape print(f"test_set2 DataFrame has {rows} rows and {cols} columns") test_set2.head()
Titanic - Machine Learning from Disaster
13,563,857
sub = pd.DataFrame({ 'qid': test_df.qid, 'prediction': all_test_preds }) sub = sub[['qid', 'prediction']] sub.to_csv('submission.csv', index=False, sep=',' )<import_modules>
X = test_set2[["Pclass", "Sex", "SibSp", "Parch", "Fare"]] test_set2["Age"] = age_model.predict(X) test_set2.head()
Titanic - Machine Learning from Disaster
13,563,857
tqdm.pandas() gc.collect()<define_variables>
test_set1 = test_set1.append(test_set2) rows, cols = test_set1.shape print(f"test_set1 DataFrame has {rows} rows and {cols} columns") test_set1.head()
Titanic - Machine Learning from Disaster
13,563,857
max_features= 200000 max_senten_len = 40 max_senten_num = 3 embed_size = 300 VALIDATION_SPLIT = 0<import_modules>
X = test_set1[["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare"]] predictions = survival_model.predict(X) output = pd.DataFrame({"PassengerId": test_set1.index, "Survived": predictions}) output.to_csv("my_submission.csv", index=False) print("my_submission.csv is ready to submit!" )
Titanic - Machine Learning from Disaster
14,160,111
from sklearn.utils import shuffle<load_from_csv>
data=pd.read_csv('.. /input/titanic/train.csv') data
Titanic - Machine Learning from Disaster
14,160,111
df = pd.read_csv('.. /input/train.csv' )<load_from_csv>
data['Ticket_type']=data['Ticket'].apply(lambda x: x[0:3]) data['Ticket_type']=data['Ticket_type'].astype('category' ).cat.codes
Titanic - Machine Learning from Disaster
14,160,111
test_df = pd.read_csv(".. /input/test.csv" )<count_unique_values>
data['Words_counts']=data['Name'].apply(lambda x: len(x.split()))
Titanic - Machine Learning from Disaster
14,160,111
len(df.target.unique() )<rename_columns>
data['cabin_or_not']=data["Cabin"].apply(lambda x: 0 if type(x)== float else 1) data.head(3 )
Titanic - Machine Learning from Disaster
14,160,111
df.columns = ['qid', 'text', 'category'] test_df.columns = ['qid', 'text']<drop_column>
data['Family_size']=data['SibSp'] + data['Parch'] + 1
Titanic - Machine Learning from Disaster
14,160,111
df = df[['text', 'category']]<feature_engineering>
data['IsAlone'] = 0 data.loc[data['Family_size'] == 1, 'IsAlone'] = 1 data.head(3 )
Titanic - Machine Learning from Disaster
14,160,111
df['text'] = df['text'].str.lower() test_df['text'] = test_df['text'].str.lower()<define_variables>
data['Embarked'] = data['Embarked'].fillna('S') data['Age'].fillna(data['Age'].mean() ,inplace=True )
Titanic - Machine Learning from Disaster
14,160,111
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", ...
data['fare_cat']=pd.qcut(data['Fare'], 4) data['fare_cat']=data['fare_cat'].astype('category' ).cat.codes.astype('int' )
Titanic - Machine Learning from Disaster
14,160,111
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<feature_engineering>
data['cat_age']=pd.cut(data['Age'],5) print(data['cat_age'].value_counts()) data['cat_age']=data['cat_age'].astype('category' ).cat.codes.astype('int' )
Titanic - Machine Learning from Disaster
14,160,111
df['text'] = df['text'].progress_apply(lambda x: clean_contractions(x, contraction_mapping)) test_df['text'] = test_df['text'].progress_apply(lambda x: clean_contractions(x, contraction_mapping))<define_variables>
title=title.replace(['Lady', 'Countess','Capt', 'Col','Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'],'Rare') title=title.replace('Mlle','Miss') title=title.replace('Ms','Miss') title=title.replace('Mme','Mrs') title.value_counts()
Titanic - Machine Learning from Disaster
14,160,111
punct = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', ' '·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…', '“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾',...
data['Title']=title dic1= {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Rare": 5} data['Title'] = data['Title'].map(dic1) data['Title'] =data['Title'].fillna(0 )
Titanic - Machine Learning from Disaster
14,160,111
punct_mapping = {"‘": "'", "₹": "e", "´": "'", "°": "", "€": "e", "™": "tm", "√": " sqrt ", "×": "x", "²": "2", "—": "-", "–": "-", "’": "'", "_": "-", "`": "'", '“': '"', '”': '"', '“': '"', "£": "e", '∞': 'infinity', 'θ': 'theta', '÷': '/', 'α': 'alpha', '•': '.', 'à': 'a', '−': '-', 'β': 'beta', '∅': '', '³': '3', '...
data['Sex'] = data['Sex'].map({'female': 0, 'male': 1} ).astype(int) data.head(3 )
Titanic - Machine Learning from Disaster
14,160,111
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} ') specials = {'\u200b': ' ', '…': '...', '\ufeff': '', 'करना': '', 'है': ''} for s in specials: text = text.replace(s, specials[s]) return text<feature_engineering>
data['Embarked'] = data['Embarked'].map({'S': 0, 'C': 1, 'Q': 2} ).astype(int )
Titanic - Machine Learning from Disaster
14,160,111
df['text'] = df['text'].progress_apply(lambda x: clean_special_chars(x, punct, punct_mapping)) test_df['text'] = test_df['text'].progress_apply(lambda x: clean_special_chars(x, punct, punct_mapping))<define_variables>
data.drop(columns=['PassengerId','Name','Ticket','Cabin'],inplace=True )
Titanic - Machine Learning from Disaster
14,160,111
mispell_dict = {'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'...
train=pd.read_csv('.. /input/titanic/train.csv') test=pd.read_csv('.. /input/titanic/test.csv' )
Titanic - Machine Learning from Disaster
14,160,111
def correct_spelling(x, dic): for word in dic.keys() : x = x.replace(word, dic[word]) return x<feature_engineering>
test['Fare'].fillna(test['Fare'].mean() ,inplace=True )
Titanic - Machine Learning from Disaster
14,160,111
df['text'] = df['text'].progress_apply(lambda x: correct_spelling(x, mispell_dict)) test_df['text'] = test_df['text'].progress_apply(lambda x: correct_spelling(x, mispell_dict))<define_variables>
datas=[train,test] for data in datas: data['Ticket_type']=data['Ticket'].apply(lambda x: x[0:3]) data['Ticket_type']=data['Ticket_type'].astype('category' ).cat.codes data['Words_counts']=data['Name'].apply(lambda x: len(x.split())) data['cabin_or_not']=data["Cabin"].apply(lambda x: 0 if type(x)== float else 1) data[...
Titanic - Machine Learning from Disaster
14,160,111
labels = df['category'] text = df['text']<prepare_x_and_y>
x=train.drop(columns=['Survived']) y=train['Survived']
Titanic - Machine Learning from Disaster
14,160,111
train_text = text.reset_index().drop('index', axis=1) y_train = labels.reset_index().drop('index', axis=1) val_text = None y_val = None<drop_column>
log_model = LogisticRegression(C=22 ).fit(x, y )
Titanic - Machine Learning from Disaster
14,160,111
test = test_df['text']<groupby>
submitssion_dis={'PassengerId':[a for a in range(892,1310)] ,'Survived':log_model.predict(test)}
Titanic - Machine Learning from Disaster
14,160,111
cates = df.groupby('category') print("total categories:", cates.ngroups) print(cates.size() )<define_variables>
submission=pd.DataFrame(submitssion_dis) submission.to_csv('Submission_out.csv',index=False )
Titanic - Machine Learning from Disaster
14,123,238
paras = [] labels = [] texts = []<string_transform>
train=pd.read_csv('/kaggle/input/titanic/train.csv') test=pd.read_csv('/kaggle/input/titanic/test.csv') train.head()
Titanic - Machine Learning from Disaster
14,123,238
sent_lens = [] sent_nums = [] for idx in tqdm(range(train_text.shape[0])) : text = train_text.text[idx] texts.append(text) sentences = tokenize.sent_tokenize(text) sent_nums.append(len(sentences)) for sent in sentences: sent_lens.append(len(text_to_word_sequence(sent))) paras.append(sentences )<define_variables>
df = train.copy()
Titanic - Machine Learning from Disaster
14,123,238
val_paras = [] val_labels = []<define_variables>
testo =test.copy()
Titanic - Machine Learning from Disaster
14,123,238
test_paras = [] test_labels = []<string_transform>
df.drop(columns=['Name', 'Ticket', 'Cabin'], axis=1, inplace=True) test.drop(columns=['Name', 'Ticket', 'Cabin'], axis=1, inplace=True )
Titanic - Machine Learning from Disaster
14,123,238
for idx in range(test.shape[0]): text = test[idx] sentences = tokenize.sent_tokenize(text) test_paras.append(sentences )<feature_engineering>
df.isnull().sum()
Titanic - Machine Learning from Disaster
14,123,238
tokenizer = Tokenizer(num_words=max_features, oov_token=True) tokenizer.fit_on_texts(texts )<feature_engineering>
df['Age'].fillna(df['Age'].median() , inplace=True) df['Embarked'].fillna(df['Embarked'].mode() [0], inplace=True)
Titanic - Machine Learning from Disaster
14,123,238
x_train = np.zeros(( len(texts), max_senten_num, max_senten_len), dtype='int32') for i, sentences in tqdm(enumerate(paras)) : tokenized_sent = tokenizer.texts_to_sequences(sentences) padded_seq = pad_sequences(tokenized_sent, maxlen=max_senten_len, padding='post', truncating='post') for j, seq in enumerate(padded_se...
df.isnull().sum()
Titanic - Machine Learning from Disaster
14,123,238
<categorify>
df[df.Fare.isnull() ]
Titanic - Machine Learning from Disaster
14,123,238
test_data = np.zeros(( test.shape[0], max_senten_num, max_senten_len), dtype='int32') for i, sentences in enumerate(test_paras): tokenized_sent = tokenizer.texts_to_sequences(sentences) padded_seq = pad_sequences(tokenized_sent, maxlen=max_senten_len, padding='post', truncating='post') for j, seq in enumerate(padded...
df.isnull().sum()
Titanic - Machine Learning from Disaster
14,123,238
word_index = tokenizer.word_index print('Total %s unique tokens.' % len(word_index))<import_modules>
test.isnull().sum()
Titanic - Machine Learning from Disaster
14,123,238
import os<statistical_test>
test.isnull().sum()
Titanic - Machine Learning from Disaster
14,123,238
gc.collect() word_index = tokenizer.word_index max_features = len(word_index)+1 def load_glove(word_index): EMBEDDING_FILE = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt' def get_coefs(word,*arr): return word.lower() , np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o...
print('Duplicated data =',df.duplicated().sum() )
Titanic - Machine Learning from Disaster
14,123,238
embedding_matrix_1 = load_glove(word_index) embedding_matrix_3 = load_para(word_index) embedding_matrix = np.mean(( embedding_matrix_1, embedding_matrix_3), axis=0) del embedding_matrix_1, embedding_matrix_3 gc.collect() np.shape(embedding_matrix )<train_model>
df[['Pclass','Survived']].groupby(['Pclass'],as_index = False ).mean().sort_values(by = 'Survived', ascending = False )
Titanic - Machine Learning from Disaster
14,123,238
class CyclicLR(Callback): def __init__(self, base_lr=0.001, max_lr=0.006, step_size=2000., mode='triangular', gamma=1., scale_fn=None, scale_mode='cycle'): super(CyclicLR, self ).__init__() self.base_lr = base_lr self.max_lr = max_lr self.step_size = step_size self.mode = mode self.gamma = gamma if scale_fn == None: ...
df[['Sex','Survived']].groupby(['Sex'],as_index = False ).mean()
Titanic - Machine Learning from Disaster
14,123,238
def han_model(embedding_matrix): nb_words = embedding_matrix.shape[0] embedding_layer = Embedding(nb_words, embed_size, weights=[embedding_matrix]) word_input = Input(shape=(max_senten_len,), dtype='float32') word_sequences = embedding_layer(word_input) word_lstm = Bidirectional(CuDNNLSTM(64, return_sequences=True))...
df[['SibSp','Survived']].groupby(['SibSp'] ).mean()
Titanic - Machine Learning from Disaster
14,123,238
def train_pred(model, train_X, train_y, val_X, val_y, epochs=2, callback=None, batch_size=512): print(train_X.dtype, train_y.dtype) h = model.fit(train_X, train_y, batch_size=batch_size, epochs=epochs, validation_data=(val_X, val_y), callbacks = callback, verbose=1) model.load_weights(filepath) pred_val_y = model.pr...
df[['Parch','Survived']].groupby(['Parch'] ).mean()
Titanic - Machine Learning from Disaster
14,123,238
from sklearn.model_selection import GridSearchCV, StratifiedKFold<compute_test_metric>
LabelEncoder = preprocessing.LabelEncoder() df['Embarked'] = LabelEncoder.fit_transform(df['Embarked']) test['Embarked'] = LabelEncoder.transform(test['Embarked']) df['Sex'] = LabelEncoder.fit_transform(df['Sex']) test['Sex'] = LabelEncoder.fit_transform(test['Sex']) y = df['Survived'] X = df.drop(['Survived'],axis...
Titanic - Machine Learning from Disaster
14,123,238
search_result = threshold_search(y_train, train_meta )<save_to_csv>
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25 )
Titanic - Machine Learning from Disaster
14,123,238
pred_test_y =(test_meta>search_result['threshold'] ).astype(int) out_df = pd.DataFrame({"qid":test_df["qid"].values}) out_df['prediction'] = pred_test_y out_df.to_csv("submission.csv", index=False )<set_options>
scaler = MinMaxScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) test = scaler.fit_transform(test )
Titanic - Machine Learning from Disaster
14,123,238
gc.collect()<import_modules>
def perform_model(model, X_train, y_train, X_test, y_test, class_labels, cm_normalize=True, \ print_cm=True, cm_cmap=plt.cm.Greens): results = dict() train_start_time = datetime.now() print('training the model.. ') model.fit(X_train, y_train) print('Done ') train_end_time = datetime.now() results['training_time'] = ...
Titanic - Machine Learning from Disaster
14,123,238
import os import random import re import time from collections import Counter from itertools import chain import numpy as np import pandas as pd import torch import torch.nn as nn from sklearn.metrics import f1_score, roc_auc_score from sklearn.model_selection import StratifiedKFold, KFold from sklearn.utils import shu...
def print_grid_search_attributes(model): print('--------------------------') print('| Best Estimator |') print('--------------------------') print(' \t{} '.format(model.best_estimator_)) print('--------------------------') print('| Best parameters |') print('--------------------------') print('\tParameters of bes...
Titanic - Machine Learning from Disaster
14,123,238
embedding_glove = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt' embedding_fasttext = '.. /input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec' embedding_para = '.. /input/embeddings/paragram_300_sl999/paragram_300_sl999.txt' embedding_w2v = '.. /input/embeddings/GoogleNews-vectors-negative300/GoogleNe...
labels = ['0','1']
Titanic - Machine Learning from Disaster
14,123,238
def set_seed(seed): np.random.seed(seed) torch.manual_seed(seed + 1) if torch.cuda.is_available() : torch.cuda.manual_seed_all(seed + 2) random.seed(seed + 4) <string_transform>
parameters = {"C":np.logspace(-3,3,7), "penalty":["l1","l2"]} logreg=LogisticRegression() lr_grid = GridSearchCV(logreg,param_grid=parameters, n_jobs=-1) lr_grid_results = perform_model(lr_grid, X_train, y_train, X_test, y_test, class_labels=labels) print_grid_search_attributes(lr_grid_results['model'] )
Titanic - Machine Learning from Disaster
14,123,238
def clean_text(text): text = p.sub(' [ math ] ', text) text = p_space.sub(r'', text) for punct in punct_mapping: if punct in text: text = text.replace(punct, punct_mapping[punct]) tokens = [] for token in text.split() : token = mispell_dict.get(token.lower() , token) tokens.append(token) text = ' '.join(tokens) r...
parameters = {'max_depth':np.arange(3,10,2)} dt = DecisionTreeClassifier() dt_grid = GridSearchCV(dt,param_grid=parameters, n_jobs=-1) dt_grid_results = perform_model(dt_grid, X_train, y_train, X_test, y_test, class_labels=labels) print_grid_search_attributes(dt_grid_results['model'] )
Titanic - Machine Learning from Disaster
14,123,238
def build_counter(sents, splited=False): counter = Counter() for sent in tqdm(sents, ascii=True, desc='building conuter'): if splited: counter.update(sent) else: counter.update(sent.split()) return counter def build_vocab(counter, max_vocab_size): vocab = {'token2id': {'<PAD>': 0, '<UNK>': max_vocab_size + 1}} vocab[...
n_estimators = [10, 100, 500, 1000, 2000] max_depth = [5, 10, 20] parameters = dict(n_estimators=n_estimators, max_depth=max_depth) rf = RandomForestClassifier(random_state=42) rf_grid = GridSearchCV(rf,param_grid=parameters, n_jobs=-1) rf_grid_results = perform_model(rf_grid, X_train, y_train, X_test, y_test, class...
Titanic - Machine Learning from Disaster
14,123,238
def _pad_sequences(seqs): lens = [len(seq)for seq in seqs] max_len = max(lens) padded_seqs = torch.zeros(len(seqs), max_len ).long() for i, seq in enumerate(seqs): end = lens[i] padded_seqs[i, :end] = torch.LongTensor(seq) return padded_seqs, lens def collate_fn(data): qids, src_sents, src_seqs, targets, = zip(*data)...
model_rf_final = RandomForestClassifier(max_depth= 5, n_estimators= 500) model_rf_final.fit(X_train, y_train )
Titanic - Machine Learning from Disaster
14,123,238
def read_embedding(embedding_file): if os.path.basename(embedding_file)!= 'wiki-news-300d-1M.vec': skip_head = None else: skip_head = 0 if os.path.basename(embedding_file)== 'paragram_300_sl999.txt': encoding = 'latin' else: encoding = 'utf-8' embeddings_index = {} t_chunks = pd.read_csv(embedding_file, index_col=0, ...
test_pred = pd.Series(model_rf_final.predict(test), name = "Survived") test_pred_final = pd.DataFrame(test_pred )
Titanic - Machine Learning from Disaster
14,123,238
def set_lr(optimizer, lr): for g in optimizer.param_groups: g['lr'] = lr class CyclicLR: def __init__(self, optimizer, base_lr=0.001, max_lr=0.002, step_size=300., mode='triangular', gamma=0.99994, scale_fn=None, scale_mode='cycle'): super(CyclicLR, self ).__init__() self.optimizer = optimizer self.base_lr = base_lr se...
df_gender_submission = pd.read_csv('.. /input/titanic/gender_submission.csv')
Titanic - Machine Learning from Disaster
14,123,238
class Capsule(nn.Module): def __init__(self, input_dim_capsule=1024, num_capsule=5, dim_capsule=5, routings=4): super(Capsule, self ).__init__() self.num_capsule = num_capsule self.dim_capsule = dim_capsule self.routings = routings self.activation = self.squash self.W = nn.Parameter( nn.init.xavier_normal_(torch.empty...
submission = pd.DataFrame({ "PassengerId": testo["PassengerId"], "Survived": test_pred_final['Survived'] }) submission.to_csv('Titanic Submission.csv', index = False) print('Done' )
Titanic - Machine Learning from Disaster
14,129,375
def eval_model(model, data_iter, device, order_index=None): model.eval() predictions = [] with torch.no_grad() : for batch_data in data_iter: qid_batch, src_sents, src_seqs, src_lens, tgts = batch_data src_seqs = src_seqs.to(device) out = model(src_seqs, src_lens, return_logits=False) predictions.append(out) predict...
train_data = pd.read_csv("/kaggle/input/titanic/train.csv") train_data.head()
Titanic - Machine Learning from Disaster
14,129,375
def cv(train_df, test_df, device=None, n_folds=10, shared_resources=None, share=True, **kwargs): if device is None: device = torch.device("cuda:{}".format(0)if torch.cuda.is_available() else "cpu") max_vocab_size = kwargs['max_vocab_size'] embed_size = kwargs['embed_size'] threshold = kwargs['threshold'] max_seq_len =...
test_data = pd.read_csv("/kaggle/input/titanic/test.csv") test_data.head() print(test_data.isnull().sum() )
Titanic - Machine Learning from Disaster
14,129,375
def main(train_df, valid_df, test_df, device=None, epochs=3, fine_tuning_epochs=3, batch_size=512, learning_rate=0.001, learning_rate_max_offset=0.001, dropout=0.1, threshold=None, max_vocab_size=95000, embed_size=300, max_seq_len=70, print_every_step=500, idx=0, shared_resources=None, return_reduced=True): if device i...
y = train_data["Survived"] features = ["Pclass", "Sex", "SibSp", "Parch", "Fare", "Age"] X = pd.get_dummies(train_data[features]) X_unknown = pd.get_dummies(test_data[features]) my_imputer = SimpleImputer() X = my_imputer.fit_transform(X) X_unknown = my_imputer.fit_transform(X_unknown) X_train, X_test, y_train, y_t...
Titanic - Machine Learning from Disaster
14,129,375
set_seed(233) epochs = 8 batch_size = 512 learning_rate = 0.001 learning_rate_max_offset = 0.002 fine_tuning_epochs = 2 threshold = 0.31 max_vocab_size = 120000 embed_size = 300 print_every_step = 500 max_seq_len = 70 share = True dropout = 0.1 sub = pd.read_csv('.. /input/sample_submission.csv') train_df, test_df = ...
optimal_alpha = 1 optimal_accuracy = 0 for i in range(20): model = MLPClassifier(hidden_layer_sizes = [50, 50], alpha = 0.1*(i+1), activation='relu', solver='adam', random_state=1 ).fit(X_train, y_train) model_accuracy = model.score(X_test, y_test) if model_accuracy > optimal_accuracy: optimal_accuracy = model_accura...
Titanic - Machine Learning from Disaster
14,129,375
embed_size = 600 max_features = None maxlen = 57<import_modules>
optimal_estimators = 1 optimal_accuracy = 0 for i in range(20): model = RandomForestClassifier(n_estimators=(i+1)*10, max_depth=5, random_state=1 ).fit(X_train, y_train) model_accuracy = model.score(X_test, y_test) if model_accuracy > optimal_accuracy: optimal_accuracy = model_accuracy optimal_estimators =(i+1)*10 pr...
Titanic - Machine Learning from Disaster
14,129,375
import os import time import numpy as np import pandas as pd from tqdm import tqdm import math from sklearn.model_selection import train_test_split from sklearn import metrics from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.layers import Dense, Input, CuD...
model = RandomForestClassifier(n_estimators=110, max_depth=5, random_state=1 ).fit(X, y) predictions = model.predict(X_unknown) output = pd.DataFrame({'PassengerId': test_data.PassengerId, 'Survived': predictions}) output.to_csv('my_submission.csv', index=False )
Titanic - Machine Learning from Disaster
14,110,105
puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', ' '·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…', '“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾'...
warnings.filterwarnings("ignore")
Titanic - Machine Learning from Disaster
14,110,105
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: clean_text(x)) test_df["question_text"] = test_df...
train=pd.read_csv('.. /input/titanic/train.csv') test=pd.read_csv('.. /input/titanic/test.csv') y_test=pd.read_csv('.. /input/titanic/gender_submission.csv' )
Titanic - Machine Learning from Disaster
14,110,105
def load_glove(word_index): EMBEDDING_FILE = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt' emb_mean,emb_std = -0.005838499,0.48782197 embed_size = 300 nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size)) with open(EMBEDDING_FILE, 'r', e...
p=train.loc[train['Survived']==1 ] print(len(p)) male=p.loc[p['Sex']=='male'] female=p.loc[p['Sex']=='female'] print(male['Pclass'].value_counts()) print(female['Pclass'].value_counts() )
Titanic - Machine Learning from Disaster
14,110,105
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 rocauc = roc_auc_score(y_true, y_proba) p, r, _ = precision_recall_...
p=train.loc[train['Survived']==0 ] male=p.loc[p['Sex']=='male'] female=p.loc[p['Sex']=='female'] print(male['Pclass'].value_counts()) print(female['Pclass'].value_counts() )
Titanic - Machine Learning from Disaster
14,110,105
class CyclicLR(Callback): def __init__(self, base_lr=0.001, max_lr=0.006, step_size=2000., mode='triangular', gamma=1., scale_fn=None, scale_mode='cycle'): super(CyclicLR, self ).__init__() self.base_lr = base_lr self.max_lr = max_lr self.step_size = step_size self.mode = mode self.gamma = gamma if scale_fn == None: ...
feature_mix=[] for i in range(0,len(train)) : marks=0 if(train['Sex'].iloc[i]=='female'): marks=marks+10 if(train['Pclass'].iloc[i]!=1): marks=marks+5 else: marks=marks+2 if(train['Age'].iloc[i]<35 and train['Age'].iloc[i]>20): marks=marks+4 else: marks=marks+2 feature_mix.append(marks) train['feature_mix']=feature_mi...
Titanic - Machine Learning from Disaster
14,110,105
class Attention(Layer): def __init__(self, step_dim, W_regularizer=None, b_regularizer=None, W_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.b_regularizer = regularizers.ge...
feature_mix=[] for i in range(0,len(test)) : marks=0 if(test['Sex'].iloc[i]=='female'): marks=marks+10 if(test['Pclass'].iloc[i]!=1): marks=marks+5 else: marks=marks+2 if(test['Age'].iloc[i]<35 and test['Age'].iloc[i]>20): marks=marks+4 feature_mix.append(marks) test['feature_mix']=feature_mix test['feature_mix'].valu...
Titanic - Machine Learning from Disaster
14,110,105
def model_gru_conv_3(embedding_matrix): inp = Input(shape=(maxlen,)) x = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False )(inp) x = SpatialDropout1D(0.2 )(x) x0 = Bidirectional(CuDNNLSTM(128, kernel_initializer=initializers.glorot_uniform(seed = 2018), return_sequences=True))(x) x1 = ...
y_test.head() PassengerId=y_test['PassengerId'] y_test=y_test.drop(['PassengerId'],axis=1 )
Titanic - Machine Learning from Disaster
14,110,105
SEED=2018 def model_RCNN(embedding_matrix, hidden_dim_1=128, hidden_dim_2=64,max_features=max_features): embedding_matrix = np.concatenate([embedding_matrix,np.zeros(( 1,np.shape(embedding_matrix)[1])) ]) print(np.shape(embedding_matrix)) left_context = Input(shape=(maxlen,)) document = Input(shape=(maxlen,)) right_co...
train_m=(max(train['Age'])+min(train['Age'])) /2 values={'Cabin':'nocabin','Age':train_m,'Embarked':'notknown'} train=train.fillna(value=values) test_m=(max(test['Age'])+min(test['Age'])) /2 print(test_m) values={'Cabin':'nocabin','Age':test_m,'Embarked':'notknown',"Fare":max(test['Fare'])} test=test.fillna(value=val...
Titanic - Machine Learning from Disaster
14,110,105
def model_lstm_atten(embedding_matrix): inp = Input(shape=(maxlen,)) x = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False )(inp) x = SpatialDropout1D(0.2 )(x) x0 = Bidirectional(CuDNNLSTM(128, return_sequences=True))(x) x2 = Bidirectional(CuDNNGRU(96, return_sequences=True))(x0) y2 = ...
y= train["Survived"] train=train.drop(["Survived"],axis=1 )
Titanic - Machine Learning from Disaster
14,110,105
def model_lstm_max(embedding_matrix): inp = Input(shape=(maxlen,)) x = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False )(inp) x = SpatialDropout1D(0.2 )(x) x0 = Bidirectional(CuDNNLSTM(128, return_sequences=True))(x) x1 = Bidirectional(CuDNNGRU(64, kernel_initializer=initializers.glor...
X_train, X_cv, y_train, y_cv = train_test_split(train, y, stratify=y, test_size=0.2,random_state=42 )
Titanic - Machine Learning from Disaster
14,110,105
def get_train_list(train_X): return [np.concatenate(( np.ones(( np.shape(train_X)[0],1)) *max_features+1,train_X[:,1:]),1),train_X,np.concatenate(( np.ones(( np.shape(train_X)[0],1)) *max_features+1,train_X[:,::-1][:,1:]),1)] def RCNN_train_pred(model, epochs=2): train_X_list = get_train_list(train_X) test_X_list=get_...
vectorizer = CountVectorizer() X_tr_emb =vectorizer.fit_transform(X_train['Embarked']) X_cv_emb =vectorizer.transform(X_cv['Embarked']) X_te_emb =vectorizer.transform(test['Embarked'] )
Titanic - Machine Learning from Disaster
14,110,105
def train_pred(model, epochs=2): for e in range(epochs): model.fit(train_X, train_y, batch_size=512, epochs=1, validation_data=(val_X, val_y),verbose=1,callbacks=[clr]) pred_val_y = model.predict([val_X], batch_size=1024, verbose=0) pred_test_y = model.predict([test_X], batch_size=1024, verbose=0) return pred_val_y,...
enc = OneHotEncoder(handle_unknown='ignore') X_tr_age =enc.fit_transform(np.array(X_train['Age'] ).reshape(-1,1)) X_cv_age =enc.transform(np.array(X_cv['Age'] ).reshape(-1,1)) X_te_age =enc.transform(np.array(test['Age'] ).reshape(-1,1))
Titanic - Machine Learning from Disaster
14,110,105
train_X, val_X, test_X, train_y, val_y, word_index = load_and_prec() max_features = len(word_index) print(max_features) embedding_matrix_1 = load_glove(word_index) embedding_matrix_2 = load_fasttext(word_index) embedding_matrix = np.concatenate([embedding_matrix_1, embedding_matrix_2], axis = 1) np.shape(embedding...
X_tr_fare =enc.fit_transform(np.array(X_train['Fare'] ).reshape(-1,1)) X_cv_fare =enc.transform(np.array(X_cv['Fare'] ).reshape(-1,1)) X_te_fare =enc.transform(np.array(test['Fare'] ).reshape(-1,1))
Titanic - Machine Learning from Disaster
14,110,105
outputs = []<choose_model_class>
X_tr_Sbp =enc.fit_transform(np.array(X_train['SibSp'] ).reshape(-1,1)) X_cv_Sbp =enc.transform(np.array(X_cv['SibSp'] ).reshape(-1,1)) X_te_Sbp =enc.transform(np.array(test['SibSp'] ).reshape(-1,1))
Titanic - Machine Learning from Disaster
14,110,105
clr = CyclicLR(base_lr=0.001, max_lr=0.003,step_size=300., mode='exp_range', gamma=0.99994 )<compute_train_metric>
X_tr_par =enc.fit_transform(np.array(X_train['Parch'] ).reshape(-1,1)) X_cv_par =enc.transform(np.array(X_cv['Parch'] ).reshape(-1,1)) X_te_par=enc.transform(np.array(test['Parch'] ).reshape(-1,1))
Titanic - Machine Learning from Disaster