kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
13,420,831
tqdm.pandas(desc='Progress') <define_variables>
tuned_LR = LogisticRegression(C= 11.288378916846883, max_iter= 100, penalty= 'l1', random_state= 42, solver= 'liblinear') get_model_accuracy(tuned_LR )
Titanic - Machine Learning from Disaster
13,420,831
embed_size = 300 max_features = 120000 maxlen = 70 batch_size = 512 n_epochs = 5 n_splits = 5 SEED = 1029<set_options>
param_grid = { 'random_state': [42], 'C': [.1,.3, 1, 3], 'kernel': ['rbf'], 'gamma': [.03,.1,.3, 1] } clf_SVC = GridSearchCV(SVC, param_grid=param_grid, cv=5, verbose=True, n_jobs=-1) best_clf_SVC = clf_SVC.fit(X_train_scaled, y_train) clf_performance(best_clf_SVC )
Titanic - Machine Learning from Disaster
13,420,831
def seed_everything(seed=1029): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True seed_everything()<features_selection>
print_valid_params("'C': 3, 'gamma': 0.03, 'kernel': 'rbf', 'random_state': 42" )
Titanic - Machine Learning from Disaster
13,420,831
def load_glove(word_index): EMBEDDING_FILE = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')[:300] embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = -0.005838499,0.48782197 embed_size = all_embs.shape[1] nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size)) for word, i in word_index.items() : if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix def load_fasttext(word_index): EMBEDDING_FILE = '.. /input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)if len(o)>100) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = all_embs.mean() , all_embs.std() embed_size = all_embs.shape[1] nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size)) for word, i in word_index.items() : if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix def load_para(word_index): EMBEDDING_FILE = '.. /input/embeddings/paragram_300_sl999/paragram_300_sl999.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE, encoding="utf8", errors='ignore')if len(o)>100) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = -0.0053247833,0.49346462 embed_size = all_embs.shape[1] nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size)) for word, i in word_index.items() : if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix<load_from_csv>
tuned_SVC = svm.SVC(C= 3, gamma= 0.03, kernel= 'rbf', random_state= 42, probability=True) get_model_accuracy(tuned_SVC )
Titanic - Machine Learning from Disaster
13,420,831
df_train = pd.read_csv(".. /input/train.csv") df_test = pd.read_csv(".. /input/test.csv") df = pd.concat([df_train ,df_test],sort=True )<feature_engineering>
param_grid = { 'n_neighbors': [3, 5, 7, 9], 'weights': ['uniform', 'distance'], 'algorithm': ['auto', 'ball_tree', 'kd_tree'], 'p': [1, 2] } clf_KNN = GridSearchCV(KNN, param_grid=param_grid, cv=5, verbose=True, n_jobs=-1) best_clf_KNN = clf_KNN.fit(X_train_scaled, y_train) clf_performance(best_clf_KNN )
Titanic - Machine Learning from Disaster
13,420,831
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 vocab = build_vocab(df['question_text'] )<define_variables>
print_valid_params("'algorithm': 'auto', 'n_neighbors': 7, 'p': 2, 'weights': 'uniform'" )
Titanic - Machine Learning from Disaster
13,420,831
sin = len(df_train[df_train["target"]==0]) insin = len(df_train[df_train["target"]==1]) persin =(sin/(sin+insin)) *100 perinsin =(insin/(sin+insin)) *100 print(" print("<feature_engineering>
tuned_KNN = KNeighborsClassifier(algorithm= 'auto', n_neighbors= 7, p= 2, weights= 'uniform') get_model_accuracy(tuned_KNN )
Titanic - Machine Learning from Disaster
13,420,831
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 def known_contractions(embed): known = [] for contract in contraction_mapping: if contract in embed: known.append(contract) return known 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 def correct_spelling(x, dic): for word in dic.keys() : x = x.replace(word, dic[word]) return x def unknown_punct(embed, punct): unknown = '' for p in punct: if p not in embed: unknown += p unknown += ' ' return unknown def clean_numbers(x): x = re.sub('[0-9]{5,}', ' x = re.sub('[0-9]{4}', ' x = re.sub('[0-9]{3}', ' x = re.sub('[0-9]{2}', ' return x 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 def add_lower(embedding, vocab): count = 0 for word in vocab: if word in embedding and word.lower() not in embedding: embedding[word.lower() ] = embedding[word] count += 1 print(f"Added {count} words to embedding" )<define_variables>
param_grid = { 'random_state': [42], 'n_estimators': [10, 30, 100, 300, 1000], 'bootstrap': [True, False], 'max_depth': [1, 3, 10, 30, 100, None], 'max_features': ['auto', 'sqrt'], 'min_samples_leaf': [1, 3, 10, 30], 'min_samples_split': [2, 4, 7, 10] } clf_RFC = RandomizedSearchCV(RFC, param_distributions=param_grid, n_iter=100, cv=5, verbose=True, n_jobs=-1) best_clf_RFC = clf_RFC.fit(X_train_scaled, y_train) clf_performance(best_clf_RFC )
Titanic - Machine Learning from Disaster
13,420,831
puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', ' '·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…', '“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾', '═', '¦', '║', '―', '¥', '▓', '—', '‹', '─', '▒', ':', '¼', '⊕', '▼', '▪', '†', '■', '’', '▀', '¨', '▄', '♫', '☆', 'é', '¯', '♦', '¤', '▲', 'è', '¸', '¾', 'Ã', '⋅', '‘', '∞', '∙', ')', '↓', '、', '│', '(', '»', ',', '♪', '╩', '╚', '³', '・', '╦', '╣', '╔', '╗', '▬', '❤', 'ï', 'Ø', '¹', '≤', '‡', '√', ] def clean_text(x): x = str(x) for punct in puncts: x = x.replace(punct, f' {punct} ') return x def clean_numbers(x): x = re.sub('[0-9]{5,}', ' x = re.sub('[0-9]{4}', ' x = re.sub('[0-9]{3}', ' x = re.sub('[0-9]{2}', ' return x mispell_dict = {"ain't": "is not", "aren't": "are not","can't": "cannot", "'cause": "because", "could've": "could have", "couldn't": "could not", "didn't": "did not", "doesn't": "does not", "don't": "do not", "hadn't": "had not", "hasn't": "has not", "haven't": "have not", "he'd": "he would","he'll": "he will", "he's": "he is", "how'd": "how did", "how'd'y": "how do you", "how'll": "how will", "how's": "how is", "I'd": "I would", "I'd've": "I would have", "I'll": "I will", "I'll've": "I will have","I'm": "I am", "I've": "I have", "i'd": "i would", "i'd've": "i would have", "i'll": "i will", "i'll've": "i will have","i'm": "i am", "i've": "i have", "isn't": "is not", "it'd": "it would", "it'd've": "it would have", "it'll": "it will", "it'll've": "it will have","it's": "it is", "let's": "let us", "ma'am": "madam", "mayn't": "may not", "might've": "might have","mightn't": "might not","mightn't've": "might not have", "must've": "must have", "mustn't": "must not", "mustn't've": "must not have", "needn't": "need not", "needn't've": "need not have","o'clock": "of the clock", "oughtn't": "ought not", "oughtn't've": "ought not have", "shan't": "shall not", "sha'n't": "shall not", "shan't've": "shall not have", "she'd": "she would", "she'd've": "she would have", "she'll": "she will", "she'll've": "she will have", "she's": "she is", "should've": "should have", "shouldn't": "should not", "shouldn't've": "should not have", "so've": "so have","so's": "so as", "this's": "this is","that'd": "that would", "that'd've": "that would have", "that's": "that is", "there'd": "there would", "there'd've": "there would have", "there's": "there is", "here's": "here is","they'd": "they would", "they'd've": "they would have", "they'll": "they will", "they'll've": "they will have", "they're": "they are", "they've": "they have", "to've": "to have", "wasn't": "was not", "we'd": "we would", "we'd've": "we would have", "we'll": "we will", "we'll've": "we will have", "we're": "we are", "we've": "we have", "weren't": "were not", "what'll": "what will", "what'll've": "what will have", "what're": "what are", "what's": "what is", "what've": "what have", "when's": "when is", "when've": "when have", "where'd": "where did", "where's": "where is", "where've": "where have", "who'll": "who will", "who'll've": "who will have", "who's": "who is", "who've": "who have", "why's": "why is", "why've": "why have", "will've": "will have", "won't": "will not", "won't've": "will not have", "would've": "would have", "wouldn't": "would not", "wouldn't've": "would not have", "y'all": "you all", "y'all'd": "you all would","y'all'd've": "you all would have","y'all're": "you all are","y'all've": "you all have","you'd": "you would", "you'd've": "you would have", "you'll": "you will", "you'll've": "you will have", "you're": "you are", "you've": "you have", 'colour': 'color', 'centre': 'center', 'favourite': 'favorite', 'travelling': 'traveling', 'counselling': 'counseling', 'theatre': 'theater', 'cancelled': 'canceled', 'labour': 'labor', 'organisation': 'organization', 'wwii': 'world war 2', 'citicise': 'criticize', 'youtu ': 'youtube ', 'Qoura': 'Quora', 'sallary': 'salary', 'Whta': 'What', 'narcisist': 'narcissist', 'howdo': 'how do', 'whatare': 'what are', 'howcan': 'how can', 'howmuch': 'how much', 'howmany': 'how many', 'whydo': 'why do', 'doI': 'do I', 'theBest': 'the best', 'howdoes': 'how does', 'mastrubation': 'masturbation', 'mastrubate': 'masturbate', "mastrubating": 'masturbating', 'pennis': 'penis', 'Etherium': 'Ethereum', 'narcissit': 'narcissist', 'bigdata': 'big data', '2k17': '2017', '2k18': '2018', 'qouta': 'quota', 'exboyfriend': 'ex boyfriend', 'airhostess': 'air hostess', "whst": 'what', 'watsapp': 'whatsapp', 'demonitisation': 'demonetization', 'demonitization': 'demonetization', 'demonetisation': 'demonetization'} def _get_mispell(mispell_dict): mispell_re = re.compile('(%s)' % '|'.join(mispell_dict.keys())) return mispell_dict, mispell_re mispellings, mispellings_re = _get_mispell(mispell_dict) def replace_typical_misspell(text): def replace(match): return mispellings[match.group(0)] return mispellings_re.sub(replace, text )<feature_engineering>
print_valid_params("'random_state': 42, 'n_estimators': 30, 'min_samples_split': 7, 'min_samples_leaf': 1, 'max_features': 'sqrt', 'max_depth': None, 'bootstrap': False" )
Titanic - Machine Learning from Disaster
13,420,831
def add_features(df): df['question_text'] = df['question_text'].progress_apply(lambda x:str(x)) df['total_length'] = df['question_text'].progress_apply(len) df['capitals'] = df['question_text'].progress_apply(lambda comment: sum(1 for c in comment if c.isupper())) df['caps_vs_length'] = df.progress_apply(lambda row: float(row['capitals'])/float(row['total_length']), axis=1) df['num_words'] = df.question_text.str.count('\S+') df['num_unique_words'] = df['question_text'].progress_apply(lambda comment: len(set(w for w in comment.split()))) df['words_vs_unique'] = df['num_unique_words'] / df['num_words'] return df 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["question_text"].apply(lambda x: clean_text(x)) train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: clean_numbers(x)) test_df["question_text"] = test_df["question_text"].apply(lambda x: clean_numbers(x)) train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: replace_typical_misspell(x)) test_df["question_text"] = test_df["question_text"].apply(lambda x: replace_typical_misspell(x)) train = add_features(train_df) test = add_features(test_df) train_df["question_text"] = train_df["question_text"].apply(lambda x: x.lower()) test_df["question_text"] = test_df["question_text"].apply(lambda x: x.lower()) train_X = train_df["question_text"].fillna("_ test_X = test_df["question_text"].fillna("_ features = train[['caps_vs_length', 'words_vs_unique']].fillna(0) test_features = test[['caps_vs_length', 'words_vs_unique']].fillna(0) ss = StandardScaler() ss.fit(np.vstack(( features, test_features))) features = ss.transform(features) test_features = ss.transform(test_features) tokenizer = Tokenizer(num_words=max_features) tokenizer.fit_on_texts(list(train_X)) train_X = tokenizer.texts_to_sequences(train_X) test_X = tokenizer.texts_to_sequences(test_X) train_X = pad_sequences(train_X, maxlen=maxlen) test_X = pad_sequences(test_X, maxlen=maxlen) train_y = train_df['target'].values np.random.seed(SEED) trn_idx = np.random.permutation(len(train_X)) train_X = train_X[trn_idx] train_y = train_y[trn_idx] features = features[trn_idx] return train_X, test_X, train_y, features, test_features, tokenizer.word_index <train_model>
tuned_RFC = RandomForestClassifier(random_state= 42, n_estimators= 30, min_samples_split= 7, min_samples_leaf= 1, max_features= 'sqrt', max_depth= None, bootstrap= False) get_model_accuracy(tuned_RFC )
Titanic - Machine Learning from Disaster
13,420,831
x_train, x_test, y_train, features, test_features, word_index = load_and_prec() <save_model>
param_grid = { 'random_state': [42], 'n_estimators': [100, 300], 'learning_rate': [.1,.3, 1], 'max_depth': [1, 2, 3, 10], 'min_samples_split': [.1,.3, 1, 3, 10], 'min_samples_leaf': [.1,.3, 1, 3] } clf_GB = GridSearchCV(GB, param_grid=param_grid, cv=5, verbose=True, n_jobs=-1) best_clf_GB = clf_GB.fit(X_train_scaled, y_train) clf_performance(best_clf_GB )
Titanic - Machine Learning from Disaster
13,420,831
np.save("x_train",x_train) np.save("x_test",x_test) np.save("y_train",y_train) np.save("features",features) np.save("test_features",test_features) np.save("word_index.npy",word_index )<load_pretrained>
print_valid_params("'learning_rate': 0.1, 'max_depth': 3, 'min_samples_leaf': 3, 'min_samples_split': 0.1, 'n_estimators': 300, 'random_state': 42" )
Titanic - Machine Learning from Disaster
13,420,831
x_train = np.load("x_train.npy") x_test = np.load("x_test.npy") y_train = np.load("y_train.npy") features = np.load("features.npy") test_features = np.load("test_features.npy") word_index = np.load("word_index.npy" ).item()<normalization>
tuned_GB = GradientBoostingClassifier(learning_rate= 0.1, max_depth= 3, min_samples_leaf= 3, min_samples_split= 0.1, n_estimators= 300, random_state= 42) get_model_accuracy(tuned_GB )
Titanic - Machine Learning from Disaster
13,420,831
seed_everything() glove_embeddings = load_glove(word_index) paragram_embeddings = load_para(word_index) fasttext_embeddings = load_fasttext(word_index) embedding_matrix = np.mean([glove_embeddings, paragram_embeddings, fasttext_embeddings], axis=0) del glove_embeddings, paragram_embeddings, fasttext_embeddings gc.collect() np.shape(embedding_matrix )<split>
params = { 'weights': [[1, 1, 1], [1, 1, 2], [1, 2, 1], [2, 1, 1], [1, 2, 2], [2, 1, 2], [2, 2, 1]] } vote_weight = GridSearchCV(voting_clf_best_3, param_grid=params, cv=5, verbose=True, n_jobs=-1) best_clf_weight = vote_weight.fit(X_train_scaled, y_train) clf_performance(best_clf_weight )
Titanic - Machine Learning from Disaster
13,420,831
splits = list(StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=SEED ).split(x_train, y_train)) splits[:3]<choose_model_class>
print_valid_params("'weights': [1, 1, 2]" )
Titanic - Machine Learning from Disaster
13,420,831
class CyclicLR(object): def __init__(self, optimizer, base_lr=1e-3, max_lr=6e-3, step_size=2000, mode='triangular', gamma=1., scale_fn=None, scale_mode='cycle', last_batch_iteration=-1): if not isinstance(optimizer, Optimizer): raise TypeError('{} is not an Optimizer'.format( type(optimizer ).__name__)) self.optimizer = optimizer if isinstance(base_lr, list)or isinstance(base_lr, tuple): if len(base_lr)!= len(optimizer.param_groups): raise ValueError("expected {} base_lr, got {}".format( len(optimizer.param_groups), len(base_lr))) self.base_lrs = list(base_lr) else: self.base_lrs = [base_lr] * len(optimizer.param_groups) if isinstance(max_lr, list)or isinstance(max_lr, tuple): if len(max_lr)!= len(optimizer.param_groups): raise ValueError("expected {} max_lr, got {}".format( len(optimizer.param_groups), len(max_lr))) self.max_lrs = list(max_lr) else: self.max_lrs = [max_lr] * len(optimizer.param_groups) self.step_size = step_size if mode not in ['triangular', 'triangular2', 'exp_range'] \ and scale_fn is None: raise ValueError('mode is invalid and scale_fn is None') self.mode = mode self.gamma = gamma if scale_fn is None: if self.mode == 'triangular': self.scale_fn = self._triangular_scale_fn self.scale_mode = 'cycle' elif self.mode == 'triangular2': self.scale_fn = self._triangular2_scale_fn self.scale_mode = 'cycle' elif self.mode == 'exp_range': self.scale_fn = self._exp_range_scale_fn self.scale_mode = 'iterations' else: self.scale_fn = scale_fn self.scale_mode = scale_mode self.batch_step(last_batch_iteration + 1) self.last_batch_iteration = last_batch_iteration def batch_step(self, batch_iteration=None): if batch_iteration is None: batch_iteration = self.last_batch_iteration + 1 self.last_batch_iteration = batch_iteration for param_group, lr in zip(self.optimizer.param_groups, self.get_lr()): param_group['lr'] = lr def _triangular_scale_fn(self, x): return 1. def _triangular2_scale_fn(self, x): return 1 /(2.**(x - 1)) def _exp_range_scale_fn(self, x): return self.gamma**(x) def get_lr(self): step_size = float(self.step_size) cycle = np.floor(1 + self.last_batch_iteration /(2 * step_size)) x = np.abs(self.last_batch_iteration / step_size - 2 * cycle + 1) lrs = [] param_lrs = zip(self.optimizer.param_groups, self.base_lrs, self.max_lrs) for param_group, base_lr, max_lr in param_lrs: base_height =(max_lr - base_lr)* np.maximum(0,(1 - x)) if self.scale_mode == 'cycle': lr = base_lr + base_height * self.scale_fn(cycle) else: lr = base_lr + base_height * self.scale_fn(self.last_batch_iteration) lrs.append(lr) return lrs<choose_model_class>
weighted_voting_clf_best_3 = VotingClassifier( estimators=[('SVC', SVC),('RFC', RFC),('KNN', KNN)], voting='soft', weights= [1, 1, 2] ) get_model_accuracy(weighted_voting_clf_best_3 )
Titanic - Machine Learning from Disaster
13,420,831
embedding_dim = 300 embedding_path = '.. /save/embedding_matrix.npy' use_pretrained_embedding = True hidden_size = 60 gru_len = hidden_size Routings = 4 Num_capsule = 5 Dim_capsule = 5 dropout_p = 0.25 rate_drop_dense = 0.28 LR = 0.001 T_epsilon = 1e-7 num_classes = 30 class Embed_Layer(nn.Module): def __init__(self, embedding_matrix=None, vocab_size=None, embedding_dim=300): super(Embed_Layer, self ).__init__() self.encoder = nn.Embedding(vocab_size + 1, embedding_dim) if use_pretrained_embedding: self.encoder.weight.data.copy_(t.from_numpy(embedding_matrix)) def forward(self, x, dropout_p=0.25): return nn.Dropout(p=dropout_p )(self.encoder(x)) class GRU_Layer(nn.Module): def __init__(self): super(GRU_Layer, self ).__init__() self.gru = nn.GRU(input_size=300, hidden_size=gru_len, bidirectional=True) def init_weights(self): ih =(param.data for name, param in self.named_parameters() if 'weight_ih' in name) hh =(param.data for name, param in self.named_parameters() if 'weight_hh' in name) b =(param.data for name, param in self.named_parameters() if 'bias' in name) for k in ih: nn.init.xavier_uniform_(k) for k in hh: nn.init.orthogonal_(k) for k in b: nn.init.constant_(k, 0) def forward(self, x): return self.gru(x) class Caps_Layer(nn.Module): def __init__(self, input_dim_capsule=gru_len * 2, num_capsule=Num_capsule, dim_capsule=Dim_capsule, \ routings=Routings, kernel_size=(9, 1), share_weights=True, activation='default', **kwargs): super(Caps_Layer, self ).__init__(**kwargs) self.num_capsule = num_capsule self.dim_capsule = dim_capsule self.routings = routings self.kernel_size = kernel_size self.share_weights = share_weights if activation == 'default': self.activation = self.squash else: self.activation = nn.ReLU(inplace=True) if self.share_weights: self.W = nn.Parameter( nn.init.xavier_normal_(t.empty(1, input_dim_capsule, self.num_capsule * self.dim_capsule))) else: self.W = nn.Parameter( t.randn(BATCH_SIZE, input_dim_capsule, self.num_capsule * self.dim_capsule)) def forward(self, x): if self.share_weights: u_hat_vecs = t.matmul(x, self.W) else: print('add later') batch_size = x.size(0) input_num_capsule = x.size(1) u_hat_vecs = u_hat_vecs.view(( batch_size, input_num_capsule, self.num_capsule, self.dim_capsule)) u_hat_vecs = u_hat_vecs.permute(0, 2, 1, 3) b = t.zeros_like(u_hat_vecs[:, :, :, 0]) for i in range(self.routings): b = b.permute(0, 2, 1) c = F.softmax(b, dim=2) c = c.permute(0, 2, 1) b = b.permute(0, 2, 1) outputs = self.activation(t.einsum('bij,bijk->bik',(c, u_hat_vecs))) if i < self.routings - 1: b = t.einsum('bik,bijk->bij',(outputs, u_hat_vecs)) return outputs def squash(self, x, axis=-1): s_squared_norm =(x ** 2 ).sum(axis, keepdim=True) scale = t.sqrt(s_squared_norm + T_epsilon) return x / scale class Capsule_Main(nn.Module): def __init__(self, embedding_matrix=None, vocab_size=None): super(Capsule_Main, self ).__init__() self.embed_layer = Embed_Layer(embedding_matrix, vocab_size) self.gru_layer = GRU_Layer() self.gru_layer.init_weights() self.caps_layer = Caps_Layer() self.dense_layer = Dense_Layer() def forward(self, content): content1 = self.embed_layer(content) content2, _ = self.gru_layer( content1) content3 = self.caps_layer(content2) output = self.dense_layer(content3) return output <normalization>
def submission_to_csv(y_preds, filename='submission.csv'): submission = {'PassengerId': test_data.PassengerId, 'survived': y_preds} submission_df = pd.DataFrame(data=submission) submission_csv = submission_df.to_csv(filename, index=False) return(submission_csv )
Titanic - Machine Learning from Disaster
13,420,831
class Attention(nn.Module): def __init__(self, feature_dim, step_dim, bias=True, **kwargs): super(Attention, self ).__init__(**kwargs) self.supports_masking = True self.bias = bias self.feature_dim = feature_dim self.step_dim = step_dim self.features_dim = 0 weight = torch.zeros(feature_dim, 1) nn.init.xavier_uniform_(weight) self.weight = nn.Parameter(weight) if bias: self.b = nn.Parameter(torch.zeros(step_dim)) def forward(self, x, mask=None): feature_dim = self.feature_dim step_dim = self.step_dim eij = torch.mm( x.contiguous().view(-1, feature_dim), self.weight ).view(-1, step_dim) if self.bias: eij = eij + self.b eij = torch.tanh(eij) a = torch.exp(eij) if mask is not None: a = a * mask a = a / torch.sum(a, 1, keepdim=True)+ 1e-10 weighted_input = x * torch.unsqueeze(a, -1) return torch.sum(weighted_input, 1) class NeuralNet(nn.Module): def __init__(self): super(NeuralNet, self ).__init__() fc_layer = 16 fc_layer1 = 16 self.embedding = nn.Embedding(max_features, embed_size) self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32)) self.embedding.weight.requires_grad = False self.embedding_dropout = nn.Dropout2d(0.1) self.lstm = nn.LSTM(embed_size, hidden_size, bidirectional=True, batch_first=True) self.gru = nn.GRU(hidden_size * 2, hidden_size, bidirectional=True, batch_first=True) self.lstm2 = nn.LSTM(hidden_size * 2, hidden_size, bidirectional=True, batch_first=True) self.lstm_attention = Attention(hidden_size * 2, maxlen) self.gru_attention = Attention(hidden_size * 2, maxlen) self.bn = nn.BatchNorm1d(16, momentum=0.5) self.linear = nn.Linear(hidden_size*8+3, fc_layer1) self.relu = nn.ReLU() self.dropout = nn.Dropout(0.1) self.fc = nn.Linear(fc_layer**2,fc_layer) self.out = nn.Linear(fc_layer, 1) self.lincaps = nn.Linear(Num_capsule * Dim_capsule, 1) self.caps_layer = Caps_Layer() def forward(self, x): h_embedding = self.embedding(x[0]) h_embedding = torch.squeeze( self.embedding_dropout(torch.unsqueeze(h_embedding, 0))) h_lstm, _ = self.lstm(h_embedding) h_gru, _ = self.gru(h_lstm) content3 = self.caps_layer(h_gru) content3 = self.dropout(content3) batch_size = content3.size(0) content3 = content3.view(batch_size, -1) content3 = self.relu(self.lincaps(content3)) h_lstm_atten = self.lstm_attention(h_lstm) h_gru_atten = self.gru_attention(h_gru) avg_pool = torch.mean(h_gru, 1) max_pool, _ = torch.max(h_gru, 1) f = torch.tensor(x[1], dtype=torch.float ).cuda() conc = torch.cat(( h_lstm_atten, h_gru_atten,content3, avg_pool, max_pool,f), 1) conc = self.relu(self.linear(conc)) conc = self.bn(conc) conc = self.dropout(conc) out = self.out(conc) return out<categorify>
tuned_RFC.fit(X_train_scaled, y_train) tuned_RFC_preds = tuned_RFC.predict(X_test_scaled) submission_to_csv(tuned_RFC_preds, 'RFC_submission.csv' )
Titanic - Machine Learning from Disaster
13,420,831
class MyDataset(Dataset): def __init__(self,dataset): self.dataset = dataset def __getitem__(self, index): data, target = self.dataset[index] return data, target, index def __len__(self): return len(self.dataset )<compute_train_metric>
tuned_GB.fit(X_train_scaled, y_train) tuned_GB_preds = tuned_GB.predict(X_test_scaled) submission_to_csv(tuned_GB_preds, 'GB_clf_submission.csv' )
Titanic - Machine Learning from Disaster
13,420,831
class FocalLoss(nn.Module): def __init__(self, alpha=1, gamma=2, logits=True, reduction='elementwise_mean'): super(FocalLoss, self ).__init__() self.alpha = alpha self.gamma = gamma self.logits = logits self.reduction = reduction def forward(self, inputs, targets): if self.logits: BCE_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction='none') else: BCE_loss = F.binary_cross_entropy(inputs, targets, reduction='none') pt = torch.exp(-BCE_loss) F_loss = self.alpha *(1-pt)**self.gamma * BCE_loss if self.reduction is None: return F_loss else: return torch.mean(F_loss )<define_variables>
weighted_voting_clf_best_3.fit(X_train_scaled, y_train) weighted_voting_clf_best_3_preds = weighted_voting_clf_best_3.predict(X_test_scaled) submission_to_csv(weighted_voting_clf_best_3_preds, 'soft_voting_clf_submission.csv' )
Titanic - Machine Learning from Disaster
14,344,676
def sigmoid(x): return 1 /(1 + np.exp(-x)) train_preds = np.zeros(( len(x_train))) test_preds = np.zeros(( len(df_test))) seed_everything() x_test_cuda = torch.tensor(x_test, dtype=torch.long ).cuda() test = torch.utils.data.TensorDataset(x_test_cuda) test_loader = torch.utils.data.DataLoader(test, batch_size=batch_size, shuffle=False) avg_losses_f = [] avg_val_losses_f = []<data_type_conversions>
train = pd.read_csv("/kaggle/input/titanic/train.csv") test = pd.read_csv("/kaggle/input/titanic/test.csv" )
Titanic - Machine Learning from Disaster
14,344,676
for i,(train_idx, valid_idx)in enumerate(splits): x_train = np.array(x_train) y_train = np.array(y_train) features = np.array(features) x_train_fold = torch.tensor(x_train[train_idx.astype(int)], dtype=torch.long ).cuda() y_train_fold = torch.tensor(y_train[train_idx.astype(int), np.newaxis], dtype=torch.float32 ).cuda() kfold_X_features = features[train_idx.astype(int)] kfold_X_valid_features = features[valid_idx.astype(int)] x_val_fold = torch.tensor(x_train[valid_idx.astype(int)], dtype=torch.long ).cuda() y_val_fold = torch.tensor(y_train[valid_idx.astype(int), np.newaxis], dtype=torch.float32 ).cuda() model = NeuralNet() model.cuda() gamma = 1 + i/16 loss_fn = FocalLoss(gamma=gamma) step_size = 300 base_lr, max_lr = 0.001, 0.003 optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=max_lr) scheduler = CyclicLR(optimizer, base_lr=base_lr, max_lr=max_lr, step_size=step_size, mode='exp_range', gamma=0.99994) train = torch.utils.data.TensorDataset(x_train_fold, y_train_fold) valid = torch.utils.data.TensorDataset(x_val_fold, y_val_fold) train = MyDataset(train) valid = MyDataset(valid) train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True) valid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False) print(f'Fold {i + 1}') for epoch in range(n_epochs): start_time = time.time() model.train() avg_loss = 0. for i,(x_batch, y_batch, index)in enumerate(train_loader): f = kfold_X_features[index] y_pred = model([x_batch,f]) if scheduler: scheduler.batch_step() loss = loss_fn(y_pred, y_batch) optimizer.zero_grad() loss.backward() optimizer.step() avg_loss += loss.item() / len(train_loader) model.eval() valid_preds_fold = np.zeros(( x_val_fold.size(0))) test_preds_fold = np.zeros(( len(df_test))) avg_val_loss = 0. for i,(x_batch, y_batch, index)in enumerate(valid_loader): f = kfold_X_valid_features[index] y_pred = model([x_batch,f] ).detach() avg_val_loss += loss_fn(y_pred, y_batch ).item() / len(valid_loader) valid_preds_fold[i * batch_size:(i+1)* batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0] elapsed_time = time.time() - start_time print('Epoch {}/{} \t loss={:.4f} \t val_loss={:.4f} \t time={:.2f}s'.format( epoch + 1, n_epochs, avg_loss, avg_val_loss, elapsed_time)) avg_losses_f.append(avg_loss) avg_val_losses_f.append(avg_val_loss) for i,(x_batch,)in enumerate(test_loader): f = test_features[i * batch_size:(i+1)* batch_size] y_pred = model([x_batch,f] ).detach() test_preds_fold[i * batch_size:(i+1)* batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0] train_preds[valid_idx] = valid_preds_fold test_preds += test_preds_fold / len(splits) print('All \t loss={:.4f} \t val_loss={:.4f} \t '.format(np.average(avg_losses_f),np.average(avg_val_losses_f))) <compute_test_metric>
train.groupby('Pclass' ).mean() ['Survived']*100
Titanic - Machine Learning from Disaster
14,344,676
def bestThresshold(y_train,train_preds): tmp = [0,0,0] delta = 0 for tmp[0] in tqdm(np.arange(0.3, 0.601, 0.001)) : tmp[1] = f1_score(y_train, np.array(train_preds)>tmp[0]) if tmp[1] > tmp[2]: delta = tmp[0] tmp[2] = tmp[1] print('best threshold is {:.4f} with F1 score: {:.4f}'.format(delta, tmp[2])) return delta delta = bestThresshold(y_train,train_preds )<save_to_csv>
train.isna().sum()
Titanic - Machine Learning from Disaster
14,344,676
submission = df_test[['qid']].copy() submission['prediction'] =(test_preds > delta ).astype(int) submission.to_csv('submission.csv', index=False )<import_modules>
print(train.isna().sum() ,' ', test.isna().sum())
Titanic - Machine Learning from Disaster
14,344,676
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, LSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D from keras.layers import Bidirectional, GlobalMaxPool1D from keras.models import Model from keras import initializers, regularizers, constraints, optimizers, layers<load_from_csv>
train[train['Embarked'].isna() == True]
Titanic - Machine Learning from Disaster
14,344,676
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 )<split>
train['Embarked'] = train['Embarked'].fillna(value='S' )
Titanic - Machine Learning from Disaster
14,344,676
train_df, val_df = train_test_split(train_df, test_size=0.1, random_state=2018) embed_size = 300 max_features = 50000 maxlen = 100 train_X = train_df["question_text"].fillna("_na_" ).values val_X = val_df["question_text"].fillna("_na_" ).values test_X = test_df["question_text"].fillna("_na_" ).values tokenizer = Tokenizer(num_words=max_features) tokenizer.fit_on_texts(list(train_X)) train_X = tokenizer.texts_to_sequences(train_X) val_X = tokenizer.texts_to_sequences(val_X) test_X = tokenizer.texts_to_sequences(test_X) train_X = pad_sequences(train_X, maxlen=maxlen) val_X = pad_sequences(val_X, maxlen=maxlen) test_X = pad_sequences(test_X, maxlen=maxlen) train_y = train_df['target'].values val_y = val_df['target'].values<statistical_test>
train = pd.get_dummies(train, columns=['Embarked'], drop_first=True) train = pd.get_dummies(train, columns=['Sex'], drop_first=True) test = pd.get_dummies(test, columns=['Embarked'], drop_first=True) test = pd.get_dummies(test, columns=['Sex'], drop_first=True)
Titanic - Machine Learning from Disaster
14,344,676
EMBEDDING_FILE = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = all_embs.mean() , all_embs.std() embed_size = all_embs.shape[1] word_index = tokenizer.word_index nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size)) for word, i in word_index.items() : if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector inp = Input(shape=(maxlen,)) x = Embedding(max_features, embed_size, weights=[embedding_matrix] )(inp) x = Bidirectional(CuDNNGRU(64, return_sequences=True))(x) x = GlobalMaxPool1D()(x) x = Dense(16, activation="relu" )(x) x = Dropout(0.1 )(x) x = Dense(1, activation="sigmoid" )(x) model = Model(inputs=inp, outputs=x) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) print(model.summary() )<train_model>
train.drop(['Name','Ticket'],axis=1,inplace=True) test.drop(['Name','Ticket'],axis=1,inplace=True )
Titanic - Machine Learning from Disaster
14,344,676
model.fit(train_X, train_y, batch_size=512, epochs=2, validation_data=(val_X, val_y))<predict_on_test>
train.Cabin.isna().sum() /len(train.Cabin)*100
Titanic - Machine Learning from Disaster
14,344,676
pred_glove_val_y = model.predict([val_X], batch_size=1024, verbose=1) for thresh in np.arange(0.1, 0.501, 0.01): thresh = np.round(thresh, 2) print("F1 score at threshold {0} is {1}".format(thresh, metrics.f1_score(val_y,(pred_glove_val_y>thresh ).astype(int))))<predict_on_test>
train = train.drop('Cabin',axis=1) test = test.drop('Cabin',axis=1 )
Titanic - Machine Learning from Disaster
14,344,676
pred_glove_test_y = model.predict([test_X], batch_size=1024, verbose=1 )<set_options>
def imputeAge(cols): Age = cols[0] Pclass = cols[1] if(pd.isnull(Age)) : if(Pclass==1): return 37 if Pclass==2: return 29 else: return 24 else: return Age
Titanic - Machine Learning from Disaster
14,344,676
del word_index, embeddings_index, all_embs, embedding_matrix, model, inp, x time.sleep(10 )<statistical_test>
train['Age']= train[['Age','Pclass']].apply(imputeAge,axis=1) test['Age']= test[['Age','Pclass']].apply(imputeAge,axis=1 )
Titanic - Machine Learning from Disaster
14,344,676
EMBEDDING_FILE = '.. /input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)if len(o)>100) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = all_embs.mean() , all_embs.std() embed_size = all_embs.shape[1] word_index = tokenizer.word_index nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size)) for word, i in word_index.items() : if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector inp = Input(shape=(maxlen,)) x = Embedding(max_features, embed_size, weights=[embedding_matrix] )(inp) x = Bidirectional(CuDNNGRU(64, return_sequences=True))(x) x = GlobalMaxPool1D()(x) x = Dense(16, activation="relu" )(x) x = Dropout(0.1 )(x) x = Dense(1, activation="sigmoid" )(x) model = Model(inputs=inp, outputs=x) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'] )<train_model>
test['Fare'] = test['Fare'].fillna(( test.Fare.mean())) train['Fare'] = train['Fare'].fillna(( train.Fare.mean()))
Titanic - Machine Learning from Disaster
14,344,676
model.fit(train_X, train_y, batch_size=512, epochs=2, validation_data=(val_X, val_y))<predict_on_test>
Titanic - Machine Learning from Disaster
14,344,676
pred_fasttext_val_y = model.predict([val_X], batch_size=1024, verbose=1) for thresh in np.arange(0.1, 0.501, 0.01): thresh = np.round(thresh, 2) print("F1 score at threshold {0} is {1}".format(thresh, metrics.f1_score(val_y,(pred_fasttext_val_y>thresh ).astype(int))))<predict_on_test>
y = train['Survived'] features = ['PassengerId','Pclass','Age','SibSp','Sex_male','Parch','Embarked_Q','Embarked_S','Fare'] X = train[features] X_test = test[features] model = RandomForestClassifier(n_estimators=100,max_depth=5,random_state=1) model.fit(X,y)
Titanic - Machine Learning from Disaster
14,344,676
pred_fasttext_test_y = model.predict([test_X], batch_size=1024, verbose=1 )<set_options>
predictions = model.predict(X_test )
Titanic - Machine Learning from Disaster
14,344,676
del word_index, embeddings_index, all_embs, embedding_matrix, model, inp, x time.sleep(10 )<statistical_test>
output = pd.DataFrame({'PassengerId': X_test.PassengerId, 'Survived': predictions}) output.to_csv('my_submission.csv', index=False) print("Your submission was successfully saved!" )
Titanic - Machine Learning from Disaster
14,646,784
EMBEDDING_FILE = '.. /input/embeddings/paragram_300_sl999/paragram_300_sl999.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE, encoding="utf8", errors='ignore')if len(o)>100) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = all_embs.mean() , all_embs.std() embed_size = all_embs.shape[1] word_index = tokenizer.word_index nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size)) for word, i in word_index.items() : if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector inp = Input(shape=(maxlen,)) x = Embedding(max_features, embed_size, weights=[embedding_matrix] )(inp) x = Bidirectional(CuDNNGRU(64, return_sequences=True))(x) x = GlobalMaxPool1D()(x) x = Dense(16, activation="relu" )(x) x = Dropout(0.1 )(x) x = Dense(1, activation="sigmoid" )(x) model = Model(inputs=inp, outputs=x) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'] )<train_model>
train_data = pd.read_csv("/kaggle/input/titanic/train.csv") train_data.head()
Titanic - Machine Learning from Disaster
14,646,784
model.fit(train_X, train_y, batch_size=512, epochs=2, validation_data=(val_X, val_y))<predict_on_test>
test_data = pd.read_csv("/kaggle/input/titanic/test.csv") test_data.head()
Titanic - Machine Learning from Disaster
14,646,784
pred_paragram_val_y = model.predict([val_X], batch_size=1024, verbose=1) for thresh in np.arange(0.1, 0.501, 0.01): thresh = np.round(thresh, 2) print("F1 score at threshold {0} is {1}".format(thresh, metrics.f1_score(val_y,(pred_paragram_val_y>thresh ).astype(int))))<predict_on_test>
train_data.groupby('Sex' ).Survived.mean()
Titanic - Machine Learning from Disaster
14,646,784
pred_paragram_test_y = model.predict([test_X], batch_size=1024, verbose=1 )<set_options>
train_data.groupby('Pclass' ).Survived.mean()
Titanic - Machine Learning from Disaster
14,646,784
del word_index, embeddings_index, all_embs, embedding_matrix, model, inp, x time.sleep(10 )<compute_test_metric>
train_data.isnull()
Titanic - Machine Learning from Disaster
14,646,784
pred_val_y = 0.30*pred_glove_val_y + 0.35*pred_fasttext_val_y + 0.35*pred_paragram_val_y for thresh in np.arange(0.1, 0.501, 0.01): thresh = np.round(thresh, 2) print("F1 score at threshold {0} is {1}".format(thresh, metrics.f1_score(val_y,(pred_val_y>thresh ).astype(int))))<save_to_csv>
train_data.isnull().sum()
Titanic - Machine Learning from Disaster
14,646,784
pred_test_y = 0.30*pred_glove_test_y + 0.35*pred_fasttext_test_y + 0.35*pred_paragram_test_y pred_test_y =(pred_test_y>0.36 ).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 )<import_modules>
train_data.drop(["Name","Cabin"], axis=1, inplace=True )
Titanic - Machine Learning from Disaster
14,646,784
tqdm.pandas(desc='Progress') <define_variables>
train_data['Age'].fillna(value=train_data['Age'].mean() , inplace=True )
Titanic - Machine Learning from Disaster
14,646,784
embed_size = 300 max_features = 120000 maxlen = 70 batch_size = 512 n_epochs = 5 n_splits = 5 SEED = 1029<set_options>
train_data['Embarked'] = train_data['Embarked'].fillna(value=train_data['Embarked'].mode() [0] )
Titanic - Machine Learning from Disaster
14,646,784
def seed_everything(seed=1029): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True seed_everything()<features_selection>
train_data.isnull().sum()
Titanic - Machine Learning from Disaster
14,646,784
def load_glove(word_index): EMBEDDING_FILE = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')[:300] embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = -0.005838499,0.48782197 embed_size = all_embs.shape[1] nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size)) for word, i in word_index.items() : if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix def load_fasttext(word_index): EMBEDDING_FILE = '.. /input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)if len(o)>100) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = all_embs.mean() , all_embs.std() embed_size = all_embs.shape[1] nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size)) for word, i in word_index.items() : if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix def load_para(word_index): EMBEDDING_FILE = '.. /input/embeddings/paragram_300_sl999/paragram_300_sl999.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE, encoding="utf8", errors='ignore')if len(o)>100) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = -0.0053247833,0.49346462 embed_size = all_embs.shape[1] nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size)) for word, i in word_index.items() : if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix<load_from_csv>
train_data['Sex'] = train_data['Sex'].replace(['male', 'female'],[1,0]) train_data.rename(columns = {'Sex' : 'gender'}, inplace = True )
Titanic - Machine Learning from Disaster
14,646,784
df_train = pd.read_csv(".. /input/train.csv") df_test = pd.read_csv(".. /input/test.csv") df = pd.concat([df_train ,df_test],sort=True )<feature_engineering>
train_data['Embarked'] = train_data['Embarked'].replace(['S','C','Q'],[0,1,2]) train_data.rename(columns = {'Embarked' : 'port'}, inplace = True )
Titanic - Machine Learning from Disaster
14,646,784
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 vocab = build_vocab(df['question_text'] )<define_variables>
train_data.rename(columns = {'Pclass' : 'passenger_cls'} )
Titanic - Machine Learning from Disaster
14,646,784
sin = len(df_train[df_train["target"]==0]) insin = len(df_train[df_train["target"]==1]) persin =(sin/(sin+insin)) *100 perinsin =(insin/(sin+insin)) *100 print(" print("<feature_engineering>
train_data['family_members'] = train_data['SibSp'] + train_data['Parch'] train_data.drop(['SibSp', 'Parch'], axis = 1, inplace=True )
Titanic - Machine Learning from Disaster
14,646,784
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 def known_contractions(embed): known = [] for contract in contraction_mapping: if contract in embed: known.append(contract) return known 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 def correct_spelling(x, dic): for word in dic.keys() : x = x.replace(word, dic[word]) return x def unknown_punct(embed, punct): unknown = '' for p in punct: if p not in embed: unknown += p unknown += ' ' return unknown def clean_numbers(x): x = re.sub('[0-9]{5,}', ' x = re.sub('[0-9]{4}', ' x = re.sub('[0-9]{3}', ' x = re.sub('[0-9]{2}', ' return x 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 def add_lower(embedding, vocab): count = 0 for word in vocab: if word in embedding and word.lower() not in embedding: embedding[word.lower() ] = embedding[word] count += 1 print(f"Added {count} words to embedding" )<define_variables>
train_data.loc[ train_data['Age'] <= 21, 'Age'] = 0 train_data.loc[(train_data['Age'] > 21)&(train_data['Age'] <= 34), 'Age'] = 1 train_data.loc[(train_data['Age'] > 34)&(train_data['Age'] <= 54), 'Age'] = 2 train_data.loc[(train_data['Age'] > 60)&(train_data['Age'] <= 75), 'Age'] = 3 train_data.loc[ train_data['Age'] > 75, 'Age'] ;
Titanic - Machine Learning from Disaster
14,646,784
puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', ' '·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…', '“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾', '═', '¦', '║', '―', '¥', '▓', '—', '‹', '─', '▒', ':', '¼', '⊕', '▼', '▪', '†', '■', '’', '▀', '¨', '▄', '♫', '☆', 'é', '¯', '♦', '¤', '▲', 'è', '¸', '¾', 'Ã', '⋅', '‘', '∞', '∙', ')', '↓', '、', '│', '(', '»', ',', '♪', '╩', '╚', '³', '・', '╦', '╣', '╔', '╗', '▬', '❤', 'ï', 'Ø', '¹', '≤', '‡', '√', ] def clean_text(x): x = str(x) for punct in puncts: x = x.replace(punct, f' {punct} ') return x def clean_numbers(x): x = re.sub('[0-9]{5,}', ' x = re.sub('[0-9]{4}', ' x = re.sub('[0-9]{3}', ' x = re.sub('[0-9]{2}', ' return x mispell_dict = {"ain't": "is not", "aren't": "are not","can't": "cannot", "'cause": "because", "could've": "could have", "couldn't": "could not", "didn't": "did not", "doesn't": "does not", "don't": "do not", "hadn't": "had not", "hasn't": "has not", "haven't": "have not", "he'd": "he would","he'll": "he will", "he's": "he is", "how'd": "how did", "how'd'y": "how do you", "how'll": "how will", "how's": "how is", "I'd": "I would", "I'd've": "I would have", "I'll": "I will", "I'll've": "I will have","I'm": "I am", "I've": "I have", "i'd": "i would", "i'd've": "i would have", "i'll": "i will", "i'll've": "i will have","i'm": "i am", "i've": "i have", "isn't": "is not", "it'd": "it would", "it'd've": "it would have", "it'll": "it will", "it'll've": "it will have","it's": "it is", "let's": "let us", "ma'am": "madam", "mayn't": "may not", "might've": "might have","mightn't": "might not","mightn't've": "might not have", "must've": "must have", "mustn't": "must not", "mustn't've": "must not have", "needn't": "need not", "needn't've": "need not have","o'clock": "of the clock", "oughtn't": "ought not", "oughtn't've": "ought not have", "shan't": "shall not", "sha'n't": "shall not", "shan't've": "shall not have", "she'd": "she would", "she'd've": "she would have", "she'll": "she will", "she'll've": "she will have", "she's": "she is", "should've": "should have", "shouldn't": "should not", "shouldn't've": "should not have", "so've": "so have","so's": "so as", "this's": "this is","that'd": "that would", "that'd've": "that would have", "that's": "that is", "there'd": "there would", "there'd've": "there would have", "there's": "there is", "here's": "here is","they'd": "they would", "they'd've": "they would have", "they'll": "they will", "they'll've": "they will have", "they're": "they are", "they've": "they have", "to've": "to have", "wasn't": "was not", "we'd": "we would", "we'd've": "we would have", "we'll": "we will", "we'll've": "we will have", "we're": "we are", "we've": "we have", "weren't": "were not", "what'll": "what will", "what'll've": "what will have", "what're": "what are", "what's": "what is", "what've": "what have", "when's": "when is", "when've": "when have", "where'd": "where did", "where's": "where is", "where've": "where have", "who'll": "who will", "who'll've": "who will have", "who's": "who is", "who've": "who have", "why's": "why is", "why've": "why have", "will've": "will have", "won't": "will not", "won't've": "will not have", "would've": "would have", "wouldn't": "would not", "wouldn't've": "would not have", "y'all": "you all", "y'all'd": "you all would","y'all'd've": "you all would have","y'all're": "you all are","y'all've": "you all have","you'd": "you would", "you'd've": "you would have", "you'll": "you will", "you'll've": "you will have", "you're": "you are", "you've": "you have", 'colour': 'color', 'centre': 'center', 'favourite': 'favorite', 'travelling': 'traveling', 'counselling': 'counseling', 'theatre': 'theater', 'cancelled': 'canceled', 'labour': 'labor', 'organisation': 'organization', 'wwii': 'world war 2', 'citicise': 'criticize', 'youtu ': 'youtube ', 'Qoura': 'Quora', 'sallary': 'salary', 'Whta': 'What', 'narcisist': 'narcissist', 'howdo': 'how do', 'whatare': 'what are', 'howcan': 'how can', 'howmuch': 'how much', 'howmany': 'how many', 'whydo': 'why do', 'doI': 'do I', 'theBest': 'the best', 'howdoes': 'how does', 'mastrubation': 'masturbation', 'mastrubate': 'masturbate', "mastrubating": 'masturbating', 'pennis': 'penis', 'Etherium': 'Ethereum', 'narcissit': 'narcissist', 'bigdata': 'big data', '2k17': '2017', '2k18': '2018', 'qouta': 'quota', 'exboyfriend': 'ex boyfriend', 'airhostess': 'air hostess', "whst": 'what', 'watsapp': 'whatsapp', 'demonitisation': 'demonetization', 'demonitization': 'demonetization', 'demonetisation': 'demonetization'} def _get_mispell(mispell_dict): mispell_re = re.compile('(%s)' % '|'.join(mispell_dict.keys())) return mispell_dict, mispell_re mispellings, mispellings_re = _get_mispell(mispell_dict) def replace_typical_misspell(text): def replace(match): return mispellings[match.group(0)] return mispellings_re.sub(replace, text )<feature_engineering>
train_data.loc[ train_data['Fare'] <= 7.5, 'Fare'] = 0 train_data.loc[(train_data['Fare'] > 15)&(train_data['Fare'] <= 21.5), 'Fare'] = 1 train_data.loc[(train_data['Fare'] > 21.5)&(train_data['Age'] <= 29), 'Fare'] = 2 train_data.loc[(train_data['Fare'] > 29)&(train_data['Fare'] <= 36.5), 'Fare'] = 3 train_data.loc[ train_data['Fare'] > 36.5, 'Fare'] ;
Titanic - Machine Learning from Disaster
14,646,784
def add_features(df): df['question_text'] = df['question_text'].progress_apply(lambda x:str(x)) df['total_length'] = df['question_text'].progress_apply(len) df['capitals'] = df['question_text'].progress_apply(lambda comment: sum(1 for c in comment if c.isupper())) df['caps_vs_length'] = df.progress_apply(lambda row: float(row['capitals'])/float(row['total_length']), axis=1) df['num_words'] = df.question_text.str.count('\S+') df['num_unique_words'] = df['question_text'].progress_apply(lambda comment: len(set(w for w in comment.split()))) df['words_vs_unique'] = df['num_unique_words'] / df['num_words'] return df 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["question_text"].apply(lambda x: clean_text(x)) train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: clean_numbers(x)) test_df["question_text"] = test_df["question_text"].apply(lambda x: clean_numbers(x)) train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: replace_typical_misspell(x)) test_df["question_text"] = test_df["question_text"].apply(lambda x: replace_typical_misspell(x)) train = add_features(train_df) test = add_features(test_df) train_df["question_text"] = train_df["question_text"].apply(lambda x: x.lower()) test_df["question_text"] = test_df["question_text"].apply(lambda x: x.lower()) train_X = train_df["question_text"].fillna("_ test_X = test_df["question_text"].fillna("_ features = train[['caps_vs_length', 'words_vs_unique']].fillna(0) test_features = test[['caps_vs_length', 'words_vs_unique']].fillna(0) ss = StandardScaler() ss.fit(np.vstack(( features, test_features))) features = ss.transform(features) test_features = ss.transform(test_features) tokenizer = Tokenizer(num_words=max_features) tokenizer.fit_on_texts(list(train_X)) train_X = tokenizer.texts_to_sequences(train_X) test_X = tokenizer.texts_to_sequences(test_X) train_X = pad_sequences(train_X, maxlen=maxlen) test_X = pad_sequences(test_X, maxlen=maxlen) train_y = train_df['target'].values np.random.seed(SEED) trn_idx = np.random.permutation(len(train_X)) train_X = train_X[trn_idx] train_y = train_y[trn_idx] features = features[trn_idx] return train_X, test_X, train_y, features, test_features, tokenizer.word_index <train_model>
train_data.drop(['Ticket'], axis = 1, inplace=True )
Titanic - Machine Learning from Disaster
14,646,784
x_train, x_test, y_train, features, test_features, word_index = load_and_prec() <save_model>
test_data.isnull().sum()
Titanic - Machine Learning from Disaster
14,646,784
np.save("x_train",x_train) np.save("x_test",x_test) np.save("y_train",y_train) np.save("features",features) np.save("test_features",test_features) np.save("word_index.npy",word_index )<load_pretrained>
test_data.drop(['Name', 'Ticket','Cabin'], axis = 1, inplace = True )
Titanic - Machine Learning from Disaster
14,646,784
x_train = np.load("x_train.npy") x_test = np.load("x_test.npy") y_train = np.load("y_train.npy") features = np.load("features.npy") test_features = np.load("test_features.npy") word_index = np.load("word_index.npy" ).item()<normalization>
test_data['Age'].fillna(value=test_data['Age'].mean() , inplace=True )
Titanic - Machine Learning from Disaster
14,646,784
seed_everything() glove_embeddings = load_glove(word_index) paragram_embeddings = load_para(word_index) fasttext_embeddings = load_fasttext(word_index) embedding_matrix = np.mean([glove_embeddings, paragram_embeddings, fasttext_embeddings], axis=0) del glove_embeddings, paragram_embeddings, fasttext_embeddings gc.collect() np.shape(embedding_matrix )<split>
test_data['Fare'].fillna(value=test_data['Fare'].mean() , inplace=True )
Titanic - Machine Learning from Disaster
14,646,784
splits = list(StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=SEED ).split(x_train, y_train)) splits[:3]<choose_model_class>
test_data.isnull().sum()
Titanic - Machine Learning from Disaster
14,646,784
class CyclicLR(object): def __init__(self, optimizer, base_lr=1e-3, max_lr=6e-3, step_size=2000, mode='triangular', gamma=1., scale_fn=None, scale_mode='cycle', last_batch_iteration=-1): if not isinstance(optimizer, Optimizer): raise TypeError('{} is not an Optimizer'.format( type(optimizer ).__name__)) self.optimizer = optimizer if isinstance(base_lr, list)or isinstance(base_lr, tuple): if len(base_lr)!= len(optimizer.param_groups): raise ValueError("expected {} base_lr, got {}".format( len(optimizer.param_groups), len(base_lr))) self.base_lrs = list(base_lr) else: self.base_lrs = [base_lr] * len(optimizer.param_groups) if isinstance(max_lr, list)or isinstance(max_lr, tuple): if len(max_lr)!= len(optimizer.param_groups): raise ValueError("expected {} max_lr, got {}".format( len(optimizer.param_groups), len(max_lr))) self.max_lrs = list(max_lr) else: self.max_lrs = [max_lr] * len(optimizer.param_groups) self.step_size = step_size if mode not in ['triangular', 'triangular2', 'exp_range'] \ and scale_fn is None: raise ValueError('mode is invalid and scale_fn is None') self.mode = mode self.gamma = gamma if scale_fn is None: if self.mode == 'triangular': self.scale_fn = self._triangular_scale_fn self.scale_mode = 'cycle' elif self.mode == 'triangular2': self.scale_fn = self._triangular2_scale_fn self.scale_mode = 'cycle' elif self.mode == 'exp_range': self.scale_fn = self._exp_range_scale_fn self.scale_mode = 'iterations' else: self.scale_fn = scale_fn self.scale_mode = scale_mode self.batch_step(last_batch_iteration + 1) self.last_batch_iteration = last_batch_iteration def batch_step(self, batch_iteration=None): if batch_iteration is None: batch_iteration = self.last_batch_iteration + 1 self.last_batch_iteration = batch_iteration for param_group, lr in zip(self.optimizer.param_groups, self.get_lr()): param_group['lr'] = lr def _triangular_scale_fn(self, x): return 1. def _triangular2_scale_fn(self, x): return 1 /(2.**(x - 1)) def _exp_range_scale_fn(self, x): return self.gamma**(x) def get_lr(self): step_size = float(self.step_size) cycle = np.floor(1 + self.last_batch_iteration /(2 * step_size)) x = np.abs(self.last_batch_iteration / step_size - 2 * cycle + 1) lrs = [] param_lrs = zip(self.optimizer.param_groups, self.base_lrs, self.max_lrs) for param_group, base_lr, max_lr in param_lrs: base_height =(max_lr - base_lr)* np.maximum(0,(1 - x)) if self.scale_mode == 'cycle': lr = base_lr + base_height * self.scale_fn(cycle) else: lr = base_lr + base_height * self.scale_fn(self.last_batch_iteration) lrs.append(lr) return lrs <choose_model_class>
test_data['Sex'] = test_data['Sex'].replace(['male', 'female'],[1,0]) test_data.rename(columns = {'Sex' : 'gender'}, inplace = True )
Titanic - Machine Learning from Disaster
14,646,784
embedding_dim = 300 embedding_path = '.. /save/embedding_matrix.npy' use_pretrained_embedding = True hidden_size = 60 gru_len = hidden_size Routings = 4 Num_capsule = 5 Dim_capsule = 5 dropout_p = 0.25 rate_drop_dense = 0.28 LR = 0.001 T_epsilon = 1e-7 num_classes = 30 class Embed_Layer(nn.Module): def __init__(self, embedding_matrix=None, vocab_size=None, embedding_dim=300): super(Embed_Layer, self ).__init__() self.encoder = nn.Embedding(vocab_size + 1, embedding_dim) if use_pretrained_embedding: self.encoder.weight.data.copy_(t.from_numpy(embedding_matrix)) def forward(self, x, dropout_p=0.25): return nn.Dropout(p=dropout_p )(self.encoder(x)) class GRU_Layer(nn.Module): def __init__(self): super(GRU_Layer, self ).__init__() self.gru = nn.GRU(input_size=300, hidden_size=gru_len, bidirectional=True) def init_weights(self): ih =(param.data for name, param in self.named_parameters() if 'weight_ih' in name) hh =(param.data for name, param in self.named_parameters() if 'weight_hh' in name) b =(param.data for name, param in self.named_parameters() if 'bias' in name) for k in ih: nn.init.xavier_uniform_(k) for k in hh: nn.init.orthogonal_(k) for k in b: nn.init.constant_(k, 0) def forward(self, x): return self.gru(x) class Caps_Layer(nn.Module): def __init__(self, input_dim_capsule=gru_len * 2, num_capsule=Num_capsule, dim_capsule=Dim_capsule, \ routings=Routings, kernel_size=(9, 1), share_weights=True, activation='default', **kwargs): super(Caps_Layer, self ).__init__(**kwargs) self.num_capsule = num_capsule self.dim_capsule = dim_capsule self.routings = routings self.kernel_size = kernel_size self.share_weights = share_weights if activation == 'default': self.activation = self.squash else: self.activation = nn.ReLU(inplace=True) if self.share_weights: self.W = nn.Parameter( nn.init.xavier_normal_(t.empty(1, input_dim_capsule, self.num_capsule * self.dim_capsule))) else: self.W = nn.Parameter( t.randn(BATCH_SIZE, input_dim_capsule, self.num_capsule * self.dim_capsule)) def forward(self, x): if self.share_weights: u_hat_vecs = t.matmul(x, self.W) else: print('add later') batch_size = x.size(0) input_num_capsule = x.size(1) u_hat_vecs = u_hat_vecs.view(( batch_size, input_num_capsule, self.num_capsule, self.dim_capsule)) u_hat_vecs = u_hat_vecs.permute(0, 2, 1, 3) b = t.zeros_like(u_hat_vecs[:, :, :, 0]) for i in range(self.routings): b = b.permute(0, 2, 1) c = F.softmax(b, dim=2) c = c.permute(0, 2, 1) b = b.permute(0, 2, 1) outputs = self.activation(t.einsum('bij,bijk->bik',(c, u_hat_vecs))) if i < self.routings - 1: b = t.einsum('bik,bijk->bij',(outputs, u_hat_vecs)) return outputs def squash(self, x, axis=-1): s_squared_norm =(x ** 2 ).sum(axis, keepdim=True) scale = t.sqrt(s_squared_norm + T_epsilon) return x / scale class Capsule_Main(nn.Module): def __init__(self, embedding_matrix=None, vocab_size=None): super(Capsule_Main, self ).__init__() self.embed_layer = Embed_Layer(embedding_matrix, vocab_size) self.gru_layer = GRU_Layer() self.gru_layer.init_weights() self.caps_layer = Caps_Layer() self.dense_layer = Dense_Layer() def forward(self, content): content1 = self.embed_layer(content) content2, _ = self.gru_layer( content1) content3 = self.caps_layer(content2) output = self.dense_layer(content3) return output <normalization>
test_data['Embarked'] = test_data['Embarked'].replace(['S','C','Q'],[0,1,2]) test_data.rename(columns = {'Embarked' : 'port'}, inplace = True )
Titanic - Machine Learning from Disaster
14,646,784
class Attention(nn.Module): def __init__(self, feature_dim, step_dim, bias=True, **kwargs): super(Attention, self ).__init__(**kwargs) self.supports_masking = True self.bias = bias self.feature_dim = feature_dim self.step_dim = step_dim self.features_dim = 0 weight = torch.zeros(feature_dim, 1) nn.init.xavier_uniform_(weight) self.weight = nn.Parameter(weight) if bias: self.b = nn.Parameter(torch.zeros(step_dim)) def forward(self, x, mask=None): feature_dim = self.feature_dim step_dim = self.step_dim eij = torch.mm( x.contiguous().view(-1, feature_dim), self.weight ).view(-1, step_dim) if self.bias: eij = eij + self.b eij = torch.tanh(eij) a = torch.exp(eij) if mask is not None: a = a * mask a = a / torch.sum(a, 1, keepdim=True)+ 1e-10 weighted_input = x * torch.unsqueeze(a, -1) return torch.sum(weighted_input, 1) class NeuralNet(nn.Module): def __init__(self): super(NeuralNet, self ).__init__() fc_layer = 16 fc_layer1 = 16 self.embedding = nn.Embedding(max_features, embed_size) self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32)) self.embedding.weight.requires_grad = False self.embedding_dropout = nn.Dropout2d(0.1) self.lstm = nn.LSTM(embed_size, hidden_size, bidirectional=True, batch_first=True) self.gru = nn.GRU(hidden_size * 2, hidden_size, bidirectional=True, batch_first=True) self.lstm2 = nn.LSTM(hidden_size * 2, hidden_size, bidirectional=True, batch_first=True) self.lstm_attention = Attention(hidden_size * 2, maxlen) self.gru_attention = Attention(hidden_size * 2, maxlen) self.bn = nn.BatchNorm1d(16, momentum=0.5) self.linear = nn.Linear(hidden_size*8+3, fc_layer1) self.relu = nn.ReLU() self.dropout = nn.Dropout(0.1) self.fc = nn.Linear(fc_layer**2,fc_layer) self.out = nn.Linear(fc_layer, 1) self.lincaps = nn.Linear(Num_capsule * Dim_capsule, 1) self.caps_layer = Caps_Layer() def forward(self, x): h_embedding = self.embedding(x[0]) h_embedding = torch.squeeze( self.embedding_dropout(torch.unsqueeze(h_embedding, 0))) h_lstm, _ = self.lstm(h_embedding) h_gru, _ = self.gru(h_lstm) content3 = self.caps_layer(h_gru) content3 = self.dropout(content3) batch_size = content3.size(0) content3 = content3.view(batch_size, -1) content3 = self.relu(self.lincaps(content3)) h_lstm_atten = self.lstm_attention(h_lstm) h_gru_atten = self.gru_attention(h_gru) avg_pool = torch.mean(h_gru, 1) max_pool, _ = torch.max(h_gru, 1) f = torch.tensor(x[1], dtype=torch.float ).cuda() conc = torch.cat(( h_lstm_atten, h_gru_atten,content3, avg_pool, max_pool,f), 1) conc = self.relu(self.linear(conc)) conc = self.bn(conc) conc = self.dropout(conc) out = self.out(conc) return out<categorify>
test_data.rename(columns = {'Pclass' : 'passenger cls'} )
Titanic - Machine Learning from Disaster
14,646,784
class MyDataset(Dataset): def __init__(self,dataset): self.dataset = dataset def __getitem__(self, index): data, target = self.dataset[index] return data, target, index def __len__(self): return len(self.dataset )<compute_train_metric>
test_data['family_members'] = test_data['SibSp'] + test_data['Parch'] test_data.drop(['SibSp', 'Parch'], axis = 1, inplace=True )
Titanic - Machine Learning from Disaster
14,646,784
class FocalLoss(nn.Module): def __init__(self, alpha=1, gamma=2, logits=True, reduction='elementwise_mean'): super(FocalLoss, self ).__init__() self.alpha = alpha self.gamma = gamma self.logits = logits self.reduction = reduction def forward(self, inputs, targets): if self.logits: BCE_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction='none') else: BCE_loss = F.binary_cross_entropy(inputs, targets, reduction='none') pt = torch.exp(-BCE_loss) F_loss = self.alpha *(1-pt)**self.gamma * BCE_loss if self.reduction is None: return F_loss else: return torch.mean(F_loss )<define_variables>
test_data.loc[ test_data['Age'] <= 21, 'Age'] = 0 test_data.loc[(test_data['Age'] > 21)&(test_data['Age'] <= 34), 'Age'] = 1 test_data.loc[(test_data['Age'] > 34)&(test_data['Age'] <= 54), 'Age'] = 2 test_data.loc[(test_data['Age'] > 60)&(test_data['Age'] <= 75), 'Age'] = 3 test_data.loc[ test_data['Age'] > 75, 'Age'] ;
Titanic - Machine Learning from Disaster
14,646,784
def sigmoid(x): return 1 /(1 + np.exp(-x)) train_preds = np.zeros(( len(x_train))) test_preds = np.zeros(( len(df_test))) seed_everything() x_test_cuda = torch.tensor(x_test, dtype=torch.long ).cuda() test = torch.utils.data.TensorDataset(x_test_cuda) test_loader = torch.utils.data.DataLoader(test, batch_size=batch_size, shuffle=False) avg_losses_f = [] avg_val_losses_f = []<data_type_conversions>
test_data.loc[ test_data['Fare'] <= 7.5, 'Fare'] = 0 test_data.loc[(test_data['Fare'] > 15)&(test_data['Fare'] <= 21.5), 'Fare'] = 1 test_data.loc[(test_data['Fare'] > 21.5)&(test_data['Age'] <= 29), 'Fare'] = 2 test_data.loc[(test_data['Fare'] > 29)&(test_data['Fare'] <= 36.5), 'Fare'] = 3 test_data.loc[ test_data['Fare'] > 36.5, 'Fare'] ;
Titanic - Machine Learning from Disaster
14,646,784
for i,(train_idx, valid_idx)in enumerate(splits): x_train = np.array(x_train) y_train = np.array(y_train) features = np.array(features) x_train_fold = torch.tensor(x_train[train_idx.astype(int)], dtype=torch.long ).cuda() y_train_fold = torch.tensor(y_train[train_idx.astype(int), np.newaxis], dtype=torch.float32 ).cuda() kfold_X_features = features[train_idx.astype(int)] kfold_X_valid_features = features[valid_idx.astype(int)] x_val_fold = torch.tensor(x_train[valid_idx.astype(int)], dtype=torch.long ).cuda() y_val_fold = torch.tensor(y_train[valid_idx.astype(int), np.newaxis], dtype=torch.float32 ).cuda() model = NeuralNet() model.cuda() gamma = 1.1 + i/16 loss_fn = FocalLoss(gamma=gamma) step_size = 300 base_lr, max_lr = 0.001, 0.003 optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=max_lr) scheduler = CyclicLR(optimizer, base_lr=base_lr, max_lr=max_lr, step_size=step_size, mode='exp_range', gamma=0.99994) train = torch.utils.data.TensorDataset(x_train_fold, y_train_fold) valid = torch.utils.data.TensorDataset(x_val_fold, y_val_fold) train = MyDataset(train) valid = MyDataset(valid) train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True) valid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False) print(f'Fold {i + 1}') for epoch in range(n_epochs): start_time = time.time() model.train() avg_loss = 0. for i,(x_batch, y_batch, index)in enumerate(train_loader): f = kfold_X_features[index] y_pred = model([x_batch,f]) if scheduler: scheduler.batch_step() loss = loss_fn(y_pred, y_batch) optimizer.zero_grad() loss.backward() optimizer.step() avg_loss += loss.item() / len(train_loader) model.eval() valid_preds_fold = np.zeros(( x_val_fold.size(0))) test_preds_fold = np.zeros(( len(df_test))) avg_val_loss = 0. for i,(x_batch, y_batch, index)in enumerate(valid_loader): f = kfold_X_valid_features[index] y_pred = model([x_batch,f] ).detach() avg_val_loss += loss_fn(y_pred, y_batch ).item() / len(valid_loader) valid_preds_fold[i * batch_size:(i+1)* batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0] elapsed_time = time.time() - start_time print('Epoch {}/{} \t loss={:.4f} \t val_loss={:.4f} \t time={:.2f}s'.format( epoch + 1, n_epochs, avg_loss, avg_val_loss, elapsed_time)) avg_losses_f.append(avg_loss) avg_val_losses_f.append(avg_val_loss) for i,(x_batch,)in enumerate(test_loader): f = test_features[i * batch_size:(i+1)* batch_size] y_pred = model([x_batch,f] ).detach() test_preds_fold[i * batch_size:(i+1)* batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0] train_preds[valid_idx] = valid_preds_fold test_preds += test_preds_fold / len(splits) print('All \t loss={:.4f} \t val_loss={:.4f} \t '.format(np.average(avg_losses_f),np.average(avg_val_losses_f))) <compute_test_metric>
x = train_data.drop("Survived", axis = 1 )
Titanic - Machine Learning from Disaster
14,646,784
def bestThresshold(y_train,train_preds): tmp = [0,0,0] delta = 0 for tmp[0] in tqdm(np.arange(0.3, 0.601, 0.001)) : tmp[1] = f1_score(y_train, np.array(train_preds)>tmp[0]) if tmp[1] > tmp[2]: delta = tmp[0] tmp[2] = tmp[1] print('best threshold is {:.4f} with F1 score: {:.4f}'.format(delta, tmp[2])) return delta delta = bestThresshold(y_train,train_preds )<save_to_csv>
y = train_data["Survived"]
Titanic - Machine Learning from Disaster
14,646,784
submission = df_test[['qid']].copy() submission['prediction'] =(test_preds > delta ).astype(int) submission.to_csv('submission.csv', index=False )<set_options>
from sklearn.model_selection import train_test_split
Titanic - Machine Learning from Disaster
14,646,784
%matplotlib inline pd.set_option('max_colwidth',400) warnings.filterwarnings("ignore", message="F-score is ill-defined and being set to 0.0 due to no predicted samples.") <set_options>
from sklearn.model_selection import train_test_split
Titanic - Machine Learning from Disaster
14,646,784
def seed_torch(seed=1029): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True<load_from_csv>
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.4, random_state = 12 )
Titanic - Machine Learning from Disaster
14,646,784
train = pd.read_csv(".. /input/train.csv") test = pd.read_csv(".. /input/test.csv") sub = pd.read_csv('.. /input/sample_submission.csv' )<count_values>
dtree = DecisionTreeClassifier() dtree.fit(x_train, y_train) y_pred = dtree.predict(x_test) dtree_accuracy = round(accuracy_score(y_pred, y_test)* 100, 2) print(dtree_accuracy )
Titanic - Machine Learning from Disaster
14,646,784
train["target"].value_counts()<split>
randomforest = RandomForestClassifier(n_estimators=30, max_depth = 4) randomforest.fit(x_train, y_train) y_pred = randomforest.predict(x_test) acc_randomforest = round(accuracy_score(y_pred, y_test)* 100, 2) print(acc_randomforest )
Titanic - Machine Learning from Disaster
14,646,784
print('Average word length of questions in train is {0:.0f}.'.format(np.mean(train['question_text'].apply(lambda x: len(x.split()))))) print('Average word length of questions in test is {0:.0f}.'.format(np.mean(test['question_text'].apply(lambda x: len(x.split())))) )<string_transform>
logreg = LogisticRegression(solver='liblinear', dual = False) logreg.fit(x_train, y_train) y_pred = logreg.predict(x_test) acc_log = round(logreg.score(x_train, y_train)* 100, 2) acc_log accuracy_score(y_test, y_pred )
Titanic - Machine Learning from Disaster
14,646,784
print('Max word length of questions in train is {0:.0f}.'.format(np.max(train['question_text'].apply(lambda x: len(x.split()))))) print('Max word length of questions in test is {0:.0f}.'.format(np.max(test['question_text'].apply(lambda x: len(x.split())))) )<compute_test_metric>
dt = RandomForestClassifier(n_estimators=30, max_depth = 4 )
Titanic - Machine Learning from Disaster
14,646,784
print('Average character length of questions in train is {0:.0f}.'.format(np.mean(train['question_text'].apply(lambda x: len(x))))) print('Average character length of questions in test is {0:.0f}.'.format(np.mean(test['question_text'].apply(lambda x: len(x)))) )<train_model>
dt.fit(x_train, y_train )
Titanic - Machine Learning from Disaster
14,646,784
max_features = 120000 tk = Tokenizer(lower = True, filters='', num_words=max_features) full_text = list(train['question_text'].values)+ list(test['question_text'].values) tk.fit_on_texts(full_text )<string_transform>
y_test_predict = dt.predict(x_test )
Titanic - Machine Learning from Disaster
14,646,784
train_tokenized = tk.texts_to_sequences(train['question_text'].fillna('missing')) test_tokenized = tk.texts_to_sequences(test['question_text'].fillna('missing'))<categorify>
print(classification_report(y_test, y_test_predict))
Titanic - Machine Learning from Disaster
14,646,784
max_len = 72 maxlen = 72 X_train = pad_sequences(train_tokenized, maxlen = max_len) X_test = pad_sequences(test_tokenized, maxlen = max_len )<prepare_x_and_y>
x_test = test_data
Titanic - Machine Learning from Disaster
14,646,784
y_train = train['target'].values<compute_test_metric>
y_test_predict = dt.predict(test_data )
Titanic - Machine Learning from Disaster
14,646,784
<split><EOS>
output_data = pd.DataFrame({'PassengerId' : test_data.PassengerId, 'Survived' : y_test_predict}) output_data.to_csv('Titanic_Survival_Decision_Tree', index = False) print("Submission is successfully" )
Titanic - Machine Learning from Disaster
14,395,164
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<statistical_test>
import pandas as pd from sklearn.tree import DecisionTreeClassifier
Titanic - Machine Learning from Disaster
14,395,164
embed_size = 300 embedding_path = ".. /input/embeddings/glove.840B.300d/glove.840B.300d.txt" def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embedding_index = dict(get_coefs(*o.split(" ")) for o in open(embedding_path, encoding='utf-8', errors='ignore')) emb_mean,emb_std = -0.005838499, 0.48782197 word_index = tk.word_index nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words + 1, embed_size)) for word, i in word_index.items() : if i >= max_features: continue embedding_vector = embedding_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector<compute_train_metric>
train = pd.read_csv('.. /input/titanic/train.csv') test = pd.read_csv('.. /input/titanic/test.csv' )
Titanic - Machine Learning from Disaster
14,395,164
embedding_path = ".. /input/embeddings/paragram_300_sl999/paragram_300_sl999.txt" def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embedding_index = dict(get_coefs(*o.split(" ")) for o in open(embedding_path, encoding='utf-8', errors='ignore')if len(o)>100) emb_mean,emb_std = -0.0053247833, 0.49346462 embedding_matrix1 = np.random.normal(emb_mean, emb_std,(nb_words + 1, embed_size)) for word, i in word_index.items() : if i >= max_features: continue embedding_vector = embedding_index.get(word) if embedding_vector is not None: embedding_matrix1[i] = embedding_vector<compute_test_metric>
train = train.drop(["Name", "Ticket", "Cabin"], axis=1) test = test.drop(["Name", "Ticket", "Cabin"], axis=1 )
Titanic - Machine Learning from Disaster
14,395,164
embedding_matrix = np.mean([embedding_matrix, embedding_matrix1], axis=0) del embedding_matrix1<normalization>
new_data_train = pd.get_dummies(train) new_data_test = pd.get_dummies(test )
Titanic - Machine Learning from Disaster
14,395,164
class Attention(nn.Module): def __init__(self, feature_dim, step_dim, bias=True, **kwargs): super(Attention, self ).__init__(**kwargs) self.supports_masking = True self.bias = bias self.feature_dim = feature_dim self.step_dim = step_dim self.features_dim = 0 weight = torch.zeros(feature_dim, 1) nn.init.xavier_uniform_(weight) self.weight = nn.Parameter(weight) if bias: self.b = nn.Parameter(torch.zeros(step_dim)) def forward(self, x, mask=None): feature_dim = self.feature_dim step_dim = self.step_dim eij = torch.mm( x.contiguous().view(-1, feature_dim), self.weight ).view(-1, step_dim) if self.bias: eij = eij + self.b eij = torch.tanh(eij) a = torch.exp(eij) if mask is not None: a = a * mask a = a / torch.sum(a, 1, keepdim=True)+ 1e-10 weighted_input = x * torch.unsqueeze(a, -1) return torch.sum(weighted_input, 1) class NeuralNet(nn.Module): def __init__(self): super(NeuralNet, self ).__init__() hidden_size = 128 self.embedding = nn.Embedding(max_features, embed_size) self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32)) self.embedding.weight.requires_grad = False self.embedding_dropout = nn.Dropout2d(0.1) self.lstm = nn.LSTM(embed_size, hidden_size, bidirectional=True, batch_first=True) self.gru = nn.GRU(hidden_size*2, hidden_size, bidirectional=True, batch_first=True) self.lstm_attention = Attention(hidden_size*2, maxlen) self.gru_attention = Attention(hidden_size*2, maxlen) self.linear = nn.Linear(1024, 16) self.relu = nn.ReLU() self.dropout = nn.Dropout(0.1) self.out = nn.Linear(16, 1) def forward(self, x): h_embedding = self.embedding(x) h_embedding = torch.squeeze(self.embedding_dropout(torch.unsqueeze(h_embedding, 0))) h_lstm, _ = self.lstm(h_embedding) h_gru, _ = self.gru(h_lstm) h_lstm_atten = self.lstm_attention(h_lstm) h_gru_atten = self.gru_attention(h_gru) avg_pool = torch.mean(h_gru, 1) max_pool, _ = torch.max(h_gru, 1) conc = torch.cat(( h_lstm_atten, h_gru_atten, avg_pool, max_pool), 1) conc = self.relu(self.linear(conc)) conc = self.dropout(conc) out = self.out(conc) return out<choose_model_class>
new_data_train.isnull().sum().sort_values(ascending=False ).head(10 )
Titanic - Machine Learning from Disaster
14,395,164
m = NeuralNet()<train_model>
new_data_train["Age"].fillna(new_data_train["Age"].mean() , inplace=True) new_data_test["Age"].fillna(new_data_test["Age"].mean() , inplace=True )
Titanic - Machine Learning from Disaster
14,395,164
def train_model(model, x_train, y_train, x_val, y_val, validate=True): optimizer = torch.optim.Adam(model.parameters()) train = torch.utils.data.TensorDataset(x_train, y_train) valid = torch.utils.data.TensorDataset(x_val, y_val) train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True) valid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False) loss_fn = torch.nn.BCEWithLogitsLoss(reduction='mean' ).cuda() best_score = -np.inf for epoch in range(n_epochs): start_time = time.time() model.train() avg_loss = 0. for x_batch, y_batch in tqdm(train_loader, disable=True): y_pred = model(x_batch) loss = loss_fn(y_pred, y_batch) optimizer.zero_grad() loss.backward() optimizer.step() avg_loss += loss.item() / len(train_loader) model.eval() valid_preds = np.zeros(( x_val_fold.size(0))) if validate: avg_val_loss = 0. for i,(x_batch, y_batch)in enumerate(valid_loader): y_pred = model(x_batch ).detach() avg_val_loss += loss_fn(y_pred, y_batch ).item() / len(valid_loader) valid_preds[i * batch_size:(i+1)* batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0] search_result = threshold_search(y_val.cpu().numpy() , valid_preds) val_f1, val_threshold = search_result['f1'], search_result['threshold'] elapsed_time = time.time() - start_time print('Epoch {}/{} \t loss={:.4f} \t val_loss={:.4f} \t val_f1={:.4f} best_t={:.2f} \t time={:.2f}s'.format( epoch + 1, n_epochs, avg_loss, avg_val_loss, val_f1, val_threshold, elapsed_time)) else: elapsed_time = time.time() - start_time print('Epoch {}/{} \t loss={:.4f} \t time={:.2f}s'.format( epoch + 1, n_epochs, avg_loss, elapsed_time)) valid_preds = np.zeros(( x_val_fold.size(0))) avg_val_loss = 0. for i,(x_batch, y_batch)in enumerate(valid_loader): y_pred = model(x_batch ).detach() avg_val_loss += loss_fn(y_pred, y_batch ).item() / len(valid_loader) valid_preds[i * batch_size:(i+1)* batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0] print('Validation loss: ', avg_val_loss) test_preds = np.zeros(( len(test_loader.dataset))) for i,(x_batch,)in enumerate(test_loader): y_pred = model(x_batch ).detach() test_preds[i * batch_size:(i+1)* batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0] return valid_preds, test_preds<create_dataframe>
new_data_test.isnull().sum().sort_values(ascending=False ).head(10 )
Titanic - Machine Learning from Disaster
14,395,164
x_test_cuda = torch.tensor(X_test, dtype=torch.long ).cuda() test = torch.utils.data.TensorDataset(x_test_cuda) batch_size = 512 test_loader = torch.utils.data.DataLoader(test, batch_size=batch_size, shuffle=False )<compute_train_metric>
new_data_test["Fare"].fillna(new_data_test["Fare"].mean() , inplace=True )
Titanic - Machine Learning from Disaster
14,395,164
seed=1029 def threshold_search(y_true, y_proba): best_threshold = 0 best_score = 0 for threshold in tqdm([i * 0.01 for i in range(100)], disable=True): score = f1_score(y_true=y_true, y_pred=y_proba > threshold) if score > best_score: best_threshold = threshold best_score = score search_result = {'threshold': best_threshold, 'f1': best_score} return search_result def seed_everything(seed=1234): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True seed_everything()<prepare_x_and_y>
X = new_data_train.drop("Survived", axis=1) y = new_data_train["Survived"]
Titanic - Machine Learning from Disaster
14,395,164
train_preds = np.zeros(len(train)) test_preds = np.zeros(( len(test), len(splits))) n_epochs = 5 for i,(train_idx, valid_idx)in enumerate(splits): x_train_fold = torch.tensor(X_train[train_idx], dtype=torch.long ).cuda() y_train_fold = torch.tensor(y_train[train_idx, np.newaxis], dtype=torch.float32 ).cuda() x_val_fold = torch.tensor(X_train[valid_idx], dtype=torch.long ).cuda() y_val_fold = torch.tensor(y_train[valid_idx, np.newaxis], dtype=torch.float32 ).cuda() train = torch.utils.data.TensorDataset(x_train_fold, y_train_fold) valid = torch.utils.data.TensorDataset(x_val_fold, y_val_fold) train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True) valid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False) print(f'Fold {i + 1}') seed_everything(seed + i) model = NeuralNet() model.cuda() valid_preds_fold, test_preds_fold = train_model(model, x_train_fold, y_train_fold, x_val_fold, y_val_fold, validate=False) train_preds[valid_idx] = valid_preds_fold test_preds[:, i] = test_preds_fold<save_to_csv>
tree = DecisionTreeClassifier(max_depth = 10, random_state = 0) tree.fit(X, y )
Titanic - Machine Learning from Disaster
14,395,164
search_result = threshold_search(y_train, train_preds) sub['prediction'] = test_preds.mean(1)> search_result['threshold'] sub.to_csv("submission.csv", index=False )<import_modules>
tree.score(X, y)
Titanic - Machine Learning from Disaster
14,395,164
tqdm.pandas(desc='Progress') <define_variables>
from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split
Titanic - Machine Learning from Disaster
14,395,164
embed_size = 300 max_features = 120000 maxlen = 70 batch_size = 512 n_epochs = 5 n_splits = 5 SEED = 1029<set_options>
Xtrain, Xvalidation, Ytrain, Yvalidation = train_test_split(X, y, test_size=0.2, random_state=True )
Titanic - Machine Learning from Disaster
14,395,164
def seed_everything(seed=1029): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True seed_everything()<features_selection>
model = RandomForestClassifier(n_estimators=100, max_leaf_nodes=12, max_depth=12, random_state=0) model.fit(Xtrain, Ytrain )
Titanic - Machine Learning from Disaster
14,395,164
def load_glove(word_index): EMBEDDING_FILE = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')[:300] embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = -0.005838499,0.48782197 embed_size = all_embs.shape[1] nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size)) for word, i in word_index.items() : if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix def load_fasttext(word_index): EMBEDDING_FILE = '.. /input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)if len(o)>100) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = all_embs.mean() , all_embs.std() embed_size = all_embs.shape[1] nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size)) for word, i in word_index.items() : if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix def load_para(word_index): EMBEDDING_FILE = '.. /input/embeddings/paragram_300_sl999/paragram_300_sl999.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE, encoding="utf8", errors='ignore')if len(o)>100) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = -0.0053247833,0.49346462 embed_size = all_embs.shape[1] nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size)) for word, i in word_index.items() : if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix<load_from_csv>
model.score(Xtrain, Ytrain )
Titanic - Machine Learning from Disaster
14,395,164
df_train = pd.read_csv(".. /input/train.csv") df_test = pd.read_csv(".. /input/test.csv") df = pd.concat([df_train ,df_test],sort=True )<feature_engineering>
Yprediction = model.predict(Xvalidation) accuracy_score(Yvalidation, Yprediction )
Titanic - Machine Learning from Disaster
14,395,164
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 vocab = build_vocab(df['question_text'] )<define_variables>
submission = pd.DataFrame() submission["PassengerId"] = Xtest["PassengerId"] submission["Survived"] = model.predict(Xtest) submission.to_csv("submission.csv", index=False )
Titanic - Machine Learning from Disaster
14,261,262
sin = len(df_train[df_train["target"]==0]) insin = len(df_train[df_train["target"]==1]) persin =(sin/(sin+insin)) *100 perinsin =(insin/(sin+insin)) *100 print(" print("<feature_engineering>
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt
Titanic - Machine Learning from Disaster
14,261,262
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 def known_contractions(embed): known = [] for contract in contraction_mapping: if contract in embed: known.append(contract) return known 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 def correct_spelling(x, dic): for word in dic.keys() : x = x.replace(word, dic[word]) return x def unknown_punct(embed, punct): unknown = '' for p in punct: if p not in embed: unknown += p unknown += ' ' return unknown def clean_numbers(x): x = re.sub('[0-9]{5,}', ' x = re.sub('[0-9]{4}', ' x = re.sub('[0-9]{3}', ' x = re.sub('[0-9]{2}', ' return x 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 def add_lower(embedding, vocab): count = 0 for word in vocab: if word in embedding and word.lower() not in embedding: embedding[word.lower() ] = embedding[word] count += 1 print(f"Added {count} words to embedding" )<define_variables>
train_df = pd.read_csv('/kaggle/input/titanic/train.csv') test_df = pd.read_csv('/kaggle/input/titanic/test.csv') dataset = [train_df, test_df] dataset[0].head()
Titanic - Machine Learning from Disaster
14,261,262
puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', ' '·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…', '“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾', '═', '¦', '║', '―', '¥', '▓', '—', '‹', '─', '▒', ':', '¼', '⊕', '▼', '▪', '†', '■', '’', '▀', '¨', '▄', '♫', '☆', 'é', '¯', '♦', '¤', '▲', 'è', '¸', '¾', 'Ã', '⋅', '‘', '∞', '∙', ')', '↓', '、', '│', '(', '»', ',', '♪', '╩', '╚', '³', '・', '╦', '╣', '╔', '╗', '▬', '❤', 'ï', 'Ø', '¹', '≤', '‡', '√', ] def clean_text(x): x = str(x) for punct in puncts: x = x.replace(punct, f' {punct} ') return x def clean_numbers(x): x = re.sub('[0-9]{5,}', ' x = re.sub('[0-9]{4}', ' x = re.sub('[0-9]{3}', ' x = re.sub('[0-9]{2}', ' return x mispell_dict = {"ain't": "is not", "aren't": "are not","can't": "cannot", "'cause": "because", "could've": "could have", "couldn't": "could not", "didn't": "did not", "doesn't": "does not", "don't": "do not", "hadn't": "had not", "hasn't": "has not", "haven't": "have not", "he'd": "he would","he'll": "he will", "he's": "he is", "how'd": "how did", "how'd'y": "how do you", "how'll": "how will", "how's": "how is", "I'd": "I would", "I'd've": "I would have", "I'll": "I will", "I'll've": "I will have","I'm": "I am", "I've": "I have", "i'd": "i would", "i'd've": "i would have", "i'll": "i will", "i'll've": "i will have","i'm": "i am", "i've": "i have", "isn't": "is not", "it'd": "it would", "it'd've": "it would have", "it'll": "it will", "it'll've": "it will have","it's": "it is", "let's": "let us", "ma'am": "madam", "mayn't": "may not", "might've": "might have","mightn't": "might not","mightn't've": "might not have", "must've": "must have", "mustn't": "must not", "mustn't've": "must not have", "needn't": "need not", "needn't've": "need not have","o'clock": "of the clock", "oughtn't": "ought not", "oughtn't've": "ought not have", "shan't": "shall not", "sha'n't": "shall not", "shan't've": "shall not have", "she'd": "she would", "she'd've": "she would have", "she'll": "she will", "she'll've": "she will have", "she's": "she is", "should've": "should have", "shouldn't": "should not", "shouldn't've": "should not have", "so've": "so have","so's": "so as", "this's": "this is","that'd": "that would", "that'd've": "that would have", "that's": "that is", "there'd": "there would", "there'd've": "there would have", "there's": "there is", "here's": "here is","they'd": "they would", "they'd've": "they would have", "they'll": "they will", "they'll've": "they will have", "they're": "they are", "they've": "they have", "to've": "to have", "wasn't": "was not", "we'd": "we would", "we'd've": "we would have", "we'll": "we will", "we'll've": "we will have", "we're": "we are", "we've": "we have", "weren't": "were not", "what'll": "what will", "what'll've": "what will have", "what're": "what are", "what's": "what is", "what've": "what have", "when's": "when is", "when've": "when have", "where'd": "where did", "where's": "where is", "where've": "where have", "who'll": "who will", "who'll've": "who will have", "who's": "who is", "who've": "who have", "why's": "why is", "why've": "why have", "will've": "will have", "won't": "will not", "won't've": "will not have", "would've": "would have", "wouldn't": "would not", "wouldn't've": "would not have", "y'all": "you all", "y'all'd": "you all would","y'all'd've": "you all would have","y'all're": "you all are","y'all've": "you all have","you'd": "you would", "you'd've": "you would have", "you'll": "you will", "you'll've": "you will have", "you're": "you are", "you've": "you have", 'colour': 'color', 'centre': 'center', 'favourite': 'favorite', 'travelling': 'traveling', 'counselling': 'counseling', 'theatre': 'theater', 'cancelled': 'canceled', 'labour': 'labor', 'organisation': 'organization', 'wwii': 'world war 2', 'citicise': 'criticize', 'youtu ': 'youtube ', 'Qoura': 'Quora', 'sallary': 'salary', 'Whta': 'What', 'narcisist': 'narcissist', 'howdo': 'how do', 'whatare': 'what are', 'howcan': 'how can', 'howmuch': 'how much', 'howmany': 'how many', 'whydo': 'why do', 'doI': 'do I', 'theBest': 'the best', 'howdoes': 'how does', 'mastrubation': 'masturbation', 'mastrubate': 'masturbate', "mastrubating": 'masturbating', 'pennis': 'penis', 'Etherium': 'Ethereum', 'narcissit': 'narcissist', 'bigdata': 'big data', '2k17': '2017', '2k18': '2018', 'qouta': 'quota', 'exboyfriend': 'ex boyfriend', 'airhostess': 'air hostess', "whst": 'what', 'watsapp': 'whatsapp', 'demonitisation': 'demonetization', 'demonitization': 'demonetization', 'demonetisation': 'demonetization'} def _get_mispell(mispell_dict): mispell_re = re.compile('(%s)' % '|'.join(mispell_dict.keys())) return mispell_dict, mispell_re mispellings, mispellings_re = _get_mispell(mispell_dict) def replace_typical_misspell(text): def replace(match): return mispellings[match.group(0)] return mispellings_re.sub(replace, text )<feature_engineering>
for df in dataset: df.Sex = df.Sex.map({'male':0, 'female': 1}) train_df.Sex.unique()
Titanic - Machine Learning from Disaster