kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
5,616,085
train_df["question_text"] = train_df["question_text"].map(lambda x: clean_punctuation(x)).str.replace('\d+', ' test_df["question_text"] = test_df["question_text"].map(lambda x: clean_punctuation(x)).str.replace('\d+', ' vocab = get_vocab(train_df["question_text"]) out_of_vocab = check_coverage(vocab, embeddings_index ...
model_param_grid = {}
Titanic - Machine Learning from Disaster
5,616,085
maxlen = 65 max_features = 60000 train_df, val_df = train_test_split(train_df, test_size=0.1, random_state=201901) train_X = train_df["question_text"].fillna("_ val_X = val_df["question_text"].fillna("_ test_X = test_df["question_text"].fillna("_ tokenizer = Tokenizer(num_words=max_features) tokenizer.fit_on_texts(li...
model_param_grid['LogisticRegression'] = {'penalty' : ['l1', 'l2'], 'C' : np.logspace(0, 4, 10)}
Titanic - Machine Learning from Disaster
5,616,085
def prepare_embedding_matrix(embeddings_index,word_index,num_words): all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = all_embs.mean() , all_embs.std() embed_size = all_embs.shape[1] embedding_matrix = np.random.normal(emb_mean, emb_std,(num_words, embed_size)) for word, i in word_index.items() : if i ...
model_param_grid['SVC'] = [{'kernel': ['rbf'], 'gamma': [1e-2, 1e-3, 1e-4, 1e-5], 'C': [0.001, 0.10, 0.1, 10, 25, 50, 100, 1000]}, {'kernel': ['sigmoid'], 'gamma': [1e-2, 1e-3, 1e-4, 1e-5], 'C': [0.001, 0.10, 0.1, 10, 25, 50, 100, 1000]}, {'kernel': ['linear'], 'C': [0.001, 0.10, 0.1, 10, 25, 50, 100, 1000]}, {'kernel'...
Titanic - Machine Learning from Disaster
5,616,085
EMBEDDING_DIM = 300 word_index = tokenizer.word_index num_words = min(max_features, len(word_index)+ 1) embedding_matrix = prepare_embedding_matrix(embeddings_index,word_index,num_words )<set_options>
model_param_grid['DecisionTreeClassifier'] = {'criterion' : ["gini","entropy"], 'max_features': ['auto', 'sqrt', 'log2'], 'min_samples_split': [10,11,12,13,14,15], 'min_samples_leaf':[1,2,3,4,5,6,7]}
Titanic - Machine Learning from Disaster
5,616,085
class Attention(Layer): def __init__(self, step_dim, W_regularizer=None, b_regularizer=None, W_constraint=None, b_constraint=None, bias=True, **kwargs): self.supports_masking = True self.init = initializers.get('glorot_uniform') self.W_regularizer = regularizers.get(W_regularizer) self.b_regularizer = regularizers.ge...
model_param_grid['RandomForestClassifier'] = {'n_estimators' : [50,100,150,200], 'criterion' : ["gini","entropy"], 'max_features': ['auto', 'sqrt', 'log2'], 'class_weight' : ["balanced", "balanced_subsample"]}
Titanic - Machine Learning from Disaster
5,616,085
inp = Input(shape=(maxlen,)) x = Embedding(max_features, EMBEDDING_DIM, weights=[embedding_matrix],trainable=False )(inp) x = SpatialDropout1D(0.25 )(x) x1 = Bidirectional(CuDNNLSTM(128, return_sequences=True))(x) x2 = Bidirectional(CuDNNGRU(128, return_sequences=True))(x) attn_lstm = Attention(maxlen )(x1) attn_g...
model_param_grid['AdaBoostClassifier'] = {'n_estimators' : [25,50,75,100], 'learning_rate' : [0.001,0.01,0.05,0.1,1,10], 'algorithm' : ['SAMME', 'SAMME.R']}
Titanic - Machine Learning from Disaster
5,616,085
model.fit(train_X, train_y, batch_size=512, epochs=4, validation_data=(val_X, val_y))<predict_on_test>
def tune_parameters(model_name,model,params,cv,scorer,X,y): best_model = GridSearchCV(estimator = model, param_grid = params, scoring = scorer, cv = cv, n_jobs = -1 ).fit(X, y) print("Tuning Results for ", model_name) print("Best Score Achieved: ",best_model.best_score_) print("Best Parameters Used: ",best_model.bes...
Titanic - Machine Learning from Disaster
5,616,085
pred_glove_val_y = model.predict([val_X], batch_size=1024, verbose=1 )<compute_test_metric>
def roc_metric(y_test, y_pred): score = roc_auc_score(y_test, y_pred) return score
Titanic - Machine Learning from Disaster
5,616,085
result = threshold_search(val_y, pred_glove_val_y) print(result )<save_model>
roc_scorer = make_scorer(roc_metric,greater_is_better=True )
Titanic - Machine Learning from Disaster
5,616,085
model.save('my_model.h5') <predict_on_test>
best_estimators = []
Titanic - Machine Learning from Disaster
5,616,085
pred_glove_test_y = model.predict([test_X], batch_size=1024, verbose=1 )<save_to_csv>
for m_name, m_obj in estimators: best_estimators.append(( m_name,tune_parameters(m_name, m_obj, model_param_grid[m_name], 10, roc_scorer, X_train, y_train)) )
Titanic - Machine Learning from Disaster
5,616,085
pred_test_y = pred_glove_test_y pred_test_y =(pred_test_y > result['threshold'] ).astype(int) out_df = pd.DataFrame({"qid":test_df["qid"].values}) out_df['prediction'] = pred_test_y out_df.to_csv("submission.csv", index=False )<import_modules>
best_estimators
Titanic - Machine Learning from Disaster
5,616,085
tqdm.pandas(desc='Progress') <define_variables>
tuned_vc = VotingClassifier(best_estimators) tuned_vc.fit(X_train,y_train )
Titanic - Machine Learning from Disaster
5,616,085
embed_size = 300 max_features = 120000 maxlen = 80 batch_size = 512 n_epochs = 5 n_splits = 5 debug = 0 num_embeddings = 2<define_variables>
y_pred = tuned_vc.predict(X_test )
Titanic - Machine Learning from Disaster
5,616,085
puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', ' '·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…', '“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾'...
confusion_matrix(y_test,y_pred )
Titanic - Machine Learning from Disaster
5,616,085
mispell_dict = {"aren't" : "are not", "can't" : "cannot", "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", "i'd" : "I would", "i'd" : "I had", "i'll"...
accuracy_score(y_test,y_pred )
Titanic - Machine Learning from Disaster
5,616,085
first_word_mispell_dict = { 'whta': 'what', 'howdo': 'how do', 'Whatare': 'what are', 'howcan': 'how can', 'howmuch': 'how much', 'howmany': 'how many', 'whydo': 'why do', 'doi': 'do i', 'howdoes': 'how does', "whst": 'what', 'shoupd': 'should', 'whats': 'what is', "im": "i am", "whatis": "what is", "iam": "i am", "wat...
precision_score(y_test,y_pred )
Titanic - Machine Learning from Disaster
5,616,085
def clean_text(x): x = str(x) for punct in puncts: if punct in x: x = x.replace(punct, f' {punct} ') return x def clean_numbers(x): if bool(re.search(r'\d', 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 <string_transform>
recall_score(y_test,y_pred )
Titanic - Machine Learning from Disaster
5,616,085
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) d...
f1_score(y_test,y_pred )
Titanic - Machine Learning from Disaster
5,616,085
def add_features(df): df['question_text'] = df['question_text'].progress_apply(lambda x:str(x)) df["lower_question_text"] = df["question_text"].apply(lambda x: x.lower()) df['total_length'] = df['question_text'].progress_apply(len) df['capitals'] = df['question_text'].progress_apply(lambda comment: sum(1 for c in com...
import keras from keras.utils import plot_model from keras.models import Model,Sequential,load_model from keras.layers import Input, Flatten, Dense, Dropout from keras.layers.merge import concatenate from keras import backend as K from keras.callbacks import ModelCheckpoint,EarlyStopping,ReduceLROnPlateau
Titanic - Machine Learning from Disaster
5,616,085
def parallelize_apply(df,func,colname,num_process,newcolnames): pool =Pool(processes=num_process) arraydata = pool.map(func,tqdm(df[colname].values)) pool.close() newdf = pd.DataFrame(arraydata,columns = newcolnames) df = pd.concat([df,newdf],axis=1) return df def parallelize_dataframe(df, func): df_split = np.array...
def nn_model(X,y,optimizer,kernels): input_shape = X.shape[1] if(len(np.unique(y)) == 2): op_neurons = 1 op_activation = 'sigmoid' loss = 'binary_crossentropy' else: op_neurons = len(np.unique(y)) op_activation = 'softmax' loss = 'categorical_crossentropy' classifier = Sequential() classifier.add(Dense(units = input_sh...
Titanic - Machine Learning from Disaster
5,616,085
if debug: train_df = pd.read_csv(".. /input/quora-insincere-questions-classification/train.csv")[:800] test_df = pd.read_csv(".. /input/quora-insincere-questions-classification/test.csv")[:200] else: train_df = pd.read_csv(".. /input/quora-insincere-questions-classification/train.csv") test_df = pd.read_csv(".. /input...
model = nn_model(X_train,y_train,'adam','he_uniform') history = model.fit(X_train, y_train, batch_size = 64, epochs = 1000, validation_data=(X_test, y_test))
Titanic - Machine Learning from Disaster
5,616,085
train = parallelize_dataframe(train_df, add_features) test = parallelize_dataframe(test_df, add_features )<feature_engineering>
his_df = pd.DataFrame(history.history) his_df.shape
Titanic - Machine Learning from Disaster
9,690,994
train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: x.lower()) test_df["question_text"] = test_df["question_text"].progress_apply(lambda x: x.lower() )<feature_engineering>
train = pd.read_csv("/kaggle/input/titanic/train.csv") test = pd.read_csv("/kaggle/input/titanic/test.csv" )
Titanic - Machine Learning from Disaster
9,690,994
train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: clean_text(x)) test_df["question_text"] = test_df["question_text"].progress_apply(lambda x: clean_text(x))<feature_engineering>
train = train.drop(columns=['Name','Cabin','Ticket']) test = test.drop(columns=['Name','Cabin','Ticket'] )
Titanic - Machine Learning from Disaster
9,690,994
train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: clean_numbers(x)) test_df["question_text"] = test_df["question_text"].progress_apply(lambda x: clean_numbers(x))<feature_engineering>
train['Embarked_S'] =(train['Embarked'] == 'S' ).astype(int) train['Embarked_C'] =(train['Embarked'] == 'C' ).astype(int) train['Embarked_Q'] =(train['Embarked'] == 'Q' ).astype(int) train['Gender'] =(train['Sex'] == 'male' ).astype(int )
Titanic - Machine Learning from Disaster
9,690,994
train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: replace_typical_misspell(x)) test_df["question_text"] = test_df["question_text"].progress_apply(lambda x: replace_typical_misspell(x))<prepare_x_and_y>
test['Embarked_S'] =(test['Embarked'] == 'S' ).astype(int) test['Embarked_C'] =(test['Embarked'] == 'C' ).astype(int) test['Embarked_Q'] =(test['Embarked'] == 'Q' ).astype(int) test['Gender'] =(test['Sex'] == 'male' ).astype(int )
Titanic - Machine Learning from Disaster
9,690,994
train_X = train_df["question_text"].fillna("_ test_X = test_df["question_text"].fillna("_<string_transform>
train = train.drop(columns = ['Sex']) test = test.drop(columns = ['Sex']) train = train.drop(columns = ['Embarked']) test = test.drop(columns = ['Embarked'] )
Titanic - Machine Learning from Disaster
9,690,994
def tokenize_and_split(train_X,test_X): tokenizer = Tokenizer(num_words=max_features,oov_token = 'xxunk',filters='') 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_sequen...
train.fillna(0, inplace=True) test.fillna(0, inplace=True )
Titanic - Machine Learning from Disaster
9,690,994
def make_stat_features() : train_features = train[['num_unique_words','words_vs_unique','total_length','capitals', 'caps_vs_length','num_words']].fillna(0) test_features = test[['num_unique_words','words_vs_unique','total_length','capitals', 'caps_vs_length','num_words']].fillna(0) ss = StandardScaler() ss.fit(np.vst...
X = train.drop(columns=['Survived']) y = train['Survived']
Titanic - Machine Learning from Disaster
9,690,994
x_train, x_test, y_train, train_features, test_features , word_index = tokenize_and_split(train_X,test_X )<compute_train_metric>
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42 )
Titanic - Machine Learning from Disaster
9,690,994
def load_embedding(path, word_index,emb_mean, emb_std): def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(path, encoding="utf8", errors='ignore')if len(o)>100) all_embs = np.stack(embeddings_index.values()) embed_size = all_embs.sha...
model_1 = LGBMClassifier(learning_rate=0.01, n_estimators=1000, max_depth=None) model_2 = XGBClassifier(learning_rate=0.01, n_estimators=1000, max_depth=None) model_3 = AdaBoostClassifier(learning_rate=0.01, n_estimators=1000) model_4 = RandomForestClassifier(n_estimators=1000, random_state=42 )
Titanic - Machine Learning from Disaster
9,690,994
if debug: paragram_embeddings = np.random.randn(120000,300) glove_embeddings = np.random.randn(120000,300) else: glove_embeddings = load_embedding('.. /input/quora-insincere-questions-classification/embeddings/glove.840B.300d/glove.840B.300d.txt',word_index,-0.005838499,0.48782197) paragram_embeddings = load_embeddi...
estimators = [] estimators.append(( 'lgbm',model_1)) estimators.append(( 'xgb',model_2)) estimators.append(( 'adaboost',model_3)) estimators.append(( 'clf',model_4))
Titanic - Machine Learning from Disaster
9,690,994
class AttentionBlock(nn.Module): def __init__(self, feature_dim, step_dim, bias=True, **kwargs): super(AttentionBlock, 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.xavi...
hybrid_model = StackingClassifier(estimators )
Titanic - Machine Learning from Disaster
9,690,994
class EmbeddingDropout(nn.Module): def __init__(self, embedding_matrix, max_features = 120000, embedding_size = 300): super(EmbeddingDropout,self ).__init__() self.embedding = nn.Embedding(max_features, embedding_size) self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32)) self.embed...
hybrid_model.fit(X_train, y_train )
Titanic - Machine Learning from Disaster
9,690,994
class Body(nn.Module): def __init__(self, embedding_size= 300, hidden_size= 128): super(Body,self ).__init__() self.lstm = nn.LSTM(embedding_size*num_embeddings, hidden_size, bidirectional=True, batch_first=True) self.gru = nn.GRU(hidden_size*2, hidden_size, bidirectional=True, batch_first=True) self.hidden= hidden_s...
pred = hybrid_model.predict(X_test )
Titanic - Machine Learning from Disaster
9,690,994
class Extractor(nn.Module): def __init__(self,maxlen= 70,hidden_size= 128,out= 64,len_feats= 6): super(Extractor,self ).__init__() self.conv = nn.Conv1d(maxlen,out,kernel_size= 1,stride= 2) self.stat = nn.Linear(len_feats,hidden_size) def forward(self,h_lstm,h_gru,stat_features): conv_out = self.conv(h_lstm) l_maxpo...
accuracy_score(pred, y_test )
Titanic - Machine Learning from Disaster
9,690,994
class Head(nn.Module): def __init__(self,embedding_size= 300,intermediate_layer=64,maxlen=70,hidden_size=128): super(Head,self ).__init__() self.linear = nn.Linear(hidden_size*8,intermediate_layer) self.dropout = nn.Dropout(0.15) self.bn = nn.BatchNorm1d(intermediate_layer) self.output = nn.Linear(intermediate_layer...
test['Survived'] = actual_pred = hybrid_model.predict(test )
Titanic - Machine Learning from Disaster
9,690,994
<choose_model_class><EOS>
test[['PassengerId','Survived']].to_csv('submission.csv', index=False )
Titanic - Machine Learning from Disaster
5,315,723
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<categorify>
%matplotlib inline
Titanic - Machine Learning from Disaster
5,315,723
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 )<prepare_x_and_y>
COLOR = 'black' mpl.rcParams['text.color'] = COLOR mpl.rcParams['axes.labelcolor'] = COLOR mpl.rcParams['xtick.color'] = COLOR mpl.rcParams['ytick.color'] = COLOR plt.rcParams.update({'font.size': 18}) plt.subplots_adjust(wspace = 15, hspace = 15 )
Titanic - Machine Learning from Disaster
5,315,723
def sigmoid(x): return 1 /(1 + np.exp(-x)) if debug : x_test_cuda = torch.tensor(x_test, dtype=torch.long) else : 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 )<split...
original_training_df = pd.read_csv('/kaggle/input/train.csv') original_training_df.head()
Titanic - Machine Learning from Disaster
5,315,723
def kfold_train(x_train,y_train,x_test, model_obj, train_features, test_features,clip = True): avg_losses_f = [] avg_val_losses_f = [] train_preds = np.zeros(( len(x_train))) test_preds = np.zeros(( len(x_test))) splits = list(StratifiedKFold(n_splits=n_splits, shuffle=True ).split(x_train, y_train)) for i,(train_idx...
original_training_df.isnull().sum()
Titanic - Machine Learning from Disaster
5,315,723
def cpu_kfold_train(x_train,y_train,x_test, model_obj, train_features, test_features,clip = True): avg_losses_f = [] avg_val_losses_f = [] train_preds = np.zeros(( len(x_train))) test_preds = np.zeros(( len(x_test))) splits = list(StratifiedKFold(n_splits=n_splits, shuffle=True ).split(x_train, y_train)) for i,(train...
original_training_df.isnull().sum().divide(len(original_training_df.index)).multiply(100 )
Titanic - Machine Learning from Disaster
5,315,723
model = NeuralNet(embedding_matrix,maxlen=maxlen,max_features=len(embedding_matrix))<train_model>
def get_title(dataframe_in): dataframe_in['Title'] = dataframe_in['Name'].apply(lambda X: re.search('[A-Z]{1}[a-z]+\.', X ).group(0)) return dataframe_in dataframe_transformations_test = original_training_df.copy() dataframe_transformations_test = get_title(dataframe_transformations_test) dataframe_transformations_tes...
Titanic - Machine Learning from Disaster
5,315,723
if debug: train_preds, test_preds = cpu_kfold_train(x_train,y_train,x_test,model,train_features,test_features) else : train_preds, test_preds = kfold_train(x_train,y_train,x_test,model,train_features,test_features )<compute_train_metric>
dataframe_transformations_test.drop('PassengerId', axis = 1, inplace = True )
Titanic - Machine Learning from Disaster
5,315,723
def findthreshold(y_train, train_preds): best_f1= 0 best_thresh= 0 for thresh in tqdm(np.arange(0.1,0.501,0.01)) : f1 = f1_score(y_train,(train_preds>thresh)) if f1 > best_f1: best_thresh = thresh best_f1 = f1 print('best threshold is {:.4f} with F1 score: {:.4f}'.format(best_thresh, best_f1)) return best_thresh, best_...
def convert_sex_to_number(dataframe_in): dataframe_in['Sex'] = dataframe_in['Sex'].apply(lambda X: 0 if X == 'female' else 1) return dataframe_in dataframe_transformations_test = convert_sex_to_number(dataframe_transformations_test )
Titanic - Machine Learning from Disaster
5,315,723
if debug: df_test = pd.read_csv(".. /input/quora-insincere-questions-classification/test.csv")[:200] else: df_test = pd.read_csv(".. /input/quora-insincere-questions-classification/test.csv") submission = df_test[['qid']].copy() submission['prediction'] =(test_preds > threshold ).astype(int) submission.to_csv('submis...
def get_cabin_letter(dataframe_in): dataframe_in['Cabin'] = dataframe_in['Cabin'].apply(lambda X: re.search('[A-Za-z]{1}', X ).group(0 ).upper() if isinstance(X, str)else '?') return dataframe_in def get_ticket_prefix(dataframe_in): dataframe_in['Ticket'] = dataframe_in['Ticket'].apply(lambda X: X.split(' ')[0] if len...
Titanic - Machine Learning from Disaster
5,315,723
tqdm.pandas()<init_hyperparams>
def get_family_name(dataframe_in): dataframe_in['FamilyName'] = dataframe_in['Name'].apply(lambda X: re.search('[A-Z]{1}[a-z ]+', X ).group(0)) return dataframe_in dataframe_transformations_test = get_family_name(dataframe_transformations_test) dataframe_transformations_test.drop(['Name'], axis = 1, inplace = True) d...
Titanic - Machine Learning from Disaster
5,315,723
emb_size = 300 max_features = 200000 maxlen = 100<set_options>
def embarked_fillna_median(df): df.loc[:, ['Embarked']] = df['Embarked'].fillna(value = df['Embarked'].value_counts().idxmax()) return df dataframe_transformations_test = embarked_fillna_median(dataframe_transformations_test) dataframe_transformations_test.isnull().sum()
Titanic - Machine Learning from Disaster
5,315,723
def clean_memory(*args): for arg in args: del arg gc.collect() time.sleep(10 )<load_from_csv>
def fill_age_from_masters(df, strategy_in = 'median'): is_master =(df['Title'] == 'Master.') imp = SimpleImputer(missing_values = np.nan, strategy = strategy_in) df.loc[is_master, 'Age'] = imp.fit_transform(df.loc[is_master][['Age']]) return df dataframe_transformations_test = fill_age_from_masters(dataframe_transfo...
Titanic - Machine Learning from Disaster
5,315,723
path = '/kaggle/input/quora-insincere-questions-classification' train_df = pd.read_csv(path + "/train.csv") test_df = pd.read_csv(path + "/test.csv") train_df["question_text"].fillna("_na_", inplace=True) test_df["question_text"].fillna("_na_", inplace=True )<feature_engineering>
def fill_age_from_non_masters(df, strategy_in = 'median'): is_not_master =(df['Title'] != 'Master.') imp = SimpleImputer(missing_values = np.nan, strategy = strategy_in) df.loc[is_not_master, 'Age'] = imp.fit_transform(df.loc[is_not_master][['Age']]) return df dataframe_transformations_test = fill_age_from_non_maste...
Titanic - Machine Learning from Disaster
5,315,723
train_df["num_words"] = train_df["question_text"].progress_apply(lambda x: len(str(x ).split())) train_df["num_unique_words"] = train_df["question_text"].progress_apply(lambda x: len(set(str(x ).split()))) train_df["num_chars"] = train_df["question_text"].progress_apply(lambda x: len(str(x))) <feature_engineering>
def get_family_info(df_in): df_in['FamilyMembers'] = df_in['Parch'] + df_in['SibSp'] + 1 df_in['Is_Mother'] = np.where(( df_in.Title=='Mrs.')&(df_in.Parch >0), 1, 0) return df_in
Titanic - Machine Learning from Disaster
5,315,723
test_df["num_words"] = test_df["question_text"].progress_apply(lambda x: len(str(x ).split())) test_df["num_unique_words"] = test_df["question_text"].progress_apply(lambda x: len(set(str(x ).split()))) test_df["num_chars"] = test_df["question_text"].progress_apply(lambda x: len(str(x)) )<feature_engineering>
class TransformerSignificantData(BaseEstimator, TransformerMixin): def __init__(self): return def fit(self, X, y = None): return self def transform(self, X, y = None): out = get_cabin_letter(X) out = get_ticket_prefix(out) out = get_title(out) out = get_family_info(out) out = classify_title(out) out = get_family_n...
Titanic - Machine Learning from Disaster
5,315,723
def build_vocab(sentences, verbose = True): vocab = {} for sentence in tqdm(sentences, disable =(not verbose)) : for word in sentence: try: vocab[word] += 1 except KeyError: vocab[word] = 1 return vocab<feature_engineering>
class TransformerDummify(BaseEstimator, TransformerMixin): def __init__(self): return def fit(self, X, y = None): return self def transform(self, X, y = None): columns_to_dummify = ['Sex', 'Cabin', 'Embarked', 'Title', 'Ticket'] useless_columns = ['PassengerId', 'Name', 'FamilyName'] dim_redundant_cols = ['Sex_male', '...
Titanic - Machine Learning from Disaster
5,315,723
emb_path = '/kaggle/input/quora-insincere-questions-classification/embeddings' def load_all() : word2vec_format = {} glove = [o.split(" ")[0] for o in tqdm(open(emb_path + '/glove.840B.300d/glove.840B.300d.txt')) ] for word in tqdm(glove): word2vec_format[word] = 1 clean_memory(glove) return word2vec_format emb_all = ...
class TransformerMissingData(BaseEstimator, TransformerMixin): def __init__(self, missing_age_masters_strategy = 'mean', missing_age_non_masters_strategy = 'mean'): self.missing_age_masters_strategy = missing_age_masters_strategy self.missing_age_non_masters_strategy = missing_age_non_masters_strategy def fit(self, X, ...
Titanic - Machine Learning from Disaster
5,315,723
def check_coverage(vocab, embeddings_index): a = {} oov = {} k = 0 i = 0 for word in tqdm(vocab): try: a[word] = embeddings_index[word] k += vocab[word] except: oov[word] = vocab[word] i += vocab[word] pass print('Found embeddings for {:.2%} of vocab'.format(len(a)/ len(vocab))) print('Found embeddings for {:.2%} of a...
class TransformerNormalize(BaseEstimator, TransformerMixin): def __init__(self): return def fit(self, X, y = None): return self def transform(self, X, y = None): out = X out.loc[:, ['Pclass']] = MinMaxScaler().fit_transform(out[['Pclass']]) out.loc[:, ['Age', 'Fare']] = StandardScaler().fit_transform(out[['Age', 'Fare...
Titanic - Machine Learning from Disaster
5,315,723
sentences = train_df["question_text"].progress_apply(lambda x: x.split()) vocab = build_vocab(sentences) oov = check_coverage(vocab, emb_all) oov[:10]<define_variables>
df_dummy = pd.concat([pd.read_csv('/kaggle/input/train.csv'), pd.read_csv('/kaggle/input/test.csv')], ignore_index = True) dummy_pipeline = Pipeline([ ('prepare', TransformerSignificantData()), ('dummify', TransformerDummify()), ('normalize', TransformerNormalize()) ]) df_dummy = dummy_pipeline.transform(df_dummy...
Titanic - Machine Learning from Disaster
5,315,723
punct = "/-'?!., punct_mapping = {"‘": "'", "₹": "e", "´": "'", "°": "", "€": "e", "™": "tm", "√": " sqrt ", "×": "x", "²": "2", "—": "-", "–": "-", "’": "'", "_": "-", "`": "'", '“': '"', '”': '"', '“': '"', "£": "e", '∞': 'infinity', 'θ': 'theta', '÷': '/', 'α': 'alpha', '•': '.', 'à': 'a', '−': '-', 'β': 'beta', '∅'...
related_to_age = ['Pclass', 'Title_Miss.', 'SibSp', 'Cabin_C', 'Title_Mr.', 'Fare', 'Parch']
Titanic - Machine Learning from Disaster
5,315,723
train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: clean_special_chars(x)) test_df["question_text"] = test_df["question_text"].progress_apply(lambda x: clean_special_chars(x)) sentences = train_df["question_text"].progress_apply(lambda x: x.split()) vocab = build_vocab(sentences) oov = che...
df_pca = df_dummy.copy().loc[:, related_to_age] df_pca.isnull().sum()
Titanic - Machine Learning from Disaster
5,315,723
mispell_dict = {'colour': 'color', 'centre': 'center', 'favourite': 'favorite', 'travelling': 'traveling', 'counselling': 'counseling', 'theatre': 'theater', 'cancelled': 'canceled', 'labour': 'labor', 'organisation': 'organization', 'wwii': 'world war 2', 'citicise': 'criticize', 'youtu ': 'youtube ', 'Qoura': 'Quora'...
df_pca = df_pca.fillna(value = df_pca['Fare'].mean()) df_pca.isnull().sum()
Titanic - Machine Learning from Disaster
5,315,723
train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: correct_spelling(x, mispell_dict)) test_df["question_text"] = test_df["question_text"].progress_apply(lambda x: correct_spelling(x, mispell_dict)) sentences = train_df["question_text"].apply(lambda x: x.split()) vocab = build_vocab(sentence...
np.cumsum(pca_age.explained_variance_ratio_ )
Titanic - Machine Learning from Disaster
5,315,723
go_to_more_common_words = { 'Redmi': 'Mobile', 'OnePlus': 'Mobile', 'Quorans': 'Quoran', 'cryptocurrencies': 'technology', 'Cryptocurrency': 'Technology', 'Blockchain': 'Technology', 'Upwork': 'Technology', 'HackerRank': 'Programming', } train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: cor...
kmeans2 = KMeans(n_clusters = 2, random_state = 42, n_init = 500 ).fit_predict(np_pca_significant) kmeans3 = KMeans(n_clusters = 3, random_state = 42, n_init = 500 ).fit_predict(np_pca_significant) kmeans4 = KMeans(n_clusters = 4, random_state = 42, n_init = 500 ).fit_predict(np_pca_significant) kmeans5 = KMeans(n_c...
Titanic - Machine Learning from Disaster
5,315,723
clean_memory(oov, vocab, sentences, mispell_dict, go_to_more_common_words, punct, punct_mapping, emb_all )<split>
dbscan_model = DBSCAN(eps = 0.7, min_samples = 20 ).fit(np_pca_significant) dbscan_predict = dbscan_model.fit_predict(np_pca_significant )
Titanic - Machine Learning from Disaster
5,315,723
def load_all_emb(word_index): def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') glove = dict(get_coefs(*o.split(" ")) for o in tqdm(open(emb_path + '/glove.840B.300d/glove.840B.300d.txt')) if o.split(" ")[0] in word_index) global max_features all_embs = np.stack(glove.values()) emb_mean, emb_st...
class TransformerMissingData(BaseEstimator, TransformerMixin): def __init__(self, missing_age_masters_strategy = 'mean', missing_age_non_masters_strategy = 'cluster'): self.missing_age_masters_strategy = missing_age_masters_strategy self.missing_age_non_masters_strategy = missing_age_non_masters_strategy def fit(self, ...
Titanic - Machine Learning from Disaster
5,315,723
emb_path = '/kaggle/input/quora-insincere-questions-classification/embeddings' tokenizer = Tokenizer(num_words=max_features, filters="") tokenizer.fit_on_texts(np.concatenate(( train_df["question_text"].values, test_df["question_text"].values))) embeddings = load_all_emb(tokenizer.word_index) print(max_features )<sp...
feature_engineering_pipeline = Pipeline([ ('prepare', TransformerSignificantData()), ('dummify', TransformerDummify()), ('normalize', TransformerNormalize()), ('missing', TransformerMissingData()) ]) df_all_original = pd.concat([pd.read_csv('/kaggle/input/train.csv'), pd.read_csv('/kaggle/input/test.csv')], ignor...
Titanic - Machine Learning from Disaster
5,315,723
train_df, val_df = train_test_split(train_df, test_size=0.1, random_state=47) train_X = train_df["question_text"].values val_X = val_df["question_text"].values test_X = test_df["question_text"].values train_X2 = train_df[['num_words', 'num_unique_words', 'num_chars']] val_X2 = val_df[['num_words', 'num_unique_words', ...
df_all_processed = feature_engineering_pipeline.transform(df_all_original.copy()) df_all_processed.head()
Titanic - Machine Learning from Disaster
5,315,723
early_stopping = EarlyStopping(monitor="val_f1", patience=2, restore_best_weights=True, mode="max") reduce_lr = ReduceLROnPlateau(monitor="val_f1", mode="max") callbacks = [early_stopping, reduce_lr]<compute_test_metric>
df_all_processed.isnull().sum()
Titanic - Machine Learning from Disaster
5,315,723
def f1(y_true, y_pred): def recall(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives /(possible_positives + K.epsilon()) return recall def precision(y_true, y_pred): true_positives = K.sum(K.round(K.clip...
df_ans = df_all_processed[df_all_processed['Survived'].isnull() ] df_ans = df_ans.loc[:, df_ans.columns != 'Survived'] df_cv_and_test = df_all_processed[df_all_processed['Survived'].notnull() ] df_cv_and_test_X = df_cv_and_test.drop(['Survived', 'ClusterLabel'], axis = 1) df_cv_and_test_Y = df_cv_and_test['Survived'] ...
Titanic - Machine Learning from Disaster
5,315,723
inp1 = Input(shape=(maxlen,)) x = Embedding(max_features, emb_size, weights=[embeddings], trainable=False )(inp1) x = SpatialDropout1D(0.4 )(x) x = Bidirectional(CuDNNLSTM(128, return_sequences=True))(x) x = Conv1D(64, 1 )(x) max_pool = GlobalMaxPooling1D()(x) inp2 = Input(shape=(3,)) y = Dense(64 )(inp2) xy = co...
hyper_rf = dict( n_estimators = [85, 86, 87, 88, 89], max_depth = [3, 4, 5, 6, 7, 8, 9, 10], random_state = [42] ) hyper_svm = dict( C = [6.0, 7.0, 8.0], kernel = ['linear', 'poly', 'rbf', 'sigmoid'], gamma = ['auto', 'scale'], probability = [True], random_state = [42] ) hyper_logit = dict( C = [0.1, 1.0, 10.0],...
Titanic - Machine Learning from Disaster
5,315,723
model.fit([train_X, train_X2], train_y, batch_size=512, epochs=20, validation_data=([val_X, val_X2], val_y), callbacks=callbacks, verbose=True )<drop_column>
n_cv = 10 gscv_rf = GridSearchCV(RandomForestClassifier() , hyper_rf, scoring = 'accuracy', cv = n_cv) gscv_svm = GridSearchCV(SVC() , hyper_svm, scoring = 'accuracy', cv = n_cv) gscv_logit = GridSearchCV(LogisticRegression() , hyper_logit, scoring = 'accuracy', cv = n_cv) gscv_adab = GridSearchCV(AdaBoostClassifier...
Titanic - Machine Learning from Disaster
5,315,723
clean_memory(train_X, train_y )<find_best_model_class>
print('1.Fitting Random Forest') gscv_rf.fit(df_cv_X.copy() , df_cv_Y.copy()) print('2.Fitting SVM') gscv_svm.fit(df_cv_X.copy() , df_cv_Y.copy()) print('3.Fitting Logit') gscv_logit.fit(df_cv_X.copy() , df_cv_Y.copy()) print('4.Fitting AdaBoost') gscv_adab.fit(df_cv_X.copy() , df_cv_Y.copy()) print('5.Fitting ...
Titanic - Machine Learning from Disaster
5,315,723
pred_val_y = model.predict([val_X, val_X2], batch_size=512, verbose=1) def scoring(y_true, y_proba, verbose=True): def threshold_search(y_true, y_proba): precision , recall, thresholds = precision_recall_curve(y_true, y_proba) thresholds = np.append(thresholds, 1.001) F = 2 /(1/precision + 1/recall) best_score = np...
def get_CV_score(classifier_name, n_cv): ans = [0] * n_cv for i in range(0, n_cv): command_str = classifier_name + '.cv_results_['split' + str(i)+ '_test_score']' ans[i] = eval(command_str)[0] return ans train_score_list_rf = get_CV_score('gscv_rf', n_cv) train_score_list_svm = get_CV_score('gscv_svm', n_cv) train_sc...
Titanic - Machine Learning from Disaster
5,315,723
clean_memory(val_X, val_y, pred_val_y )<predict_on_test>
def print_opt_hyper(dict_hyper, model): for k in dict_hyper.keys() : print(k + ': ' + str(model.best_estimator_.get_params() [k])+ ' -- ' + str(dict_hyper[k])) print('Optimal Hyperparameters:') print('---') print('1.Random Forest') print_opt_hyper(hyper_rf, gscv_rf) print('---') print('2.SVM') print_opt_hyper(hyp...
Titanic - Machine Learning from Disaster
5,315,723
all_preds = model.predict([test_X, test_X2], batch_size=512, verbose=1) pred_test_y =(np.array(all_preds)> optimal_point1 ).astype(np.int )<save_to_csv>
estimator_list = [('rf', gscv_rf.best_estimator_), ('svm', gscv_svm.best_estimator_), ('logit', gscv_logit.best_estimator_), ('adab', gscv_adab.best_estimator_), ('xbt', gscv_xbt.best_estimator_)] hard_vote_estimator = VotingClassifier(estimator_list) soft_vote_estimator = VotingClassifier(estimator_list) meta_lo...
Titanic - Machine Learning from Disaster
5,315,723
submit_df = pd.DataFrame({"qid": test_df["qid"], "prediction": pred_test_y1}) submit_df.to_csv("submission.csv", index=False )<import_modules>
%%capture hard_cv = GridSearchCV(hard_vote_estimator, param_grid = {'voting': ['hard']}, scoring = 'accuracy', cv = n_cv ).fit(df_cv_X.copy() , df_cv_Y.copy()) soft_cv = GridSearchCV(soft_vote_estimator, param_grid = {'voting': ['soft']}, scoring = 'accuracy', cv = n_cv ).fit(df_cv_X.copy() , df_cv_Y.copy()) stack_cv...
Titanic - Machine Learning from Disaster
5,315,723
from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.initializers import he_normal, he_uniform, glorot_normal, glorot_uniform from keras import backend as K from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau from keras.models import Model from kera...
print('Hard Voting Score: ' + str(hard_cv.best_score_)) print('Soft Voting Score: ' + str(soft_cv.best_score_)) print('Stacking Score: ' + str(stack_cv.best_score_))
Titanic - Machine Learning from Disaster
5,315,723
batch_size = 1024 epochs = 18 current_embd = "Glove" question_length = 100 max_eval_size = 15000 DATA_SPLIT_SEED = 2018 K_FOLDS = 5 K_FOLD_EPOCHS = int(epochs/K_FOLDS) seed_nb=14 np.random.seed(seed_nb) tf.set_random_seed(seed_nb )<define_variables>
train_score_list_hv = get_CV_score('hard_cv', n_cv) train_score_list_sv = get_CV_score('soft_cv', n_cv) train_score_list_st = get_CV_score('stack_cv', n_cv) df_train_score = pd.DataFrame(dict( estimator = ['1.rf'] * len(train_score_list_rf)+ ['2.svm'] * len(train_score_list_svm)+ ['3.logit'] * len(train_score_list_...
Titanic - Machine Learning from Disaster
5,315,723
paraules_prohibides = ['2g1c', '2 girls 1 cup', 'acrotomophilia', 'alabama hot pocket', 'alaskan pipeline', 'anal', 'anilingus', 'anus', 'apeshit', 'arsehole', 'ass', 'asshole', 'assmunch', 'auto erotic', 'autoerotic', 'babeland', 'baby batter', 'baby juice', 'ball gag', 'ball gravy', 'ball kicking', 'ball licking', 'b...
model_ids = ['RandomForest', 'SVM', 'AdaBoost', 'Logistic', 'XBTree', 'SoftVoting', 'HardVoting', 'Stacking'] for i, model in enumerate([gscv_rf, gscv_svm, gscv_adab, gscv_logit, gscv_xbt, soft_cv, hard_cv, stack_cv]): submission_estimator = model.best_estimator_.fit(df_cv_and_test_X, df_cv_and_test_Y) survival_ans_co...
Titanic - Machine Learning from Disaster
9,697,036
train = pd.read_csv(".. /input/train.csv") test = pd.read_csv(".. /input/test.csv") test['target']=-1 df = pd.concat([train ,test] )<set_options>
train_data = pd.read_csv("/kaggle/input/titanic/train.csv") train_data.head()
Titanic - Machine Learning from Disaster
9,697,036
del train, test; gc.collect() ; time.sleep(5 )<split>
test_data = pd.read_csv("/kaggle/input/titanic/test.csv") test_data.head()
Titanic - Machine Learning from Disaster
9,697,036
def load_embed(file): def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') if file == '.. /input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec': embeddings_index = dict(get_coefs(*o.split(" ")) for o in tqdm(open(file)) if len(o)>100) else: embeddings_index = dict(get_coefs(*o.split(" ")) for ...
women = train_data.loc[train_data.Sex == 'female']["Survived"] rate_women = sum(women)/len(women) print("% de mujeres que sobrevivieron:", rate_women )
Titanic - Machine Learning from Disaster
9,697,036
embed_glove = load_embed('.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt' )<load_pretrained>
men = train_data.loc[train_data.Sex == 'male']["Survived"] rate_men = sum(men)/len(men) print("% de hombres que sobrevivieron:", rate_men )
Titanic - Machine Learning from Disaster
9,697,036
embed_paragram = load_embed('.. /input/embeddings/paragram_300_sl999/paragram_300_sl999.txt' )<categorify>
print('Total hombres:',len(men)) print('Total mujeres:',len(women)) print('Total sobrevivientes hombres:',sum(men)) print('Total sobrevivientes mujeres:',sum(women))
Titanic - Machine Learning from Disaster
9,697,036
my_embedding_matrix = dict() for k1,v1 in embed_glove.items() : my_val = v1 if k1 in embed_paragram.keys() : my_val =(v1 + embed_paragram[k1])/2 my_embedding_matrix[k1] = my_val for k1,v1 in embed_paragram.items() : if k1 not in embed_glove.keys() : my_embedding_matrix[k1] = v1<load_pretrained>
parch_0 = train_data.loc[train_data.Parch == 0]["Survived"] rate_parch_0 = sum(parch_0)/len(parch_0) print("% parch = 0 que sobrevivieron:", rate_parch_0) parch_1 = train_data.loc[train_data.Parch == 1]["Survived"] rate_parch_1 = sum(parch_1)/len(parch_1) print("% parch = 1 que sobrevivieron:", rate_parch_1) parch_...
Titanic - Machine Learning from Disaster
9,697,036
<feature_engineering>
print('Vacios en embarked:',train_data['Embarked'].isnull().values.any()) print('Vacios en Sex:',train_data['Sex'].isnull().values.any()) print('Vacios en Name:',train_data['Name'].isnull().values.any()) print('Vacios en Age:',train_data['Age'].isnull().values.any()) print('Vacios en Cabin:',train_data['Cabin'].isn...
Titanic - Machine Learning from Disaster
9,697,036
df['size'] = df['question_text'].str.len() print(mean(df['size'])) print(median(df['size'])) print(stdev(df['size'])) print(amax(df['size'])) print(amin(df['size'])) df = df.drop(['size'], axis=1 )<feature_engineering>
print('Embarked:',train_data['Embarked'].isnull().sum()) print('Age:',train_data['Age'].isnull().sum()) print('Cabin:',train_data['Cabin'].isnull().sum() )
Titanic - Machine Learning from Disaster
9,697,036
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<define_variables>
embarked_s = train_data.loc[train_data.Embarked == 'S']["Survived"] rate_embarked_s = sum(embarked_s)/len(train_data['Survived']) print('% que sobrevivio con embarked = S: ',rate_embarked_s) embarked_c = train_data.loc[train_data.Embarked == 'C']["Survived"] rate_embarked_c = sum(embarked_c)/len(train_data['Survived'...
Titanic - Machine Learning from Disaster
9,697,036
vocab = build_vocab(df['question_text'] )<feature_engineering>
train_data[train_data['Embarked'].isnull() ]
Titanic - Machine Learning from Disaster
9,697,036
df['question_text'] = df['question_text'].apply(lambda x: x.lower() )<feature_engineering>
train_data[train_data['Age'].isnull() ]
Titanic - Machine Learning from Disaster
9,697,036
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<feature_engineering>
primera_clase = train_data.loc[train_data.Pclass == 1]["Survived"] rate_1 = sum(primera_clase)/len(primera_clase) print("% Sobrevivientes en primera clase:", rate_1) segunda_clase = train_data.loc[train_data.Pclass == 2]["Survived"] rate_2 = sum(segunda_clase)/len(segunda_clase) print("% Sobrevivientes en segunda cl...
Titanic - Machine Learning from Disaster
9,697,036
for index, row in df.iterrows() : for w in paraules_prohibides: if w in row['question_text']: row['conte_paraula_prohibida']=1 break;<train_model>
train_data['Embarked'].fillna('S', inplace=True) train_data[(train_data['PassengerId'] == 62)|(train_data['PassengerId'] == 830)]
Titanic - Machine Learning from Disaster
9,697,036
if "sexo" in paraules_prohibides: print("OK") if "casa" in paraules_prohibides: print("OK2" )<define_variables>
train_data['Cabin'].fillna('M', inplace=True) train_data['Cabin_full'] = train_data.Cabin.str.slice(0, 1) test_data['Cabin'].fillna('M', inplace=True) test_data['Cabin_full'] = test_data.Cabin.str.slice(0, 1 )
Titanic - Machine Learning from Disaster
9,697,036
for index, row in df.iterrows() : if row['conte_paraula_prohibida']==1 & index < 20: print(row['question_text'] )<define_variables>
train_data[train_data['Cabin'].isnull() ]
Titanic - Machine Learning from Disaster
9,697,036
my_embedding_matrix = {k: v for k, v in my_embedding_matrix.items() if k in vocab}<set_options>
test_data['age_bins'] = pd.cut(x=test_data['Age'], bins=[0, 12, 20, 25, 40, 80]) test_data['age_bins'].unique()
Titanic - Machine Learning from Disaster
9,697,036
del embed_paragram, embed_glove, vocab; gc.collect() ; time.sleep(5 )<define_variables>
train_data.corr(method ='pearson' )
Titanic - Machine Learning from Disaster
9,697,036
contraction_mapping = {"ain't": "is not", "aren't": "are not","can't": "cannot", "'cause": "because", "could've": "could have", "couldn't": "could not", "didn't": "did not", "doesn't": "does not", "don't": "do not", "hadn't": "had not", "hasn't": "has not", "haven't": "have not", "he'd": "he would","he'll": "he will", ...
train_data['vaSolo'] = train_data['SibSp'] + train_data['Parch'] train_data['vaSolo'] = np.where(train_data['vaSolo'] == 0, 1, 0) train_data.head()
Titanic - Machine Learning from Disaster
9,697,036
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<drop_column>
test_data['vaSolo'] = test_data['SibSp'] + test_data['Parch'] test_data['vaSolo'] = np.where(test_data['vaSolo'] == 0, 1, 0) train_data.head()
Titanic - Machine Learning from Disaster
9,697,036
df['question_text'] = df['question_text'].apply(lambda x: clean_contractions(x, contraction_mapping))<define_variables>
features = ['Pclass', 'Sex', 'Embarked', 'age_bins', 'vaSolo', 'Cabin_full'] y = train_data['Survived'].values X = pd.get_dummies(train_data[features]) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.40, random_state=5, stratify=y) X_test_r = pd.get_dummies(test_data[features]) model = RandomFor...
Titanic - Machine Learning from Disaster
9,697,036
punct = "/-'?!., <feature_engineering>
X_test_r.head() X_test_r['Cabin_full_T'] = 0
Titanic - Machine Learning from Disaster