kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
1,266,101
train_X, test_X, train_y, word_index = load_and_prec() embedding_matrix_1 = load_glove(word_index) embedding_matrix_3 = load_para(word_index )<compute_test_metric>
df = pd.read_csv('.. /input/train.csv') df.head()
Titanic - Machine Learning from Disaster
1,266,101
embedding_matrix = np.mean([embedding_matrix_1, embedding_matrix_3], axis = 0) np.shape(embedding_matrix) def threshold_search(y_true, y_proba): best_threshold = 0 best_score = 0 for threshold in [i * 0.01 for i in range(100)]: score = f1_score(y_true=y_true, y_pred=y_proba > threshold) if score > best_score: best_t...
get_missing_data_table(df )
Titanic - Machine Learning from Disaster
1,266,101
train_meta = np.zeros(train_y.shape) test_meta = np.zeros(test_X.shape[0]) splits = list(StratifiedKFold(n_splits=4, shuffle=True, random_state=DATA_SPLIT_SEED ).split(train_X, train_y)) for idx,(train_idx, valid_idx)in enumerate(splits): X_train = train_X[train_idx] y_train = train_y[train_idx] X_val = train_X[valid...
df = df.drop('Cabin', axis='columns') df = delete_null_observations(df, column='Embarked') df = df.reset_index(drop=True) df['Age'] = df['Age'].fillna(value=1000) get_missing_data_table(df )
Titanic - Machine Learning from Disaster
1,266,101
tqdm.pandas(desc='Progress') <define_variables>
df['Family Size'] = df['SibSp'] + df['Parch'] df = df.drop('SibSp', axis='columns') df = df.drop('Parch', axis='columns') df.head(5 )
Titanic - Machine Learning from Disaster
1,266,101
embed_size = 300 max_features = 120000 maxlen = 70 batch_size = 512 n_epochs = 5 n_splits = 5 SEED = 1029<set_options>
titles = name_row.tolist() for i in range(len(titles)) : title = titles[i] if title != 'Master' and title != 'Miss' and title != 'Mr' and title !='Mrs': titles[i] = 'Other' name_row = pd.DataFrame(titles, columns=['Title']) df['Title'] = name_row.copy() df = df.drop('Name', axis='columns') df.head(5 )
Titanic - Machine Learning from Disaster
1,266,101
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>
test_df = df.copy() test_df = pd.DataFrame([df['Age'].tolist() , df['Title'].tolist() ] ).transpose() test_df.columns = ['Age','Title'] test_df_list = test_df.values for i in range(len(test_df_list)) : age = test_df_list[i][0] title = test_df_list[i][1] if age == 1000: if title == 'Master': test_df_list[i][0] = 5.19 el...
Titanic - Machine Learning from Disaster
1,266,101
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,e...
df = df.drop('Ticket', axis='columns') df = df.drop('PassengerId', axis='columns') df.head(5 )
Titanic - Machine Learning from Disaster
1,266,101
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>
df = transform_dummy_variables(df,['Sex','Pclass','Embarked','Title']) df.head(5 )
Titanic - Machine Learning from Disaster
1,266,101
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>
X_train = df.iloc[:,1:].values y = df.iloc[:,0].values sc = StandardScaler() X_train = sc.fit_transform(X_train) print('X_train: {0}'.format(X_train[0:5])) print('y: {0}'.format(y[0:5]))
Titanic - Machine Learning from Disaster
1,266,101
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>
classifier = XGBClassifier() classifier.fit(X_train, y )
Titanic - Machine Learning from Disaster
1,266,101
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(c...
params = { 'min_child_weight': [1, 5, 10], 'gamma': [0.5, 1, 1.5, 2, 5], 'subsample': [0.6, 0.8, 1.0], 'colsample_bytree': [0.6, 0.8, 1.0], 'max_depth': [3, 4, 5] } folds = 4 param_comb = 5 skf = StratifiedKFold(n_splits=folds, shuffle = True, random_state = 1001) random_search = RandomizedSearchCV(classifier, param_d...
Titanic - Machine Learning from Disaster
1,266,101
puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', ' '·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…', '“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾'...
classifier = RandomForestClassifier() classifier.fit(X_train, y )
Titanic - Machine Learning from Disaster
1,266,101
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: f...
params = { 'n_estimators': [5, 10, 15], 'criterion': ['gini', 'entropy'], 'max_features': ['auto', 'sqrt', 'log2', None], 'max_depth': [None, 3, 4, 5] } folds = 4 param_comb = 5 skf = StratifiedKFold(n_splits=folds, shuffle = True, random_state = 1001) random_search = RandomizedSearchCV(classifier, param_distributions...
Titanic - Machine Learning from Disaster
1,266,101
x_train, x_test, y_train, features, test_features, word_index = load_and_prec() <save_model>
classifier = SVC(probability=True) classifier.fit(X_train, y )
Titanic - Machine Learning from Disaster
1,266,101
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>
params = { 'C': [0.5, 1, 1.5], 'kernel': ['rbf', 'linear', 'poly', 'sigmoid'], 'gamma': [0.001, 0.0001], 'class_weight': [None, 'balanced'] } folds = 4 param_comb = 5 skf = StratifiedKFold(n_splits=folds, shuffle = True, random_state = 1001) random_search = RandomizedSearchCV(classifier, param_distributions=params, n_...
Titanic - Machine Learning from Disaster
1,266,101
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>
classifier = VotingClassifier(estimators=[('xgb', xgboost_classifier),('rf',randomforest_classifier),('svc',svc_classifier)], voting='soft') classifier.fit(X_train, y )
Titanic - Machine Learning from Disaster
1,266,101
seed_everything() glove_embeddings = load_glove(word_index) paragram_embeddings = load_para(word_index) embedding_matrix = np.mean([glove_embeddings, paragram_embeddings], axis=0) del glove_embeddings, paragram_embeddings gc.collect() np.shape(embedding_matrix )<split>
accuracies = cross_val_score(estimator=classifier, X=X_train, y=y, cv=5) print('accuracy mean: {0}'.format(accuracies.mean())) print('accuracy std: {0}'.format(accuracies.std()))
Titanic - Machine Learning from Disaster
1,266,101
splits = list(StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=SEED ).split(x_train, y_train)) splits[:3]<choose_model_class>
df_test = pd.read_csv('.. /input/test.csv') df_test.describe()
Titanic - Machine Learning from Disaster
1,266,101
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...
get_missing_data_table(df_test )
Titanic - Machine Learning from Disaster
1,266,101
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, e...
df_test = imput_nan_values(df_test,'Fare','median') df_test['Age'] = df_test['Age'].fillna(value=1000) name_row = df_test['Name'].copy() name_row = pd.DataFrame(name_row.str.split(', ',1 ).tolist() , columns = ['Last name', 'Name']) name_row = name_row['Name'].copy() name_row = pd.DataFrame(name_row.str.split('.',1 ...
Titanic - Machine Learning from Disaster
1,266,101
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...
df_test = df_test.drop('Cabin', axis='columns') df_test['Family Size'] = df_test['SibSp'] + df_test['Parch'] df_test = df_test.drop('SibSp', axis='columns') df_test = df_test.drop('Parch', axis='columns') df_test = df_test.drop('Name', axis='columns') df_test = df_test.drop('Ticket', axis='columns') df_test = df_t...
Titanic - Machine Learning from Disaster
1,266,101
<define_variables><EOS>
X_test = df_test.values sc = StandardScaler() X_test = sc.fit_transform(X_test) pred = classifier.predict(X_test) test_dataset = pd.read_csv('.. /input/test.csv') ps_id = test_dataset.iloc[:,0].values d = {'PassengerId':ps_id, 'Survived':pred} df = pd.DataFrame(data=d) df = df.set_index('PassengerId') df.to_csv('p...
Titanic - Machine Learning from Disaster
9,687,592
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<data_type_conversions>
import numpy as np import pandas as pd import seaborn as sns
Titanic - Machine Learning from Disaster
9,687,592
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 ).c...
train_raw_data=pd.read_csv('.. /input/titanic/train.csv') test_raw_data=pd.read_csv('.. /input/titanic/test.csv' )
Titanic - Machine Learning from Disaster
9,687,592
def bestThresshold(y_train,train_preds): tmp = [0,0,0] delta = 0 for tmp[0] in tqdm(np.arange(0.1, 0.501, 0.01)) : 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...
trainrow=train_raw_data.shape[0] testrow=test_raw_data.shape[0] y_train=train_raw_data['Survived'].copy() train_raw_data=train_raw_data.drop(['Survived'],1 )
Titanic - Machine Learning from Disaster
9,687,592
submission = df_test[['qid']].copy() submission['prediction'] =(test_preds > delta ).astype(int) submission.to_csv('submission.csv', index=False )<import_modules>
combine=pd.concat([train_raw_data,test_raw_data]) combine.head()
Titanic - Machine Learning from Disaster
9,687,592
from sklearn.model_selection import GridSearchCV,StratifiedKFold from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import cross_val_score,train_test_split from scipy import stats from sklearn import metrics from keras.models import Sequential from keras.layers import Dense from keras....
combine.isnull().sum()
Titanic - Machine Learning from Disaster
9,687,592
import time from tqdm import tqdm import math 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,CuDNNLSTM from keras.layers import Bidirectional, GlobalMaxPool1D from keras.m...
combine['Embarked']=combine['Embarked'].fillna(combine['Embarked'].value_counts().index[0] )
Titanic - Machine Learning from Disaster
9,687,592
df_train = pd.read_csv(".. /input/train.csv") df_test = pd.read_csv(".. /input/test.csv") print("train data shape --",df_train.shape) print("test data shape --",df_test.shape )<feature_engineering>
combine['Cabin']=combine['Cabin'].fillna('U') combine['Cabin'].value_counts() combine['Cabin']=combine['Cabin'].astype(str ).str[0] combine.head()
Titanic - Machine Learning from Disaster
9,687,592
df_train["question_text"] = df_train["question_text"].apply(lambda x: x.replace('.',' fullstop ')) df_train["question_text"] = df_train["question_text"].apply(lambda x: x.replace('?',' endofquestion ')) df_train["question_text"] = df_train["question_text"].apply(lambda x: x.replace(',',' comma ')) df_train["question_te...
combine.loc[combine['Fare'].isnull() ]
Titanic - Machine Learning from Disaster
9,687,592
df_train["question_text"] = df_train["question_text"].apply(lambda x: x.replace('fullstop','.')) df_train["question_text"] = df_train["question_text"].apply(lambda x: x.replace('endofquestion','?')) df_train["question_text"] = df_train["question_text"].apply(lambda x: x.replace('comma',',')) df_train["question_text"] =...
combine['Fare']=combine['Fare'].fillna(combine.loc[(combine['Pclass']==3)&(combine['Sex']=="male")&(combine['Age']<65)&(combine['Age']>55)].dropna() ['Fare'].mean() )
Titanic - Machine Learning from Disaster
9,687,592
df_test["question_text"] = df_test["question_text"].apply(lambda x: x.replace('.',' fullstop ')) df_test["question_text"] = df_test["question_text"].apply(lambda x: x.replace('?',' endofquestion ')) df_test["question_text"] = df_test["question_text"].apply(lambda x: x.replace(',',' comma ')) df_test["question_text"] = ...
passengerids=test_raw_data['PassengerId'] combine=combine.drop(['PassengerId','Ticket'],1 )
Titanic - Machine Learning from Disaster
9,687,592
df_test["question_text"] = df_test["question_text"].apply(lambda x: x.replace('fullstop','.')) df_test["question_text"] = df_test["question_text"].apply(lambda x: x.replace('endofquestion','?')) df_test["question_text"] = df_test["question_text"].apply(lambda x: x.replace('comma',',')) df_test["question_text"] = df_tes...
combine['familysize']=combine['SibSp']+combine['Parch']+1 combine.head()
Titanic - Machine Learning from Disaster
9,687,592
df_combined = pd.concat([df_train,df_test],axis=0) print("combined shape ",df_combined.shape )<define_variables>
combine['Title'] = combine.Name.str.extract('([A-Za-z]+)\.', expand=False) combine.head()
Titanic - Machine Learning from Disaster
9,687,592
embed_size = 300 max_features = 60000 maxlen = 60 total_X = df_combined["question_text"].values<feature_engineering>
combine['Title'].value_counts()
Titanic - Machine Learning from Disaster
9,687,592
tokenizer = Tokenizer(num_words=max_features,filters='" ',) tokenizer.fit_on_texts(list(total_X))<count_values>
combine=combine.drop(['Name'],1) combine.head()
Titanic - Machine Learning from Disaster
9,687,592
WORDS = tokenizer.word_counts print(len(WORDS))<prepare_x_and_y>
combine=combine.drop(['SibSp','Parch'],1) combine.head()
Titanic - Machine Learning from Disaster
9,687,592
train_X = df_train["question_text"].values test_X = df_test["question_text"].values<string_transform>
combine['Sex']=combine['Sex'].map({'male':0,'female':1}) combine.head()
Titanic - Machine Learning from Disaster
9,687,592
train_X = tokenizer.texts_to_sequences(train_X) test_X = tokenizer.texts_to_sequences(test_X )<prepare_x_and_y>
for i in range(0,2): for j in range(0,3): print(i,j+1) temp_dataset=combine[(combine['Sex']==i)&(combine['Pclass']==j+1)]['Age'].dropna() print(temp_dataset) combine.loc[(combine.Age.isnull())&(combine.Sex==i)&(combine.Pclass==j+1),'Age']=int(temp_dataset.median() )
Titanic - Machine Learning from Disaster
9,687,592
train_X = pad_sequences(train_X, maxlen=maxlen) test_X = pad_sequences(test_X, maxlen=maxlen) train_y = df_train['target'].values<categorify>
combine.isnull().sum()
Titanic - Machine Learning from Disaster
9,687,592
def get_embeddings(embedtype): if embedtype is "glove": EMBEDDING_FILE = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt' elif embedtype is "fastext": EMBEDDING_FILE = '.. /input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec' elif embedtype is "paragram": EMBEDDING_FILE = '.. /input/embeddings/paragram_3...
combine_checkpoint=combine.copy() combine.head()
Titanic - Machine Learning from Disaster
9,687,592
embedding_glove = get_embeddings(embedtype="glove" )<choose_model_class>
combine['Age_Band']=pd.cut(combine['Age'],5) combine['Age_Band'].unique()
Titanic - Machine Learning from Disaster
9,687,592
embedding_paragram = get_embeddings(embedtype="paragram" )<train_model>
combine.loc[(combine['Age']<=16.136),'Age']=1 combine.loc[(combine['Age']>16.136)&(combine['Age']<=32.102),'Age']=2 combine.loc[(combine['Age']>32.102)&(combine['Age']<=48.068),'Age']=3 combine.loc[(combine['Age']>48.068)&(combine['Age']<=64.034),'Age']=4 combine.loc[(combine['Age']>64.034)&(combine['Age']<=80.) ,'Age'...
Titanic - Machine Learning from Disaster
9,687,592
mean_gl_par_embedding = np.mean([embedding_glove,embedding_paragram],axis=0) print("mean glove paragram embedding shape--> ",mean_gl_par_embedding.shape )<set_options>
combine=combine.drop(['Age_Band'],1 )
Titanic - Machine Learning from Disaster
9,687,592
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...
combine['Fare_Band']=pd.cut(combine['Fare'],3) combine['Fare_Band'].unique()
Titanic - Machine Learning from Disaster
9,687,592
class CyclicLR(Callback): def __init__(self, base_lr=0.001, max_lr=0.006, step_size=2000., mode='triangular', gamma=1., scale_fn=None, scale_mode='cycle'): super(CyclicLR, self ).__init__() self.base_lr = base_lr self.max_lr = max_lr self.step_size = step_size self.mode = mode self.gamma = gamma if scale_fn == None: ...
combine.loc[(combine['Fare']<=170.776),'Fare']=1 combine.loc[(combine['Fare']>170.776)&(combine['Fare']<=314.553),'Fare']=2 combine.loc[(combine['Fare']>314.553)&(combine['Fare']<=513),'Fare']=3 combine=combine.drop(['Fare_Band'],1 )
Titanic - Machine Learning from Disaster
9,687,592
def build_model() : inp = Input(shape=(maxlen,)) x = Embedding(max_features, embed_size, weights=[mean_gl_par_embedding],trainable=False )(inp) x = SpatialDropout1D(rate=0.1 )(x) x1 = Bidirectional(CuDNNGRU(200, return_sequences=True))(x) x2 = Bidirectional(CuDNNGRU(128, return_sequences=True))(x) atten_1 = Attenti...
combine['Fare'].value_counts()
Titanic - Machine Learning from Disaster
9,687,592
def f1_smart(y_true, y_pred): args = np.argsort(y_pred) tp = y_true.sum() fs =(tp - np.cumsum(y_true[args[:-1]])) / np.arange(y_true.shape[0] + tp - 1, tp, -1) res_idx = np.argmax(fs) return 2 * fs[res_idx],(y_pred[args[res_idx]] + y_pred[args[res_idx + 1]])/ 2<split>
combine=pd.get_dummies(columns=['Pclass','Sex','Cabin','Embarked','Title','Age','Fare'],data=combine) combine.head()
Titanic - Machine Learning from Disaster
9,687,592
kfold = StratifiedKFold(n_splits=5, random_state=1990, shuffle=True) bestscore = [] y_test = np.zeros(( test_X.shape[0],)) filepath="weights_best_mean.h5" for i,(train_index, valid_index)in enumerate(kfold.split(train_X, train_y)) : X_train, X_val, Y_train, Y_val = train_X[train_index], train_X[valid_index], train_y[t...
x_train=combine.iloc[:trainrow] x_test=combine.iloc[trainrow:]
Titanic - Machine Learning from Disaster
9,687,592
print("mean threshold--> ",np.mean(bestscore))<save_to_csv>
from sklearn.preprocessing import StandardScaler
Titanic - Machine Learning from Disaster
9,687,592
print(y_test.shape) pred_test_y =(y_test>np.mean(bestscore)).astype(int) out_df = pd.DataFrame({"qid":df_test["qid"].values}) out_df['prediction'] = pred_test_y out_df.to_csv("submission.csv", index=False )<import_modules>
scaler=StandardScaler() scaler.fit(x_train) x_scaled_train=scaler.transform(x_train) x_scaled_train
Titanic - Machine Learning from Disaster
9,687,592
tqdm.pandas(desc='Progress') <set_options>
x_scaled_test=scaler.transform(x_test) x_scaled_test
Titanic - Machine Learning from Disaster
9,687,592
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() SEED=12345<define_variables>
reg=LogisticRegression() reg.fit(x_scaled_train,y_train) print(reg.score(x_scaled_train,y_train)) y_pred=reg.predict(x_scaled_test) y_pred
Titanic - Machine Learning from Disaster
9,687,592
embed_size = 300 max_features = 120000 maxlen = 80 batch_size = 256 n_epochs = 5 n_splits = 5 <train_model>
xgb=XGBClassifier() xgb.fit(x_scaled_train,y_train,early_stopping_rounds=5, eval_set=[(x_scaled_train, y_train)], verbose=False) print(xgb.score(x_scaled_train,y_train)) y_pred=xgb.predict(x_scaled_test )
Titanic - Machine Learning from Disaster
9,687,592
token = Tokenizer() token.fit_on_texts(["Let us learn on a example"]) print(token.texts_to_sequences(["Let us learn on a example"])) print(token.texts_to_sequences(["Let us hopefully learn on a example"]))<drop_column>
rfc=RandomForestClassifier(random_state=4,n_estimators=500,warm_start=True,max_depth=6,min_samples_leaf=2,max_features='sqrt') rfc.fit(x_scaled_train,y_train) print(rfc.score(x_scaled_train,y_train)) y_pred=rfc.predict(x_scaled_test )
Titanic - Machine Learning from Disaster
9,687,592
del token<load_from_csv>
submission = pd.DataFrame({ "PassengerId": passengerids, "Survived": y_pred }) submission
Titanic - Machine Learning from Disaster
9,687,592
df_train = pd.read_csv(".. /input/quora-insincere-questions-classification/train.csv") df_test = pd.read_csv(".. /input/quora-insincere-questions-classification/test.csv") df = pd.concat([df_train ,df_test],sort=True )<feature_engineering>
submission.to_csv('submission1.csv', index=False )
Titanic - Machine Learning from Disaster
1,472,711
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(c...
print(os.listdir(".. /input")) warnings.filterwarnings('ignore') plt.rcParams['figure.figsize'] =(16,9) sns.set_palette('gist_earth' )
Titanic - Machine Learning from Disaster
1,472,711
puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', ' '·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…', '“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾'...
df_train = pd.read_csv('.. /input/train.csv') df_test = pd.read_csv('.. /input/test.csv') full = pd.concat([df_train, df_test], axis = 0, sort=True) full.set_index('PassengerId', drop = False, inplace=True) train = full[:891] display(full.head(3)) print(f"Dataset contains {full.shape[0]} records, with {full.shape[1...
Titanic - Machine Learning from Disaster
1,472,711
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: f...
def parse_Cabin(cabin): if type(cabin)== str: m = re.search(r'([A-Z])+', cabin) return m.group(1) else: return 'X' full['Cabin_short'] = full['Cabin'].map(parse_Cabin )
Titanic - Machine Learning from Disaster
1,472,711
def load_and_prec() : train_df = pd.read_csv(".. /input/quora-insincere-questions-classification/train.csv") test_df = pd.read_csv(".. /input/quora-insincere-questions-classification/test.csv") print("Train shape : ",train_df.shape) print("Test shape : ",test_df.shape) train_df["question_text"] = train_df["question...
dict_fare_by_Pclass = dict(full.groupby('Pclass' ).Fare.mean()) missing_fare = full.loc[full.Fare.isnull() ,'Pclass'].map(dict_fare_by_Pclass) full.loc[full.Fare.isnull() ,'Fare'] = missing_fare
Titanic - Machine Learning from Disaster
1,472,711
x_train, x_test, y_train, features, test_features, word_index = load_and_prec()<save_model>
features = pd.DataFrame() features['Pclass'] = full['Pclass'] features['Fare'] = full['Fare'] features['Sex'] = full['Sex']
Titanic - Machine Learning from Disaster
1,472,711
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>
features['A5'] =(full['Ticket_short'] == 'A5' ).astype(int) features['PC'] =(full['Ticket_short'] == 'PC' ).astype(int )
Titanic - Machine Learning from Disaster
1,472,711
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()<load_from_csv>
dict_Title = {"Capt": "Officer", "Col": "Officer", "Major": "Officer", "Jonkheer": "Royalty", "Don": "Royalty", "Sir" : "Royalty", "Dr": "Officer", "Rev": "Officer", "the Countess":"Royalty", "Dona": "Royalty", "Mme": "Mrs", "Mlle": "Miss", "Ms": "Mrs", "Mr" : "Mr", "Mrs" : "Mrs", "Miss" : "Miss", "Master" : "Master", ...
Titanic - Machine Learning from Disaster
1,472,711
with open(".. /input/glove-wiki-twitter2550/glove.twitter.27B.50d.txt")as f: lines = f.readlines() lines = [line.rstrip().split() for line in lines] print(len(lines)) print(len(lines[0])) print(lines[99][0]) print(lines[99][1:]) print(len(lines[99][1:]))<set_options>
df_title = pd.DataFrame(title ).join(full[['Age','Survived']]) dict_age = df_title.groupby('Name' ).Age.mean() idx = full.Age.isnull() full.loc[idx,'Age'] = df_title.loc[idx, 'Name'].map(dict_age )
Titanic - Machine Learning from Disaster
1,472,711
del lines gc.collect()<statistical_test>
features['Title'] = df_title['Name'] features['Child'] =(full['Age'] <= 14 ).astype(int )
Titanic - Machine Learning from Disaster
1,472,711
def load_glove(word_index): EMBEDDING_FILE = '.. /input/quora-insincere-questions-classification/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(em...
def parse_surname(name): return name.split(',')[0] family = pd.DataFrame(full[['Parch','SibSp','Ticket']]) family['Family_size'] = 1 + family.Parch + family.SibSp family['Surname'] = full.Name.map(parse_surname) dict_scount = dict(family.groupby('Surname' ).Family_size.count()) dict_scode = dict(zip(dict_scount.keys...
Titanic - Machine Learning from Disaster
1,472,711
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.c...
surname2chk = family[family['Family_size'] < family['Surname_count']].Surname.unique() family['Surname_adj'] = family['Surname'] for s in surname2chk: family_regroup = family[family['Surname'] == s] fam_code_dict = tick2fam_gen(family_regroup) for idx in family_regroup.index: curr_ticket = full.loc[idx].Ticket fam_cod...
Titanic - Machine Learning from Disaster
1,472,711
splits = list(StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=SEED ).split(x_train, y_train)) splits[:3]<choose_model_class>
dict_fcount = dict(family.groupby('Surname_adj' ).Family_size.count()) dict_fcode = dict(zip(dict_fcount.keys() , range(len(dict_fcount)))) family['Family_code'] = family['Surname_adj'].map(dict_fcode) family['Family_count'] = family['Surname_adj'].map(dict_fcount) print(f"No.of Family Before Regrouping: {len(family...
Titanic - Machine Learning from Disaster
1,472,711
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...
group = pd.DataFrame(family[['Surname_code','Surname_count','Family_code','Family_count']]) dict_tcount = dict(full.groupby('Ticket' ).PassengerId.count()) dict_tcode = dict(zip(dict_tcount.keys() ,range(len(dict_tcount)))) group['Ticket_code'] = full.Ticket.map(dict_tcode) group['Ticket_count'] = full.Ticket.map(di...
Titanic - Machine Learning from Disaster
1,472,711
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...
def ChainCombineGroups(df, colA, colB): data = df.copy() search_df = data.copy() group_count = 0 while not search_df.empty: pool = search_df.iloc[:1] idx = pool.index search_df.drop(index = idx, inplace = True) flag_init = 1 update = pd.DataFrame() while(flag_init or not update.empty): flag_init = 0 pool_A_uniq = np...
Titanic - Machine Learning from Disaster
1,472,711
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, e...
group['Group_code'] = ChainCombineGroups(group, 'Family_code', 'Ticket_code') dict_gcount = dict(group.groupby('Group_code' ).Family_code.count()) group['Group_count'] = group.Group_code.map(dict_gcount) print(f"Family: {len(family['Family_code'].unique())}") print(f"Group: {len(group['Ticket_code'].unique())}") p...
Titanic - Machine Learning from Disaster
1,472,711
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_dr...
group_final = pd.concat([family[['Surname_code','Surname_count','Family_code','Family_count']], group[['Ticket_code','Ticket_count','Group_code','Group_count']], full['Survived']], axis = 1 )
Titanic - Machine Learning from Disaster
1,472,711
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 )<define_variables>
for param in [('Surname_code','Surname_count'), ('Family_code','Family_count'), ('Ticket_code','Ticket_count'), ('Group_code','Group_count')]: n_member_survived_by_gp = group_final.groupby(param[0] ).Survived.sum() n_mem_survived = group_final[param[0]].map(n_member_survived_by_gp) n_mem_survived_adj = n_mem_surviv...
Titanic - Machine Learning from Disaster
1,472,711
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...
features['Parch'] = full['Parch'] features['SibSp'] = full['SibSp'] features['Group_size'] = group['Group_count'] features.head()
Titanic - Machine Learning from Disaster
1,472,711
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 ).c...
scalar = StandardScaler() features_z_transformed = features.copy() continuous = ['Fare'] features_z_transformed[continuous] = scalar.fit_transform(features_z_transformed[continuous]) features_z_transformed.Sex = features_z_transformed.Sex.apply(lambda x: 1 if x == 'male' else 0) features_final = pd.get_dummies(featur...
Titanic - Machine Learning from Disaster
1,472,711
def bestThresshold(y_train,train_preds): tmp = [0,0,0] delta = 0 for tmp[0] in tqdm(np.arange(0.1, 0.501, 0.01)) : 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...
X_train, X_test, y_train, y_test = train_test_split(features_final_train, train.Survived, test_size = 0.2, random_state = 0 )
Titanic - Machine Learning from Disaster
1,472,711
submission = df_test[['qid']].copy() submission['prediction'] =(test_preds > delta ).astype(int) submission.to_csv('submission.csv', index=False )<import_modules>
clf_A = GradientBoostingClassifier(random_state = 0) clf_B = LogisticRegression(random_state= 0) clf_C = RandomForestClassifier(random_state= 0) samples_100 = len(y_train) samples_10 = int(len(y_train)/2) samples_1 = int(len(y_train)/10) results = {} for clf in [clf_A, clf_B, clf_C]: clf_name = clf.__class__.__na...
Titanic - Machine Learning from Disaster
1,472,711
tqdm.pandas()<load_from_csv>
warnings.filterwarnings('ignore') clf = RandomForestClassifier(random_state = 0, oob_score = True) parameters = {'criterion' :['gini'], 'n_estimators' : [350], 'max_depth':[5], 'min_samples_leaf': [4], 'max_leaf_nodes': [10], 'min_impurity_decrease': [0], 'max_features' : [1] } scorer = make_scorer(accuracy_score) g...
Titanic - Machine Learning from Disaster
1,472,711
<set_options><EOS>
final_predict = best_clf.predict(features_final_test) prediction = pd.DataFrame(full[891:].PassengerId) prediction['Survived'] = final_predict.astype('int') prediction.to_csv('predict.csv',index = False )
Titanic - Machine Learning from Disaster
8,119,418
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<compute_test_metric>
titanic = pd.read_csv("/kaggle/input/titanic/train.csv", sep=",") titanic_sub = pd.read_csv("/kaggle/input/titanic/test.csv", sep="," )
Titanic - Machine Learning from Disaster
8,119,418
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)]): 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...
split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42) for train_index, test_index in split.split(titanic, titanic['Sex']): train_set = titanic.loc[train_index] test_set = titanic.loc[test_index] train_set = train_set.reset_index(drop=True )
Titanic - Machine Learning from Disaster
8,119,418
def sigmoid(x): return 1 /(1 + np.exp(-x))<define_variables>
np.nanmean(train_set['Age'].loc[Title[Title == 'Miss'].index] )
Titanic - Machine Learning from Disaster
8,119,418
embed_size = 300 max_features = 95000 maxlen = 70<define_variables>
np.nanmean(train_set['Age'].loc[Title[Title == 'Mrs'].index] )
Titanic - Machine Learning from Disaster
8,119,418
puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', ' '·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…', '“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾'...
np.corrcoef(Family_members, People_on_ticket )
Titanic - Machine Learning from Disaster
8,119,418
train_df["question_text"] = train_df["question_text"].str.lower() test_df["question_text"] = test_df["question_text"].str.lower() train_df["question_text"] = train_df["question_text"].apply(lambda x: clean_text(x)) test_df["question_text"] = test_df["question_text"].apply(lambda x: clean_text(x)) x_train = train_df["qu...
sum(People_on_ticket<Family_members+1 )
Titanic - Machine Learning from Disaster
8,119,418
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,e...
sum(People_on_ticket>Family_members+1 )
Titanic - Machine Learning from Disaster
8,119,418
seed_everything() glove_embeddings = load_glove(tokenizer.word_index) paragram_embeddings = load_para(tokenizer.word_index) embedding_matrix = np.mean([glove_embeddings, paragram_embeddings], axis=0) np.shape(embedding_matrix )<split>
print("Average age of lone passenger: ", round(np.nanmean(train_set_lone['Age']),0), sep="") print("Number of missing Age values: ", sum(np.isnan(train_set_lone['Age'])) , " - ", round(( sum(np.isnan(train_set_lone['Age'])) *100/len(train_set_lone['Age'])) ,2), "% of train_set_lone.", sep="") print("The number of mis...
Titanic - Machine Learning from Disaster
8,119,418
splits = list(StratifiedKFold(n_splits=5, shuffle=True, random_state=10 ).split(x_train, y_train))<normalization>
outlier_ind = train_set.loc[train_set['Fare']==max(train_set['Fare'])].index train_set = train_set.drop(outlier_ind) train_set = train_set.reset_index(drop=True )
Titanic - Machine Learning from Disaster
8,119,418
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...
print("Minimum price for ticket in first class: ", min(train_set.loc[train_set['Pclass']==1]['Fare']), sep="" )
Titanic - Machine Learning from Disaster
8,119,418
class NeuralNet(nn.Module): def __init__(self): super(NeuralNet, self ).__init__() hidden_size = 40 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.D...
first_class = train_set.loc[train_set['Pclass']==1] second_class = train_set.loc[train_set['Pclass']==2] third_class = train_set.loc[train_set['Pclass']==3] p_class = list(train_set['Pclass']) fare = list(train_set['Fare']) Fare_class = list() for i in range(0,len(p_class)) : if(p_class[i] == 1): if(fare[i] < statist...
Titanic - Machine Learning from Disaster
8,119,418
batch_size = 512 n_epochs = 6<choose_model_class>
train_set_no_cabins = train_set.loc[np.where(pd.isnull(train_set['Cabin'])) ] train_set_cabins = train_set.loc[~train_set.index.isin(train_set_no_cabins.index)] train_set_cabins['Pclass'].value_counts()
Titanic - Machine Learning from Disaster
8,119,418
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...
print("Average age of Southampton passenger:", round(np.nanmean(train_set[train_set['Embarked'] == 'S']['Age']))) print("Average age of Queenstown passenger:", round(np.nanmean(train_set[train_set['Embarked'] == 'Q']['Age']))) print("Average age of Cherbourg passenger:", round(np.nanmean(train_set[train_set['Embarked...
Titanic - Machine Learning from Disaster
8,119,418
def f1_smart(y_true, y_pred): thresholds = [] for thresh in np.arange(0.1, 0.501, 0.01): thresh = np.round(thresh, 2) res = metrics.f1_score(y_true,(y_pred > thresh ).astype(int)) thresholds.append([thresh, res]) thresholds.sort(key=lambda x: x[1], reverse=True) best_thresh = thresholds[0][0] best_f1 = thresholds[0]...
train_set_known_age = train_set_age[~np.isnan(train_set_age['Age'])] train_set_known_age = train_set_known_age[(( train_set_known_age['Pclass']==3)& (train_set_known_age['Is_alone']==1)) |(train_set_known_age['Pclass']==3)] print("Percentage of single and/or third class passengers with a known age: ", round(len(train_...
Titanic - Machine Learning from Disaster
8,119,418
train_preds = np.zeros(( len(train_df))) test_preds = np.zeros(( len(test_df))) 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) best_thresholds = []...
from sklearn.base import BaseEstimator, TransformerMixin from sklearn.impute import SimpleImputer from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.preprocessing import OneHotEncoder from sklearn.pipeline import FeatureUnion from sklearn.preprocessing import StandardScaler
Titanic - Machine Learning from Disaster
8,119,418
search_result = threshold_search(y_train, train_preds) search_result<save_to_csv>
class TitleSelector(BaseEstimator, TransformerMixin): def __init__(self, attribute_names): self._attribute_names = attribute_names def fit(self, X, y=None): return self def get_title(self, obj): title =(( obj.rsplit(',', 1)[1] ).rsplit('.', 1)[0] ).strip() return title def transform(self, X): X.loc[:, 'Title'] = X[self...
Titanic - Machine Learning from Disaster
8,119,418
submission = test_df[['qid']].copy() submission['prediction'] = test_preds > search_result['threshold'] submission.to_csv('submission.csv', index=False )<set_options>
name = 'Name' name_pipeline = Pipeline(steps=[ ('get_title', TitleSelector(name)) ]) title = 'Title' title_pipeline = Pipeline(steps=[ ('code_title', TitleCoder(title)) ]) age = 'Age' age_pipeline = Pipeline(steps=[ ('code_age', AgeCoder(age)) ]) sibsp = 'SibSp' sibsp_pipeline = Pipeline(steps=[ ('code_sibsp', S...
Titanic - Machine Learning from Disaster
8,119,418
%matplotlib inline<load_from_csv>
train_set_prepared = full_pipeline.fit_transform(train_set) train_set_prepared = full_pipeline2.fit_transform(train_set) X_train_prepared = train_set_prepared y_train_prepared = train_set['Survived'] test_set_prepared = full_pipeline.fit_transform(test_set) test_set_prepared = full_pipeline2.fit_transform(test_set) ...
Titanic - Machine Learning from Disaster
8,119,418
test = pd.read_csv(".. /input/covid19-global-forecasting-week-4/test.csv") train = pd.read_csv(".. /input/covid19-global-forecasting-week-4/train.csv") test = test[test.Date > "2020-04-14"] all_data = pd.concat([train, test],ignore_index=True ).sort_values(by=['Country_Region','Province_State','Date']) all_data['Con...
rf_model = RandomForestClassifier(random_state=42) params_grid = [ {'n_estimators': [100, 200, 300, 400, 500], 'criterion': ['gini', 'entropy'], 'min_samples_split': [2, 3, 4, 5], 'max_features': ['auto', 'log2', None], 'bootstrap': ['True', 'False']} ] grid_search = GridSearchCV(rf_model, params_grid, cv=5, scoring="...
Titanic - Machine Learning from Disaster
8,119,418
data2 = all_data data2 = data2[data2.ConfirmedCases != 0] data2.loc[data2.ConfirmedCases == -1,"ConfirmedCases"] = 0 data2["Date"] = pd.to_datetime(data2.Date) data4 = data2[["Country_Region","Date"]].groupby("Country_Region" ).min() data4.columns = ["Date_min"] data2 = data2.merge(data4, how = 'left', left_on='Countr...
params_grid2 = [ {'n_estimators': [120, 140, 160, 180, 200, 220, 240, 260, 280], 'criterion': ['gini', 'entropy'], 'min_samples_split': [4, 5], 'max_features': ['auto', None], 'bootstrap': ['True']} ] grid_search2 = GridSearchCV(rf_model, params_grid2, cv=5, scoring="accuracy", n_jobs=1) grid_search2.fit(X_train_prepa...
Titanic - Machine Learning from Disaster