kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
11,312,907
matrixes = [embedding_matrix,embedding_matrix_glov,embedding_matrix_wiki,embedding_matrix_para] matrix = np.mean(matrixes,axis=0) del embedding_matrix,embedding_matrix_glov,embedding_matrix_wiki,embedding_matrix_para gc.collect()<import_modules>
spark = SparkSession.builder.appName('classification' ).getOrCreate()
Titanic - Machine Learning from Disaster
11,312,907
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...
from itertools import chain from pyspark.sql.functions import count, mean, when, lit, create_map, regexp_extract
Titanic - Machine Learning from Disaster
11,312,907
y_pred = model.predict(x_train,batch_size=batch_size, verbose=1) search_result = threshold_search(y_train, y_pred) print(search_result) y_pred = y_pred>search_result['threshold'] y_pred = y_pred.astype(int) print('RESULTS ON TRAINING SET: ',classification_report(y_train,y_pred)) y_pred = model.predict(x_test,batch_...
df1 = spark.read.csv('.. /input/titanic/train.csv',\ header=True, inferSchema=True) df2 = spark.read.csv('.. /input/titanic/test.csv', \ header=True, inferSchema=True )
Titanic - Machine Learning from Disaster
11,312,907
print('fiting final model...') n_epochs = len(history.history['loss'])- patience history = model.fit(x_train,y_train, batch_size=batch_size, epochs=n_epochs) print('fitting on full data done...' )<save_to_csv>
df1.limit(5 ).toPandas()
Titanic - Machine Learning from Disaster
11,312,907
print('Loading test data...') df_final = pd.read_csv('.. /input/test.csv') df_final["question_text"].fillna("_ x_final=tokenizer.texts_to_sequences(df_final['question_text']) x_final = pad_sequences(x_final,maxlen=max_len) y_pred = model.predict(x_final,batch_size=batch_size,verbose=1) y_pred = y_pred > search_res...
print('Number of rows: \t', df1.count()) print('Number of columns: \t', len(df1.columns))
Titanic - Machine Learning from Disaster
11,312,907
tqdm.pandas() <load_from_csv>
for col in df1.columns: print(col.ljust(20), df1.filter(df1[col].isNull() ).count() )
Titanic - Machine Learning from Disaster
11,312,907
train = pd.read_csv(".. /input/train.csv") test = pd.read_csv(".. /input/test.csv") print("Train shape : ", train.shape) print("Test shape : ", test.shape )<feature_engineering>
df1 = df1.fillna({'Embarked': 'S', 'Fare':14.45} )
Titanic - Machine Learning from Disaster
11,312,907
train["question_text"] = train["question_text"].str.lower() test["question_text"] = test["question_text"].str.lower() puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', ' '·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', ...
df1 = age_imputer(df1, 'Mr', 33.02) df1 = age_imputer(df1, 'Mrs', 35.98) df1 = age_imputer(df1, 'Miss', 21.86) df1 = age_imputer(df1, 'Master', 4.75 )
Titanic - Machine Learning from Disaster
11,312,907
embed_size = 300 max_features = None maxlen = 72 X = train["question_text"].fillna("_na_" ).values X_test = test["question_text"].fillna("_na_" ).values tokenizer = Tokenizer(num_words=max_features) tokenizer.fit_on_texts(list(X)) X = tokenizer.texts_to_sequences(X) X_test = tokenizer.texts_to_sequences(X_test) X = ...
df1 = df1.withColumn('FamilySize', df1['Parch'] + df1['SibSp'] ).\ drop('Parch', 'SibSp' )
Titanic - Machine Learning from Disaster
11,312,907
del train, test gc.collect()<statistical_test>
df1 = df1.drop('PassengerID', 'Cabin', 'Name', 'Ticket', 'Title' )
Titanic - Machine Learning from Disaster
11,312,907
word_index = tokenizer.word_index max_features = len(word_index)+1 def load_glove(word_index): EMBEDDING_FILE = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FIL...
for col in df1.columns: print(col.ljust(20), df1.filter(df1[col].isNull() ).count() )
Titanic - Machine Learning from Disaster
11,312,907
embedding_matrix_1 = load_glove(word_index) embedding_matrix_3 = load_para(word_index) embedding_matrix = np.mean(( embedding_matrix_1, embedding_matrix_3), axis=0) del embedding_matrix_1, embedding_matrix_3 gc.collect() np.shape(embedding_matrix )<statistical_test>
RandomForestClassifier, GBTClassifier
Titanic - Machine Learning from Disaster
11,312,907
def squash(x, axis=-1): s_squared_norm = K.sum(K.square(x), axis, keepdims=True) scale = K.sqrt(s_squared_norm + K.epsilon()) return x / scale class Capsule(Layer): def __init__(self, num_capsule, dim_capsule, routings=3, kernel_size=(9, 1), share_weights=True, activation='default', **kwargs): super(Capsule, self )._...
stringIndex = StringIndexer(inputCols=['Sex', 'Embarked'], outputCols=['SexNum', 'EmbNum']) stringIndex_model = stringIndex.fit(df1) df1_ = stringIndex_model.transform(df1 ).drop('Sex', 'Embarked') df1_.show(4 )
Titanic - Machine Learning from Disaster
11,312,907
def capsule(inp): x = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False )(inp) x = SpatialDropout1D(rate=0.24 )(x) x = Bidirectional(CuDNNLSTM(100, return_sequences=True, kernel_initializer=glorot_normal(seed=123000), recurrent_initializer=orthogonal(gain=1.0, seed=10000)) )(x) x = Caps...
vec_asmbl = VectorAssembler(inputCols=df1_.columns[1:], outputCol='features') df1_ = vec_asmbl.transform(df1_ ).select('features', 'Survived') df1_.show(4, truncate=False )
Titanic - Machine Learning from Disaster
11,312,907
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<train_model>
train_df, valid_df = df1_.randomSplit([0.7, 0.3] )
Titanic - Machine Learning from Disaster
11,312,907
f1, threshold = f1_smart(np.squeeze(Y), oof) print('Optimal F1: {:.4f} at threshold: {:.4f}'.format(f1, threshold))<compute_test_metric>
evaluator = MulticlassClassificationEvaluator(labelCol='Survived', metricName='accuracy' )
Titanic - Machine Learning from Disaster
11,312,907
np.mean(bestscore), np.mean(logloss )<save_to_csv>
ridge = LogisticRegression(labelCol='Survived', maxIter=100, elasticNetParam=0, regParam=0.03) model = ridge.fit(train_df) pred = model.transform(valid_df) evaluator.evaluate(pred )
Titanic - Machine Learning from Disaster
11,312,907
y_test = y_test.reshape(( -1, 1)) pred_test_y =(y_test>threshold ).astype(int) sub['prediction'] = pred_test_y sub.to_csv("submission.csv", index=False )<load_pretrained>
lasso = LogisticRegression(labelCol='Survived', maxIter=100, elasticNetParam=1, regParam=0.0003) model = lasso.fit(train_df) pred = model.transform(valid_df) evaluator.evaluate(pred )
Titanic - Machine Learning from Disaster
11,312,907
def save_model(model, model_path): torch.save(model.state_dict() , model_path) def load_model(model, model_path, use_cuda=False): map_location = 'cpu' if use_cuda and torch.cuda.is_available() : map_location = 'cuda:0' model.load_state_dict(torch.load(model_path, map_location)) return model<init_hyperparams>
rf = RandomForestClassifier(labelCol='Survived', numTrees=100, maxDepth=3) model = rf.fit(train_df) pred = model.transform(valid_df) evaluator.evaluate(pred )
Titanic - Machine Learning from Disaster
11,312,907
class TextCNN(nn.Module): def __init__(self, args): super(TextCNN, self ).__init__() vocab_size = args["vocab_size"] pretrained_embed = args["pretrained_embed"] padding_idx = args["padding_idx"] num_classes = 1 kernel_nums = [100, 100, 100] kernel_sizes = [3, 4, 5] embed_dim = 300 hidden_dim = 100 drop_prob = 0.5 if ...
gb = GBTClassifier(labelCol='Survived', maxIter=75, maxDepth=3) model = gb.fit(train_df) pred = model.transform(valid_df) evaluator.evaluate(pred )
Titanic - Machine Learning from Disaster
11,312,907
train_path = '.. /input/train.csv' test_path = '.. /input/test.csv' embed_path = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt' submission_path = './submission.csv' model_path = './default_model.pkl'<create_dataframe>
for col in df2.columns: print(col.ljust(20), df2.filter(df2[col].isNull() ).count() )
Titanic - Machine Learning from Disaster
11,312,907
def pre() : print("Pre-processing...") fix_length = 100 text = torchtext.data.Field( sequential=True, use_vocab=True, lower=True, tokenize=nltk.word_tokenize, batch_first=True, is_target=False, fix_length=fix_length) target = torchtext.data.Field( sequential=False, use_vocab=False, batch_first=True, is_target=Tru...
df2 = df2.fillna({'Embarked': 'S', 'Fare':14.45}) df2 = df2.withColumn('FamilySize', df2['Parch'] + df2['SibSp'] ).\ drop('Parch', 'SibSp' )
Titanic - Machine Learning from Disaster
11,312,907
args = pre()<train_on_grid>
df2 = age_imputer(df2, 'Mr', 33.02) df2 = age_imputer(df2, 'Mrs', 35.98) df2 = age_imputer(df2, 'Miss', 21.86) df2 = age_imputer(df2, 'Master', 4.75) df2 = df2.drop('Cabin', 'Name', 'Ticket', 'Title') df2.show(4 )
Titanic - Machine Learning from Disaster
11,312,907
def train(**args): print("Training...") data_train = args["data_train"] pretrained_embed = data_train.fields["text"].vocab.vectors model_args = { "vocab_size": args["vocab_size"], "padding_idx": args["padding_idx"], "pretrained_embed": pretrained_embed, } model = TextCNN(model_args) trainer_args = { "epochs": 8, "b...
for col in df2.columns: print(col.ljust(20), df2.filter(df2[col].isNull() ).count() )
Titanic - Machine Learning from Disaster
11,312,907
train(**args )<train_on_grid>
pred_test = model_final.transform(df2) predictions = pred_test.select('PassengerId', 'prediction') predictions = predictions.\ withColumn('Survived', predictions['prediction'].\ cast('integer')).drop('prediction') predictions.show(5 )
Titanic - Machine Learning from Disaster
11,312,907
def test(**args): print("Testing...") model_args = { "vocab_size": args["vocab_size"], "padding_idx": args["padding_idx"], "pretrained_embed": None, } model = TextCNN(model_args) load_model(model, model_path, use_cuda=True) tester_args = { "batch_size": 128, "use_cuda": True, } tester = Tester(**tester_args) data...
predictions.coalesce(1 ).write.csv('submission_file.csv', header=True )
Titanic - Machine Learning from Disaster
11,312,907
def infer(**args): print("Predicting...") model_args = { "vocab_size": args["vocab_size"], "padding_idx": args["padding_idx"], "pretrained_embed": None, } model = TextCNN(model_args) load_model(model, model_path, use_cuda=True) predictor = Predictor(batch_size=128, use_cuda=False) data_test = args["data_test"] th...
spark.read.csv('submission_file.csv', header=True ).show(4 )
Titanic - Machine Learning from Disaster
11,312,907
warnings.filterwarnings("ignore") all_files = glob.glob(".. /input/cellstack/*.csv") all_files<save_to_csv>
predictions.toPandas().to_csv('submission.csv', index=False )
Titanic - Machine Learning from Disaster
11,312,907
<define_variables><EOS>
model_final.write().save('titanic_classification.model' )
Titanic - Machine Learning from Disaster
8,445,839
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<load_from_csv>
warnings.filterwarnings('ignore' )
Titanic - Machine Learning from Disaster
8,445,839
outs = [pd.read_csv(f, index_col=0)for f in all_files] concat_sub = pd.concat(outs, axis=1) cols = list(map(lambda x: "m" + str(x), range(len(concat_sub.columns)))) concat_sub.columns = cols concat_sub.reset_index(inplace=True )<feature_engineering>
df_train = pd.read_csv('.. /input/titanic/train.csv') df_test = pd.read_csv('.. /input/titanic/test.csv' )
Titanic - Machine Learning from Disaster
8,445,839
rank = np.tril(concat_sub.iloc[:,1:].corr().values,-1) m =(rank>0 ).sum() m_gmean, s = 0, 0 for n in range(min(rank.shape[0],m)) : mx = np.unravel_index(rank.argmin() , rank.shape) w =(m-n)/(m+n/10) print(w) m_gmean += w*(np.log(concat_sub.iloc[:,mx[0]+1])+np.log(concat_sub.iloc[:,mx[1]+1])) /2 s += w rank[mx] = 1 ...
df_test['Survived'] = 999
Titanic - Machine Learning from Disaster
8,445,839
predict_list = [] predict_list.append(pd.read_csv(".. /input/cellstack/submission-174.csv")[LABELS].values) predict_list.append(pd.read_csv(".. /input/cellstack/submission-201.csv")[LABELS].values) predict_list.append(pd.read_csv(".. /input/cellstack/submission-231.csv")[LABELS].values )<save_to_csv>
df = pd.concat([df_train , df_test] , axis = 0) print(df_train.shape) print(df_test.shape) print('Combined dataframe shape :',df.shape )
Titanic - Machine Learning from Disaster
8,445,839
warnings.filterwarnings("ignore") print("Rank averaging on ", len(predict_list), " files") predictions = np.zeros_like(predict_list[0]) for predict in predict_list: for i in range(1): predictions[:, i] = np.add(predictions[:, i], rankdata(predict[:, i])/predictions.shape[0]) predictions = predictions /len(predict_l...
print('The number of null values in age columns',df['Age'].isnull().sum()) print('The % of null values in age columns',round(df['Age'].isnull().mean() * 100,2))
Titanic - Machine Learning from Disaster
8,445,839
sub_path = ".. /input/cellstack" all_files = os.listdir(sub_path) all_files<feature_engineering>
print('The number of null values in cabin columns',df['Cabin'].isnull().sum()) print('The % of null values in cabin columns',round(df['Cabin'].isnull().mean() * 100,2))
Titanic - Machine Learning from Disaster
8,445,839
concat_sub['m_max'] = concat_sub.iloc[:, 1:ncol].max(axis=1) concat_sub['m_min'] = concat_sub.iloc[:, 1:ncol].min(axis=1) concat_sub['m_median'] = concat_sub.iloc[:, 1:ncol].median(axis=1 )<define_variables>
df.drop(columns = 'Cabin' , inplace = True )
Titanic - Machine Learning from Disaster
8,445,839
cutoff_lo = 0.8 cutoff_hi = 0.2<save_to_csv>
print('The number of null values in Embarked is ', df['Embarked'].isnull().sum() )
Titanic - Machine Learning from Disaster
8,445,839
concat_sub['sirna'] = m_gmean.astype(int) concat_sub[['id_code','sirna']].to_csv('stack_mean.csv', index=False, float_format='%.6f' )<save_to_csv>
df['Embarked'].replace({np.nan:'S'} , inplace = True )
Titanic - Machine Learning from Disaster
8,445,839
concat_sub['sirna'] = concat_sub['m_median'].astype(int) concat_sub[['id_code','sirna']].to_csv('stack_median.csv', index=False, float_format='%.6f' )<save_to_csv>
df[df['Fare'].isnull() ]
Titanic - Machine Learning from Disaster
8,445,839
concat_sub['sirna'] = np.where(np.all(concat_sub.iloc[:,1:ncol] > cutoff_lo, axis=1), 1, np.where(np.all(concat_sub.iloc[:,1:ncol] < cutoff_hi, axis=1), 0, concat_sub['m_median'])) concat_sub[['id_code','sirna']].to_csv('stack_pushout_median.csv', index=False, float_format='%.6f' )<feature_engineering>
df['Name'].isnull().sum()
Titanic - Machine Learning from Disaster
8,445,839
concat_sub['m_mean'] = m_gmean.astype(int) concat_sub['sirna'] = np.where(np.all(concat_sub.iloc[:,1:ncol] > cutoff_lo, axis=1), concat_sub['m_max'], np.where(np.all(concat_sub.iloc[:,1:ncol] < cutoff_hi, axis=1), concat_sub['m_min'], concat_sub['m_mean'])).astype(int) concat_sub[['id_code','sirna']].to_csv('stack_mi...
def GetTitle_temp(name): fname_title = name.split(',')[1] title = fname_title.split('.')[0] title = title.strip().lower() return title df.Name.map(GetTitle_temp ).value_counts()
Titanic - Machine Learning from Disaster
8,445,839
concat_sub['sirna'] = np.where(np.all(concat_sub.iloc[:,1:ncol] > cutoff_lo, axis=1), concat_sub['m_max'], np.where(np.all(concat_sub.iloc[:,1:ncol] < cutoff_hi, axis=1), concat_sub['m_min'], concat_sub['m_median'])).astype(int) concat_sub[['id_code','sirna']].to_csv('stack_minmax_median.csv', index=False, float_forma...
df['Parch'].value_counts()
Titanic - Machine Learning from Disaster
8,445,839
SIZE = 224 NUM_CLASSES = 1108 train_csv = pd.read_csv(".. /input/recursion-cellular-image-classification/train.csv") test_csv = pd.read_csv(".. /input/recursion-cellular-image-classification/test.csv") sub = pd.read_csv(".. /input/recursion-cellular-keras-densenet/submission.csv" )<concatenate>
df['SibSp'].value_counts()
Titanic - Machine Learning from Disaster
8,445,839
np.stack([train_csv.plate.values[train_csv.sirna == i] for i in range(10)] ).transpose()<count_values>
df['Accomp'] = df['SibSp'] + df['Parch'] df.drop(columns = ['SibSp' , 'Parch'] , inplace = True )
Titanic - Machine Learning from Disaster
8,445,839
train_csv.loc[train_csv.sirna==0,'plate'].value_counts()<count_values>
df['Sex'].value_counts()
Titanic - Machine Learning from Disaster
8,445,839
plate_groups = np.zeros(( 1108,4), int) for sirna in range(1108): grp = train_csv.loc[train_csv.sirna==sirna,:].plate.value_counts().index.values assert len(grp)== 3 plate_groups[sirna,0:3] = grp plate_groups[sirna,3] = 10 - grp.sum() plate_groups[:10,:]<feature_engineering>
df['Sex'] = df['Sex'].map({'female':0 , 'male':1 } )
Titanic - Machine Learning from Disaster
8,445,839
all_test_exp = test_csv.experiment.unique() group_plate_probs = np.zeros(( len(all_test_exp),4)) for idx in range(len(all_test_exp)) : preds = sub.loc[test_csv.experiment == all_test_exp[idx],'sirna'].values pp_mult = np.zeros(( len(preds),1108)) pp_mult[range(len(preds)) ,preds] = 1 sub_test = test_csv.loc[test_csv.ex...
df.drop(columns = ['Ticket'] , inplace = True )
Titanic - Machine Learning from Disaster
8,445,839
pd.DataFrame(group_plate_probs, index = all_test_exp )<groupby>
cat = pd.get_dummies(df[['Embarked' , 'Name']] , drop_first=True )
Titanic - Machine Learning from Disaster
8,445,839
exp_to_group = group_plate_probs.argmax(1) print(exp_to_group )<choose_model_class>
df = pd.concat([df,cat] , axis = 1) df.drop(columns = ['Embarked' , 'Name'] , inplace = True )
Titanic - Machine Learning from Disaster
8,445,839
def create_model(input_shape,n_out): input_tensor = Input(shape=input_shape) base_model = DenseNet121(include_top=False, weights=None, input_tensor=input_tensor) x = GlobalAveragePooling2D()(base_model.output) x = Dense(1024, activation='relu' )(x) final_output = Dense(n_out, activation='softmax', name='final_outpu...
df.isnull().mean() *100
Titanic - Machine Learning from Disaster
8,445,839
model = create_model(input_shape=(SIZE,SIZE,3),n_out=NUM_CLASSES )<load_pretrained>
knn_imputer = KNN() df_knn = df.copy() df_knn.iloc[:,:] = knn_imputer.fit_transform(df_knn )
Titanic - Machine Learning from Disaster
8,445,839
model.load_weights('.. /input/recursion-cellular-keras-densenet/Densenet121.h5' )<predict_on_test>
MICE_imputer = IterativeImputer() df_mice = df.copy() df_mice.iloc[:,:] = knn_imputer.fit_transform(df_mice )
Titanic - Machine Learning from Disaster
8,445,839
predicted = [] for i, name in tqdm(enumerate(test_csv['id_code'])) : path1 = os.path.join('.. /input/recursion-cellular-image-classification-224-jpg/test/test/', name+'_s1.jpeg') image1 = cv2.imread(path1) score_predict1 = model.predict(( image1[np.newaxis])/255) path2 = os.path.join('.. /input/recursion-cellular-im...
X, y = dfm_train.drop(columns = ['Survived','PassengerId']), dfm_train['Survived'] X_train, X_test, y_train, y_test= train_test_split(X, y,test_size=0.2, random_state=123) xg_cl = xgb.XGBClassifier(objective='binary:logistic', n_estimators=20, seed=123) xg_cl.fit(X_train, y_train) preds = xg_cl.predict(X_test) accu...
Titanic - Machine Learning from Disaster
8,445,839
def select_plate_group(pp_mult, idx): sub_test = test_csv.loc[test_csv.experiment == all_test_exp[idx],:] assert len(pp_mult)== len(sub_test) mask = np.repeat(plate_groups[np.newaxis, :, exp_to_group[idx]], len(pp_mult), axis=0)!= \ np.repeat(sub_test.plate.values[:, np.newaxis], 1108, axis=1) pp_mult[mask] = 0 retur...
confusion_matrix(y_test , preds )
Titanic - Machine Learning from Disaster
8,445,839
for idx in range(len(all_test_exp)) : indices =(test_csv.experiment == all_test_exp[idx]) preds = predicted[indices,:].copy() preds = select_plate_group(preds, idx) sub.loc[indices,'sirna'] = preds.argmax(1 )<load_from_csv>
y_pred = xg_cl.predict(dfm_test.drop(columns='PassengerId')).astype('int') results = pd.DataFrame(data={'PassengerId':dfm_test['PassengerId'].astype('int'), 'Survived':y_pred}) results.to_csv('Titanic Prediction_XGB.csv', index=False )
Titanic - Machine Learning from Disaster
8,445,839
( sub.sirna == pd.read_csv(".. /input/recursion-cellular-keras-densenet/submission.csv" ).sirna ).mean()<save_to_csv>
X, y = dfm_train.drop(columns = ['Survived','PassengerId']), dfm_train['Survived'] X_train, X_test, y_train, y_test= train_test_split(X, y,test_size=0.2, random_state=123) params = { 'min_child_weight': [1, 3,5,7 , 10], 'gamma': [0.5, 1, 1.5, 2,3,4, 5], 'subsample': [0.6,0.7, 0.8,0.9, 1.0], 'colsample_bytree': [0.6,0....
Titanic - Machine Learning from Disaster
8,445,839
sub.to_csv('.. /working/submission.csv', index=False, columns=['id_code','sirna'] )<feature_engineering>
random_search.best_params_
Titanic - Machine Learning from Disaster
8,445,839
os.environ['CUDA_LAUNCH_BLOCKING'] = '1' <set_options>
y_test = random_search.predict(dfm_test.drop(columns='PassengerId')).astype('int') results = pd.DataFrame(data={'PassengerId':dfm_test['PassengerId'].astype('int'), 'Survived':y_test}) results.to_csv('Titanic Prediction_XGB_hp.csv', index=False)
Titanic - Machine Learning from Disaster
8,445,839
def seed_everything(seed): 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 = 0 seed_everything(SEED )<load_from_csv>
X, y = dfm_train.drop(columns = ['Survived','PassengerId']), dfm_train['Survived'] X_train, X_test, y_train, y_test= train_test_split(X, y,test_size=0.2, random_state=123) params = { 'min_child_weight': [1, 3,5,7 , 10], 'gamma': [0.5, 1, 1.5, 2,3,4, 5], 'subsample': [0.6,0.7, 0.8,0.9, 1.0], 'colsample_bytree': [0.6,0....
Titanic - Machine Learning from Disaster
8,445,839
train_df = pd.read_csv('.. /input/train.csv') train_df.head(10 )<categorify>
y_test = random_search.predict(dfm_test.drop(columns='PassengerId')).astype('int') results = pd.DataFrame(data={'PassengerId':dfm_test['PassengerId'].astype('int'), 'Survived':y_test}) results.to_csv('Titanic Predictionkn.csv', index=False)
Titanic - Machine Learning from Disaster
8,445,839
def generate_df(train_df,sample_num=1): train_df['path'] = train_df['experiment'].str.cat(train_df['plate'].astype(str ).str.cat(train_df['well'],sep='/'),sep='/Plate')+ '_s'+str(sample_num)+ '_w' train_df = train_df.drop(columns=['id_code','experiment','plate','well'] ).reindex(columns=['path','sirna']) return train_...
knn = KNeighborsClassifier() params = { 'n_neighbors' : sp_randint(1 , 20), 'p' : sp_randint(1 , 5), } rsearch_knn = RandomizedSearchCV(knn , param_distributions = params , cv = 3 , random_state= 3 , n_jobs = -1 , return_train_score=True) rsearch_knn.fit(X , y )
Titanic - Machine Learning from Disaster
8,445,839
il = MultiChannelImageList.from_df(df=proc_train_df,path='.. /input/train/' )<categorify>
rsearch_knn.best_params_
Titanic - Machine Learning from Disaster
8,445,839
def image2np(image:Tensor)->np.ndarray: "Convert from torch style `image` to numpy/matplotlib style." res = image.cpu().permute(1,2,0 ).numpy() if res.shape[2]==1: return res[...,0] elif res.shape[2]>3: return res[...,:3] else: return res vision.image.image2np = image2np<split>
rfc = RandomForestClassifier(random_state=3) params = { 'n_estimators' : sp_randint(50 , 200), 'max_features' : sp_randint(1 , 12), 'max_depth' : sp_randint(2,10), 'min_samples_split' : sp_randint(2,20), 'min_samples_leaf' : sp_randint(1,20), 'criterion' : ['gini' , 'entropy'] } rsearch_rfc = RandomizedSearchCV(rfc , ...
Titanic - Machine Learning from Disaster
8,445,839
train_df,val_df = train_test_split(proc_train_df,test_size=0.035, stratify = proc_train_df.sirna, random_state=42) _proc_train_df = pd.concat([train_df,val_df] )<categorify>
rsearch_rfc.best_params_
Titanic - Machine Learning from Disaster
8,445,839
data =(MultiChannelImageList.from_df(df=_proc_train_df,path='.. /input/train/') .split_by_idx(list(range(len(train_df),len(_proc_train_df)))) .label_from_df() .transform(get_transforms() ,size=256) .databunch(bs=128,num_workers=4) .normalize() )<define_variables>
lr = LogisticRegression(solver = 'liblinear') knn = KNeighborsClassifier(**rsearch_knn.best_params_) rfc = RandomForestClassifier(**rsearch_rfc.best_params_) clf = VotingClassifier(estimators=[('lr' ,lr),('knn' , knn),('rfc' , rfc)] , voting = 'soft') clf.fit(X , y )
Titanic - Machine Learning from Disaster
8,445,839
data.show_batch()<install_modules>
y_test = clf.predict(dfm_test.drop(columns='PassengerId')).astype('int') results = pd.DataFrame(data={'PassengerId':dfm_test['PassengerId'].astype('int'), 'Survived':y_test}) results.to_csv('Titanic Prediction_Stack.csv', index=False)
Titanic - Machine Learning from Disaster
8,445,839
!pip install efficientnet_pytorch<import_modules>
X, y = dfm_train.drop(columns = ['Survived','PassengerId']), dfm_train['Survived'] X_train, X_test, y_train, y_test= train_test_split(X, y,test_size=0.2, random_state=123 )
Titanic - Machine Learning from Disaster
8,445,839
from efficientnet_pytorch import *<choose_model_class>
RFM = RandomForestClassifier(criterion='gini', n_estimators=1750, max_depth=7, min_samples_split=6, min_samples_leaf=6, max_features='auto', oob_score=True, random_state=123, n_jobs=-1, verbose=1) RFM.fit(X,y )
Titanic - Machine Learning from Disaster
8,445,839
RESNET_MODELS = { 18: torchvision.models.resnet18, 34: torchvision.models.resnet34, 50: torchvision.models.resnet50, 101: torchvision.models.resnet101, 152: torchvision.models.resnet152, } def resnet_multichannel(depth=50,pretrained=True,num_classes=1108,num_channels=6): model = RESNET_MODELS[depth](pretrained=pretra...
y_pred = RFM.predict(X_test )
Titanic - Machine Learning from Disaster
8,445,839
def resnet18(pretrained,num_channels=6): return resnet_multichannel(depth=18,pretrained=pretrained,num_channels=num_channels) def _resnet_split(m): return(m[0][6],m[1]) def densenet161(pretrained,num_channels=6): return densenet_multichannel(depth=161,pretrained=pretrained,num_channels=num_channels) def _densenet_sp...
y_test = RFM.predict(dfm_test.drop(columns='PassengerId')).astype('int') results = pd.DataFrame(data={'PassengerId':dfm_test['PassengerId'].astype('int'), 'Survived':y_test}) results.to_csv('Titanic PredictionRFM.csv', index=False)
Titanic - Machine Learning from Disaster
8,445,839
learn = Learner(data, efficientnetb0() ,metrics=[accuracy] ).to_fp16() learn.path = Path('.. /' )<train_model>
X, y = dfm_train.drop(columns = ['Survived','PassengerId']), dfm_train['Survived'] X_train, X_test, y_train, y_test= train_test_split(X, y,test_size=0.2, random_state=123 )
Titanic - Machine Learning from Disaster
8,445,839
learn.unfreeze() <train_model>
clf_ET = ExtraTreesClassifier(random_state=0, bootstrap=True, oob_score=True) sss = model_selection.StratifiedShuffleSplit(n_splits=10, test_size=0.33, random_state= 0) sss.get_n_splits(X, y) parameters = {'n_estimators' : np.r_[10:210:10], 'max_depth': np.r_[1:6] } grid = model_selection.GridSearchCV(clf_ET, param_...
Titanic - Machine Learning from Disaster
8,445,839
learn.fit_one_cycle(18,1e-3 )<load_from_csv>
y_test = RFM.predict(dfm_test.drop(columns='PassengerId')).astype('int') results = pd.DataFrame(data={'PassengerId':dfm_test['PassengerId'].astype('int'), 'Survived':y_test}) results.to_csv('Titanic PredictionETC.csv', index=False )
Titanic - Machine Learning from Disaster
7,904,086
test_df = pd.read_csv('.. /input/test.csv') proc_test_df = generate_df(test_df.copy() )<create_dataframe>
%matplotlib inline test_full = pd.read_csv(".. /input/titanic/test.csv",index_col="PassengerId") train_full = pd.read_csv(".. /input/titanic/train.csv",index_col = "PassengerId") target = train_full.Survived train = train_full.drop(['Name','Survived'],axis=1) test = test_full.drop(['Name'],axis=1) sns.pairplot(trai...
Titanic - Machine Learning from Disaster
7,904,086
data_test = MultiChannelImageList.from_df(df=proc_test_df,path='.. /input/test/') learn.data.add_test(data_test )<predict_on_test>
[(col,train[col].nunique())for col in train.select_dtypes('object')]
Titanic - Machine Learning from Disaster
7,904,086
preds, _ = learn.get_preds(DatasetType.Test )<prepare_output>
train.isnull().sum()
Titanic - Machine Learning from Disaster
7,904,086
preds_ = preds.argmax(dim=-1 )<load_from_csv>
train.isnull().sum()
Titanic - Machine Learning from Disaster
7,904,086
submission_df = pd.read_csv('.. /input/sample_submission.csv' )<data_type_conversions>
imputer = SimpleImputer(missing_values=np.nan,strategy='most_frequent',add_indicator=True) train_preprocessed = pd.DataFrame(imputer.fit_transform(train),columns=[col for col in train] + ['Age_na','Cabin_na','Embarked_na'],index = train.index) test_preprocessed = pd.DataFrame(imputer.transform(test),columns=[col for ...
Titanic - Machine Learning from Disaster
7,904,086
submission_df.sirna = preds_.numpy().astype(int) submission_df.head(10 )<save_to_csv>
LE = LabelEncoder() for col in [col for col in train.select_dtypes('object')]: train_preprocessed[col] = LE.fit_transform(train_preprocessed[col]) test_preprocessed[col] = LE.fit_transform(test_preprocessed[col]) train_preprocessed = train_preprocessed.astype('float64') test_preprocessed = test_preprocessed.astype('...
Titanic - Machine Learning from Disaster
7,904,086
submission_df.to_csv('submission.csv',index=False )<import_modules>
X_train,X_test,y_train,y_test = train_test_split(train_preprocessed,target,test_size=0.2) display(X_train )
Titanic - Machine Learning from Disaster
7,904,086
import os import time import numpy as np import pandas as pd from tqdm import tqdm import math from sklearn.model_selection import train_test_split from sklearn import metrics from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.layers import Dense, Input, CuD...
model = XGBClassifier(n_estimators=90,n_jobs=5,random_state=0) model.fit(X_train,y_train) preds = model.predict(X_test) 'Accuracy Score is %f' % accuracy_score(y_pred=preds,y_true=y_test )
Titanic - Machine Learning from Disaster
7,904,086
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>
mean_absolute_error(preds,y_test )
Titanic - Machine Learning from Disaster
7,904,086
train_df, val_df = train_test_split(train_df, test_size=0.08, random_state=2018) embed_size = 300 max_features = 95000 maxlen = 70 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...
f1_score(preds,y_test )
Titanic - Machine Learning from Disaster
7,904,086
<statistical_test><EOS>
submission_preds = model.predict(test_preprocessed) output = pd.read_csv(".. /input/titanic/gender_submission.csv") output.Survived = submission_preds output.to_csv('submission.csv',index=False) output.head()
Titanic - Machine Learning from Disaster
7,847,459
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<choose_model_class>
%matplotlib inline warnings.filterwarnings('ignore' )
Titanic - Machine Learning from Disaster
7,847,459
filter_sizes = [1,2,3,5] num_filters = 36 inp = Input(shape=(maxlen,)) x = Embedding(max_features, embed_size, weights=[embedding_matrix] )(inp) x = Reshape(( maxlen, embed_size, 1))(x) maxpool_pool = [] for i in range(len(filter_sizes)) : conv = Conv2D(num_filters, kernel_size=(filter_sizes[i], embed_size), kernel_i...
test = pd.read_csv(".. /input/titanic/test.csv") train = pd.read_csv(".. /input/titanic/train.csv" )
Titanic - Machine Learning from Disaster
7,847,459
model.fit(train_X, train_y, batch_size=512, epochs=2, validation_data=(val_X, val_y))<predict_on_test>
print('Train') print(train.isnull().sum()) print('==========================') print('Test') print(test.isnull().sum() )
Titanic - Machine Learning from Disaster
7,847,459
pred_cnn_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_cnn_val_y>thresh ).astype(int))))<predict_on_test>
train = train.fillna({'Age': -0.1}) test = test.fillna({'Age': -0.1}) train['Sex'] = LabelEncoder().fit_transform(train['Sex']) test['Sex'] = LabelEncoder().fit_transform(test['Sex']) train.loc[~train.Cabin.isnull() , 'Cabin'] = 1 train.loc[train.Cabin.isnull() , 'Cabin'] = 0 test.loc[~test.Cabin.isnull() , 'Cabin'...
Titanic - Machine Learning from Disaster
7,847,459
pred_cnn_test_y = model.predict([test_X], batch_size=1024, verbose=1 )<set_options>
train['Title'] = train.Name.str.split(',', n=1, expand=True)[1].str.split('.',n=1, expand=True)[0] train['Title'] = train.Title.str.strip() test['Title'] = test.Name.str.split(',', n=1, expand=True)[1].str.split('.', n=1, expand=True)[0] test['Title'] = test.Title.str.strip() train.head()
Titanic - Machine Learning from Disaster
7,847,459
del word_index, embeddings_index, all_embs, embedding_matrix, model, inp, x time.sleep(10 )<set_options>
train.loc[train.Title == 'Ms', 'Title'] = 'Miss' test.loc[test.Title == 'Ms', 'Title'] = 'Miss' train.loc[~train.Title.isin(['Mr', 'Miss', 'Mrs', 'Master']), 'Title'] = 'Other' test.loc[~test.Title.isin(['Mr', 'Miss', 'Mrs', 'Master']), 'Title'] = 'Other'
Titanic - Machine Learning from Disaster
7,847,459
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...
train['TicketPrefix'] = train.Ticket.str.split(' ' ).apply(lambda x: x[0] if len(x)> 1 else 'No') test['TicketPrefix'] = test.Ticket.str.split(' ' ).apply(lambda x: x[0] if len(x)> 1 else 'No') train.head()
Titanic - Machine Learning from Disaster
7,847,459
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_em...
train.groupby(['TicketPrefix'])['TicketPrefix'].count()
Titanic - Machine Learning from Disaster
7,847,459
model.fit(train_X, train_y, batch_size=512, epochs=3, validation_data=(val_X, val_y))<predict_on_test>
train.loc[train.TicketPrefix.str.startswith('A'), 'TicketPrefix'] = 'A' train.loc[train.TicketPrefix.str.startswith('C'), 'TicketPrefix'] = 'C' train.loc[train.TicketPrefix.str.startswith('F'), 'TicketPrefix'] = 'F' train.loc[train.TicketPrefix.str.startswith('P'), 'TicketPrefix'] = 'P' train.loc[train.TicketPrefix.str...
Titanic - Machine Learning from Disaster
7,847,459
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['Alone'] =(( train.Parch + train.SibSp)== 0 ).astype(int) test['Alone'] =(( test.Parch + test.SibSp)== 0 ).astype(int) train.head()
Titanic - Machine Learning from Disaster
7,847,459
pred_glove_test_y = model.predict([test_X], batch_size=1024, verbose=1 )<set_options>
train = train.drop(['Name', 'SibSp', 'Parch', 'Embarked'], axis=1) test = test.drop(['Name', 'SibSp', 'Parch', 'Embarked'], axis=1) train.head()
Titanic - Machine Learning from Disaster
7,847,459
del word_index, embeddings_index, all_embs, embedding_matrix, model, inp, x time.sleep(10 )<statistical_test>
def encode_ticket(t): e = { 'No': 0, 'A': 1, 'P': 2, 'S': 3, 'C': 4, 'W': 5, 'F': 6 } return e.get(t, -1) train['Ticket'] = train.TicketPrefix.apply(encode_ticket) test['Ticket'] = test.TicketPrefix.apply(encode_ticket) train.head()
Titanic - Machine Learning from Disaster
7,847,459
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_em...
train.Title = LabelEncoder().fit_transform(train.Title) test.Title = LabelEncoder().fit_transform(test.Title) train.head()
Titanic - Machine Learning from Disaster
7,847,459
model.fit(train_X, train_y, batch_size=512, epochs=3, validation_data=(val_X, val_y))<predict_on_test>
train.drop(['TicketPrefix'], axis=1, inplace=True) test.drop(['TicketPrefix'], axis=1, inplace=True) train.head()
Titanic - Machine Learning from Disaster
7,847,459
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>
data = pd.concat([train, test]) data.drop(['Survived'], axis=1, inplace=True) data.head()
Titanic - Machine Learning from Disaster
7,847,459
pred_fasttext_test_y = model.predict([test_X], batch_size=1024, verbose=1 )<set_options>
data.drop(['PassengerId'], axis=1, inplace=True )
Titanic - Machine Learning from Disaster