kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
929,171
train_data_gen = train_image_generator.flow_from_directory(batch_size=batch_size, directory=train_dir, shuffle=True, target_size=(IMG_HEIGHT, IMG_WIDTH), class_mode='categorical') <define_variables>
group_dataset = [train,test] for df in group_dataset: nan_age_index = list(df["Age"][df["Age"].isnull() ].index) for i in nan_age_index : age_med = df["Age"].median() age_pred = df["Age"][(( df['SibSp'] == df.iloc[i]["SibSp"])& (df['Parch'] == df.iloc[i]["Parch"])& (df['Pclass'] == df.iloc[i]["Pclass"])) ].median() if not np.isnan(age_pred): df['Age'].iloc[i] = age_pred else : df['Age'].iloc[i] = age_med f, ax = plt.subplots(figsize =(10,5)) ax = sns.kdeplot(train.Age,shade=True) ax.axvline(train.Age.mean() ,color ='r',linestyle = '--') ax.legend(['Age','Age mean'],fontsize=12) ax.set_xlabel('Age',fontsize=12,color='black') ax.set_title('Age Distribution',color='black',fontsize=14) y_axis = ax.axes.get_yaxis().set_visible(False) sns.despine(left=True )
Titanic - Machine Learning from Disaster
929,171
test_dir='/kaggle/input/car-classificationproject-vision/Test/Test/'<define_variables>
col_drop = ['Cabin','Name','Ticket'] group_dataset = [train,test] for df in group_dataset: df.drop(columns=col_drop,axis=1,inplace=True )
Titanic - Machine Learning from Disaster
929,171
test_data_gen = train_image_generator.flow_from_directory(batch_size=batch_size, directory=test_dir, shuffle=False, target_size=(IMG_HEIGHT, IMG_WIDTH), class_mode=None) <define_variables>
col_dummies = ['Embarked','Sex','family_size','Title','Pclass'] train = pd.get_dummies(train,columns=col_dummies,drop_first=True) test = pd.get_dummies(test,columns=col_dummies,drop_first=True) train.dropna(inplace=True) train.Survived =train.Survived.astype('int' )
Titanic - Machine Learning from Disaster
929,171
sample_training_images, labels = next(train_data_gen) <find_best_score>
train.drop('PassengerId',axis=1,inplace=True) X = train.drop('Survived',axis= 1) y = train['Survived'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test )
Titanic - Machine Learning from Disaster
929,171
train_data_gen.class_indices<categorify>
from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix, classification_report,accuracy_score from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import RandomForestClassifier,AdaBoostClassifier,GradientBoostingClassifier,ExtraTreesClassifier from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.model_selection import GridSearchCV, cross_val_score, StratifiedKFold, learning_curve from sklearn.neural_network import MLPClassifier import xgboost as xgb
Titanic - Machine Learning from Disaster
929,171
def output_labels_to_map_labels(Y, output_label_dict, map_label_dict): result = np.zeros(Y.shape) for i in range(Y.shape[0]): curr_label_ind = Y[i][0] car_name=0 for key, val in output_label_dict.items() : if val == curr_label_ind: car_name = key break print req_label_index = map_label_dict[car_name]['Class Numbers'] result[i][0]=req_label_index return result<categorify>
def model_select(classifier,kfold_n): cv_result = [] cv_means = [] kfold = StratifiedKFold(n_splits= kfold_n) cv_result.append(cross_val_score(classifier, X_train, y = y_train, scoring = "accuracy", cv = kfold, n_jobs=4)) cv_means.append(np.mean(cv_result)) return cv_means model_type = [LogisticRegression() ,SVC() ,KNeighborsClassifier() ,GaussianNB() ,RandomForestClassifier() , AdaBoostClassifier() ,GradientBoostingClassifier() ,DecisionTreeClassifier() ,ExtraTreesClassifier() , MLPClassifier() ,LinearDiscriminantAnalysis() ] model_score = [model_select(i,5)for i in model_type] classifier = ['Logistic Regression','SVC','KNeighbors','Naive Bayes','Random Forest', 'AdaBoost','Gradient Boosting','Decision Tree','Extra Trees','Multiple Layer Perceptron', 'Linear Discriminant'] gbm = xgb.XGBClassifier(n_estimators=1000, learning_rate=0.05,silent=False,n_jobs=4) gbm.fit(X_train, y_train,early_stopping_rounds=5,eval_set=[(X_test, y_test)], verbose=False) y_pred = gbm.predict(X_test) acc_score_1 = accuracy_score(y_pred,y_test) ml_model = pd.DataFrame(model_score,classifier ).reset_index() ml_model.columns=['Model','acc_score'] ml_model.loc[11] = ['xgboost',acc_score_1] ml_model.sort_values('acc_score',ascending = False,inplace=True) ml_model.reset_index(drop=True,inplace = True) ml_model f, ax = plt.subplots(figsize=(10,8)) sns.barplot('acc_score','Model',data=ml_model, ax=ax,palette='RdBu_r',edgecolor=".2") for i in ax.patches: ax.text(i.get_width() +.01, i.get_y() +.55, \ str(round(( i.get_width()), 2)) , fontsize=12, color='black') kwargs= {'length':3, 'width':1, 'colors':'black','labelsize':'large'} ax.tick_params(**kwargs) x_axis = ax.axes.get_xaxis().set_visible(False) ax.set_title('Model & Accuracy Score',fontsize=16) sns.despine(bottom=True) plt.show()
Titanic - Machine Learning from Disaster
929,171
output_labels_to_map_labels(oh_to_class(labels[10:15]),train_data_gen.class_indices, car_map_dict )<define_variables>
def keras_model(kernel_init,act_func,optimizer): classifier = Sequential() classifier.add(Dense(9,input_shape=(X_train.shape[1],),kernel_initializer=kernel_init,activation=act_func)) classifier.add(Dense(9,kernel_initializer=kernel_init,activation=act_func)) classifier.add(Dense(9,kernel_initializer=kernel_init,activation=act_func)) classifier.add(Dense(9,kernel_initializer=kernel_init,activation=act_func)) classifier.add(Dense(9,kernel_initializer=kernel_init,activation=act_func)) classifier.add(Dense(1,kernel_initializer=kernel_init,activation='sigmoid')) classifier.compile(optimizer=optimizer,loss = 'binary_crossentropy',metrics=['accuracy']) return classifier
Titanic - Machine Learning from Disaster
929,171
feature_extractor_url = "https://tfhub.dev/tensorflow/resnet_50/feature_vector/1" <choose_model_class>
clf = keras_model('lecun_normal','selu','adam') clf.fit(X_train,y_train,batch_size=10,epochs=150,validation_data=(X_test,y_test))
Titanic - Machine Learning from Disaster
929,171
feature_extractor_layer = hub.KerasLayer(feature_extractor_url, input_shape=(224,224,3)) <choose_model_class>
y_pred_2 = clf.predict_classes(X_test,batch_size=32) y_pred =(y_pred_2 > 0.5) def y_pred_val(input): y_pred_1 = [] for i in list(input): if i == True: y_pred_1.append(1) else: y_pred_1.append(0) return y_pred_1 accuracy_score(y_test,y_pred_2 )
Titanic - Machine Learning from Disaster
929,171
model.compile( optimizer=tf.keras.optimizers.Adam() , loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True), metrics=['acc']) <train_model>
test_1 = test.drop('PassengerId',axis=1) test_1 = sc.transform(test_1) y_test_pred = clf.predict_classes(test_1,batch_size=32) y_test_pred =(y_test_pred > 0.5) y_test_pred_2 = y_pred_val(y_test_pred )
Titanic - Machine Learning from Disaster
929,171
class CollectBatchStats(tf.keras.callbacks.Callback): def __init__(self): self.batch_losses = [] self.batch_acc = [] def on_train_batch_end(self, batch, logs=None): self.batch_losses.append(logs['loss']) self.batch_acc.append(logs['acc']) self.model.reset_metrics() <train_model>
submit = pd.DataFrame({"PassengerId": test["PassengerId"],"Survived": y_test_pred_2}) submit.to_csv(".. /working/submit.csv", index=False )
Titanic - Machine Learning from Disaster
6,498,036
steps_per_epoch = 4050//64 batch_stats_callback = CollectBatchStats() history = model.fit_generator(train_data_gen, epochs=360, steps_per_epoch=steps_per_epoch, callbacks = [batch_stats_callback]) <compute_test_metric>
train = pd.read_csv(".. /input/titanic/train.csv") test = pd.read_csv(".. /input/titanic/test.csv") train['Type'] = 'train' test['Type'] = 'test' data = train.append(test) data['Title'] = data['Name'] for name_string in data['Name']: data['Title'] = data['Name'].str.extract('([A-Za-z]+)\.', expand=True) mapping = {'Mlle': 'Miss', 'Ms': 'Miss', 'Mme': 'Mrs', 'Major': 'Other', 'Col': 'Other', 'Dr' : 'Other', 'Rev' : 'Other', 'Capt': 'Other', 'Jonkheer': 'Royal', 'Sir': 'Royal', 'Lady': 'Royal', 'Don': 'Royal', 'Countess': 'Royal', 'Dona': 'Royal'} data.replace({'Title': mapping}, inplace=True) titles = ['Miss', 'Mr', 'Mrs', 'Royal', 'Other', 'Master'] for title in titles: age_to_impute = data.groupby('Title')['Age'].median() [titles.index(title)] data.loc[(data['Age'].isnull())&(data['Title'] == title), 'Age'] = age_to_impute data['Family_Size'] = data['Parch'] + data['SibSp'] + 1 data.loc[:,'FsizeD'] = 'Alone' data.loc[(data['Family_Size'] > 1),'FsizeD'] = 'Small' data.loc[(data['Family_Size'] > 4),'FsizeD'] = 'Big' fa = data[data["Pclass"] == 3] data['Fare'].fillna(fa['Fare'].median() , inplace = True) data.loc[:,'Child'] = 1 data.loc[(data['Age'] >= 18),'Child'] =0 data['Last_Name'] = data['Name'].apply(lambda x: str.split(x, ",")[0]) DEFAULT_SURVIVAL_VALUE = 0.5 data['Family_Survival'] = DEFAULT_SURVIVAL_VALUE for grp, grp_df in data[['Survived','Name', 'Last_Name', 'Fare', 'Ticket', 'PassengerId', 'SibSp', 'Parch', 'Age', 'Cabin']].groupby(['Last_Name', 'Fare']): if(len(grp_df)!= 1): for ind, row in grp_df.iterrows() : smax = grp_df.drop(ind)['Survived'].max() smin = grp_df.drop(ind)['Survived'].min() passID = row['PassengerId'] if(smax == 1.0): data.loc[data['PassengerId'] == passID, 'Family_Survival'] = 1 elif(smin == 0.0): data.loc[data['PassengerId'] == passID, 'Family_Survival'] = 0 for _, grp_df in data.groupby('Ticket'): if(len(grp_df)!= 1): for ind, row in grp_df.iterrows() : if(row['Family_Survival'] == 0)|(row['Family_Survival']== 0.5): smax = grp_df.drop(ind)['Survived'].max() smin = grp_df.drop(ind)['Survived'].min() passID = row['PassengerId'] if(smax == 1.0): data.loc[data['PassengerId'] == passID, 'Family_Survival'] = 1 elif(smin == 0.0): data.loc[data['PassengerId'] == passID, 'Family_Survival'] = 0 data = data.drop(columns = ['Age','Cabin','Embarked','Name','Last_Name', 'Parch', 'SibSp','Ticket', 'Family_Size']) target_col = ["Survived"] id_dataset = ["Type"] cat_cols = data.nunique() [data.nunique() < 12].keys().tolist() cat_cols = [x for x in cat_cols ] num_cols = [x for x in data.columns if x not in cat_cols + target_col + id_dataset] bin_cols = data.nunique() [data.nunique() == 2].keys().tolist() multi_cols = [i for i in cat_cols if i not in bin_cols] le = LabelEncoder() for i in bin_cols : data[i] = le.fit_transform(data[i]) data = pd.get_dummies(data = data,columns = multi_cols) std = StandardScaler() scaled = std.fit_transform(data[num_cols]) scaled = pd.DataFrame(scaled,columns = num_cols) df_data_og = data.copy() data = data.drop(columns = num_cols,axis = 1) data = data.merge(scaled,left_index = True,right_index = True,how = "left") data = data.drop(columns = ['PassengerId'],axis = 1) cols = data.columns.tolist() cols.insert(0, cols.pop(cols.index('Survived'))) data = data.reindex(columns= cols) train = data[data['Type'] == 1].drop(columns = ['Type']) test = data[data['Type'] == 0].drop(columns = ['Type']) X_train = train.iloc[:, 1:20].as_matrix() y_train = train.iloc[:,0].as_matrix()
Titanic - Machine Learning from Disaster
6,498,036
model.evaluate(train_data_gen )<predict_on_test>
def make_model() : model = models.Sequential() model.add(Dense(13, input_dim = 18, activation = 'relu')) model.add(Dropout(0.2)) model.add(BatchNormalization()) model.add(Dense(8, activation = 'relu')) model.add(BatchNormalization()) model.add(Dense(1, activation = 'sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam',metrics=['accuracy']) return model
Titanic - Machine Learning from Disaster
6,498,036
train_predicted_oh = model.predict(train_data_gen )<predict_on_test>
def mixup_data(x, y, alpha=1.0): if alpha > 0: lam = np.random.beta(alpha, alpha) else: lam = 1 sample_size = x.shape[0] index_array = np.arange(sample_size) np.random.shuffle(index_array) mixed_x = lam * x +(1 - lam)* x[index_array] mixed_y =(lam * y)+(( 1 - lam)* y[index_array]) return mixed_x, mixed_y def make_batches(size, batch_size): nb_batch = int(np.ceil(size/float(batch_size))) return [(i*batch_size, min(size,(i+1)*batch_size)) for i in range(0, nb_batch)] def batch_generator(X,y,batch_size=128,shuffle=True,mixup=False): sample_size = X.shape[0] index_array = np.arange(sample_size) while 1: if shuffle: np.random.shuffle(index_array) batches = make_batches(sample_size, batch_size) for batch_index,(batch_start, batch_end)in enumerate(batches): batch_ids = index_array[batch_start:batch_end] X_batch = X[batch_ids] y_batch = y[batch_ids] if mixup: X_batch,y_batch = mixup_data(X_batch,y_batch,alpha=1.0) yield X_batch,y_batch
Titanic - Machine Learning from Disaster
6,498,036
test_predicted_oh = model.predict_generator(test_data_gen )<categorify>
def step_decay(epoch): initial_lrate = 0.01 drop = 0.5 epochs_drop = 10.0 lrate = initial_lrate * np.power(drop, np.floor(( 1+epoch)/epochs_drop)) return lrate lrate = LearningRateScheduler(step_decay )
Titanic - Machine Learning from Disaster
6,498,036
test_predicted=oh_to_class(test_predicted_oh )<define_variables>
class LossHistory(keras.callbacks.Callback): def on_train_begin(self, logs={}): self.losses = [] self.lr = [] def on_epoch_end(self, batch, logs={}): self.losses.append(logs.get('loss')) self.lr.append(step_decay(len(self.losses)) )
Titanic - Machine Learning from Disaster
6,498,036
sample_testing_images = next(test_data_gen) <categorify>
def auc(y_true, y_pred): try: return tf.py_func(metrics.roc_auc_score,(y_true, y_pred), tf.double) except: return 0.5
Titanic - Machine Learning from Disaster
6,498,036
result_test = output_labels_to_map_labels(test_predicted,train_data_gen.class_indices, car_map_dict )<define_variables>
batch_size = 32 loss_history = LossHistory() lrate = LearningRateScheduler(step_decay) annealer = LearningRateScheduler(lambda x: 1e-2 * 0.95 ** x) callbacks_list = [EarlyStopping(monitor='val_loss', patience=10,mode='min'),loss_history, annealer] sss = StratifiedShuffleSplit(n_splits=5) hold_models = [] hold_models_no_mixup = [] for train_index, test_index in sss.split(X_train, y_train): X_train_hold, X_val_hold = X_train[train_index], X_train[test_index] y_train_hold, y_val_hold = y_train[train_index], y_train[test_index] tr_gen = batch_generator(X_train_hold,y_train_hold,batch_size=batch_size,shuffle=True,mixup=True) model = make_model() model.fit_generator( tr_gen, steps_per_epoch=np.ceil(float(len(X_train_hold)) / float(batch_size)) , nb_epoch=1000, verbose=1, callbacks=callbacks_list, validation_data=(X_val_hold,y_val_hold), max_q_size=10, ) hold_models.append(model) tr_gen_no_mixup = batch_generator(X_train_hold,y_train_hold,batch_size=batch_size,shuffle=True,mixup=False) model_no_mixup = make_model() model_no_mixup.fit_generator( tr_gen, steps_per_epoch=np.ceil(float(len(X_train_hold)) / float(batch_size)) , nb_epoch=1000, verbose=1, callbacks=callbacks_list, validation_data=(X_val_hold,y_val_hold), max_q_size=10, ) hold_models_no_mixup.append(model_no_mixup) del X_train_hold, X_val_hold, y_train_hold, y_val_hold gc.collect()
Titanic - Machine Learning from Disaster
6,498,036
file_names = [] for name in test_data_gen.filenames: file_names+=[name[6:]]<data_type_conversions>
%matplotlib inline def append_last_value(target_list, length): if len(target_list)>= length: return target_list for i in range(length - len(target_list)) : target_list.append(target_list[-1]) return target_list model_index = 1 trained_epochs = max(len(hold_models[model_index].history.history['loss']), len(hold_models_no_mixup[model_index].history.history['loss'])) loss_list = append_last_value(hold_models[model_index].history.history['loss'], trained_epochs) val_acc_list = append_last_value(hold_models[model_index].history.history['val_accuracy'], trained_epochs) loss_list_no_mixup = append_last_value(hold_models_no_mixup[model_index].history.history['loss'], trained_epochs) val_acc_list_no_mixup = append_last_value(hold_models_no_mixup[model_index].history.history['val_accuracy'], trained_epochs) plt.plot(range(1, trained_epochs+1), loss_list, label="loss") plt.plot(range(1, trained_epochs+1), val_acc_list, label="val_acc") plt.plot(range(1, trained_epochs+1), loss_list_no_mixup, label="loss_no_mixup") plt.plot(range(1, trained_epochs+1), val_acc_list_no_mixup, label="val_accuracy_no_mixup") plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show()
Titanic - Machine Learning from Disaster
6,498,036
result_image_prediction = np.concatenate(( file_names, result_test.astype(np.int32)) , axis = 1 )<create_dataframe>
def get_pred(model_list, test_df): preds = [model.predict(test_df.drop('Survived', axis=1)) for model in model_list] model_count = len(preds) ensemble_pred = 0 for i in range(model_count): ensemble_pred = ensemble_pred + preds[i] ensemble_pred = ensemble_pred / model_count pred_ = ensemble_pred[:,0] return pred_ pred = get_pred(hold_models, test) pred_no_mixup = get_pred(hold_models_no_mixup, test )
Titanic - Machine Learning from Disaster
6,498,036
result_df = pd.DataFrame(result_image_prediction, columns=['image', 'predictions'] )<rename_columns>
train_survived = train['Survived'].sum() train_len = train.shape[0] print('train dataset : ' + str(train_survived)+ '/' + str(train_len)+ ' : ' + str(train_survived / train_len)) thresholds = [0.4, 0.45, 0.5, 0.55, 0.6, 0.7, 0.75, 0.8] for threshold in thresholds: pred_survived = pred[pred > threshold].shape[0] pred_len = pred.shape[0] print('threshold : ' + str(threshold)+ ' -> ' + str(pred_survived)+ '/' + str(pred_len)+ ' : ' + str(pred_survived / pred_len))
Titanic - Machine Learning from Disaster
6,498,036
result_df.set_index('image' )<save_to_csv>
submit_threshold = 0.4 submit_df = pd.read_csv('.. /input/titanic/test.csv') submit_df['Survived'] = np.where(pred > submit_threshold, 1, 0) submit_df = submit_df[['PassengerId', 'Survived']] submit_df.to_csv('submission.csv', index=False )
Titanic - Machine Learning from Disaster
10,862,355
result_df.to_csv('submissionCommit8AugmentedDataE360.csv', index=False )<load_from_csv>
train_data = pd.read_csv("/kaggle/input/titanic/train.csv") train_data.head()
Titanic - Machine Learning from Disaster
10,862,355
train = pd.read_csv('.. /input/train.csv' )<load_from_csv>
test_data = pd.read_csv("/kaggle/input/titanic/test.csv") test_data.head()
Titanic - Machine Learning from Disaster
10,862,355
test = pd.read_csv('.. /input/test.csv' )<feature_engineering>
train_data.isnull().sum()
Titanic - Machine Learning from Disaster
10,862,355
train['nota_mat'] = np.log(train['nota_mat'] )<concatenate>
test_data.isnull().sum()
Titanic - Machine Learning from Disaster
10,862,355
df = train.append(test, sort=False )<count_values>
train_data[['Pclass', 'Survived']].groupby(['Pclass'], as_index=False ).mean().sort_values(by='Survived', ascending=False )
Titanic - Machine Learning from Disaster
10,862,355
df.count()<count_values>
train_data[train_data.Embarked.isnull() ]
Titanic - Machine Learning from Disaster
10,862,355
for col in df.columns: if(df[col].count() < 3124): print(col) print(3124 - df[col].count()) <count_unique_values>
train_data = train_data.fillna({"Embarked": "S"} )
Titanic - Machine Learning from Disaster
10,862,355
df.nunique()<feature_engineering>
train_data = train_data.drop(['Ticket', 'Cabin'], axis=1) test_data = test_data.drop(['Ticket', 'Cabin'], axis=1 )
Titanic - Machine Learning from Disaster
10,862,355
df['participacao_transf_receita'] = df['participacao_transf_receita'].fillna(np.mean(df['participacao_transf_receita'])) df['servidores'] = df['servidores'].fillna(np.mean(df['servidores'])) df['perc_pop_econ_ativa'] = df['perc_pop_econ_ativa'].fillna(np.mean(df['perc_pop_econ_ativa'])) df['gasto_pc_saude'] = df['gasto_pc_saude'].fillna(np.mean(df['gasto_pc_saude'])) df['hab_p_medico'] = df['hab_p_medico'].fillna(np.mean(df['hab_p_medico'])) df['gasto_pc_educacao'] = df['gasto_pc_educacao'].fillna(np.mean(df['gasto_pc_educacao'])) df['exp_anos_estudo'] = df['exp_anos_estudo'].fillna(np.mean(df['exp_anos_estudo'])) df['exp_vida'] = df['exp_vida'].fillna(np.mean(df['exp_vida'])) df['idhm'] = df['idhm'].fillna(np.mean(df['idhm'])) df['indice_governanca'] = df['indice_governanca'].fillna(np.mean(df['indice_governanca'])) <data_type_conversions>
for dataset in combine: dataset['Title'] = dataset['Title'].replace(['Lady', 'Capt', 'Col', 'Don', 'Dr', 'Major', 'Rev', 'Jonkheer', 'Dona'], 'Rare') dataset['Title'] = dataset['Title'].replace(['Countess', 'Lady', 'Sir'], 'Royal') dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss') dataset['Title'] = dataset['Title'].replace('Ms', 'Miss') dataset['Title'] = dataset['Title'].replace('Mme', 'Mrs') train_data[['Title', 'Survived']].groupby(['Title'], as_index=False ).mean()
Titanic - Machine Learning from Disaster
10,862,355
def convertaStringParaFloat(valor): if(type(valor)== str): valor = valor.replace(',','') valor = float(valor) return valor df['densidade_dem'] = df['densidade_dem'].map(convertaStringParaFloat) df['densidade_dem'] = df['densidade_dem'].fillna(np.mean(df['densidade_dem'])) df.info() <categorify>
title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Rare": 5} for dataset in combine: dataset['Title'] = dataset['Title'].map(title_mapping) dataset['Title'] = dataset['Title'].fillna(0) train_data.head()
Titanic - Machine Learning from Disaster
10,862,355
df['area'] = df['area'].map(convertaStringParaFloat )<data_type_conversions>
mr_age = train_data[train_data["Title"] == 1]["AgeGroup"].mode() miss_age = train_data[train_data["Title"] == 2]["AgeGroup"].mode() mrs_age = train_data[train_data["Title"] == 3]["AgeGroup"].mode() master_age = train_data[train_data["Title"] == 4]["AgeGroup"].mode() royal_age = train_data[train_data["Title"] == 5]["AgeGroup"].mode() rare_age = train_data[train_data["Title"] == 6]["AgeGroup"].mode() age_title_mapping = {1: "Young Adult", 2: "Student", 3: "Adult", 4: "Baby", 5: "Adult", 6: "Adult"} for x in range(len(train_data["AgeGroup"])) : if train_data["AgeGroup"][x] == "Unknown": train_data["AgeGroup"][x] = age_title_mapping[train_data["Title"][x]] for x in range(len(test_data["AgeGroup"])) : if test_data["AgeGroup"][x] == "Unknown": test_data["AgeGroup"][x] = age_title_mapping[test_data["Title"][x]]
Titanic - Machine Learning from Disaster
10,862,355
df['estado'] = df['estado'].astype('category' )<feature_engineering>
age_mapping = {'Baby': 1, 'Child': 2, 'Teenager': 3, 'Student': 4, 'Young Adult': 5, 'Adult': 6, 'Senior': 7} train_data['AgeGroup'] = train_data['AgeGroup'].map(age_mapping) test_data['AgeGroup'] = test_data['AgeGroup'].map(age_mapping) train_data.head() train_data = train_data.drop(['Age'], axis = 1) test_data = test_data.drop(['Age'], axis = 1 )
Titanic - Machine Learning from Disaster
10,862,355
df['estado'] = df['estado'].cat.codes<data_type_conversions>
train_data = train_data.drop(['Name'], axis = 1) test_data = test_data.drop(['Name'], axis = 1 )
Titanic - Machine Learning from Disaster
10,862,355
df['municipio'] = df['municipio'].astype('category' )<feature_engineering>
sex_mapping = {"male": 0, "female": 1} train_data['Sex'] = train_data['Sex'].map(sex_mapping) test_data['Sex'] = test_data['Sex'].map(sex_mapping) train_data.head()
Titanic - Machine Learning from Disaster
10,862,355
df['municipio'] = df['municipio'].cat.codes<categorify>
embarked_mapping = {"S": 1, "C": 2, "Q": 3} train_data['Embarked'] = train_data['Embarked'].map(embarked_mapping) test_data['Embarked'] = test_data['Embarked'].map(embarked_mapping) train_data.head()
Titanic - Machine Learning from Disaster
10,862,355
df = pd.concat([df, pd.get_dummies(df['regiao'], prefix='regiao' ).iloc[:, :-1]], axis =1) del df['regiao'] df.info()<categorify>
train_data = train_data.drop(['Fare'], axis = 1) test_data= test_data.drop(['Fare'], axis = 1 )
Titanic - Machine Learning from Disaster
10,862,355
df = pd.concat([df, pd.get_dummies(df['porte'], prefix='porte' ).iloc[:, :-1]], axis =1) del df['porte'] <data_type_conversions>
X = train_data.drop(['Survived', 'PassengerId'], axis=1) Y = train_data["Survived"] x_train, x_val, y_train, y_val = train_test_split(X,Y, test_size = 0.22, random_state = 0 )
Titanic - Machine Learning from Disaster
10,862,355
f = lambda x: x.replace('ID_ID_','') df['codigo_mun'] = df['codigo_mun'].map(f) df['codigo_mun'] = df['codigo_mun'].astype(int) <categorify>
G = GaussianNB() G.fit(x_train, y_train) y_pred = G.predict(x_val) Accuracy_for_gaussian = round(accuracy_score(y_pred, y_val)* 100, 2) print("Accuracy_for_gaussian: ",Accuracy_for_gaussian) L = LogisticRegression() L.fit(x_train, y_train) y_pred = L.predict(x_val) Accuracy_for_logistic_regression = round(accuracy_score(y_pred, y_val)* 100, 2) print("Accuracy_for_logistic_regression: ",Accuracy_for_logistic_regression) R = RandomForestClassifier() R.fit(x_train, y_train) y_pred = R.predict(x_val) Accuracy_for_Random_forest = round(accuracy_score(y_pred, y_val)* 100, 2) print("Accuracy_for_Random_forest: ",Accuracy_for_Random_forest) SVC = LinearSVC() SVC.fit(x_train, y_train) y_pred = SVC.predict(x_val) Accuracy_for_LinearSVC = round(accuracy_score(y_pred, y_val)* 100, 2) print("Accuracy_for_LinearSVC: ",Accuracy_for_LinearSVC) clf = svm.SVC() clf.fit(x_train, y_train) y_pred = clf.predict(x_val) Accuracy_for_SVM = round(accuracy_score(y_pred, y_val)* 100, 2) print("Accuracy_for_SVM: ",Accuracy_for_SVM) MNB = MultinomialNB() MNB.fit(x_train, y_train) y_pred = MNB.predict(x_val) Accuracy_for_MultinomialNB = round(accuracy_score(y_pred, y_val)* 100, 2) print("Accuracy_for_MultinomialNB: ",Accuracy_for_MultinomialNB) DTC = DecisionTreeClassifier() DTC.fit(x_train, y_train) y_pred = DTC.predict(x_val) Accuracy_for_DecisionTreeClassifier = round(accuracy_score(y_pred, y_val)* 100, 2) print("Accuracy_for_DecisionTreeClassifier: ",Accuracy_for_DecisionTreeClassifier) GBC = GradientBoostingClassifier() GBC.fit(x_train, y_train) y_pred = GBC.predict(x_val) Accuracy_for_GradientBoostingClassifier = round(accuracy_score(y_pred, y_val)* 100, 2) print("Accuracy_for_GradientBoostingClassifier: ",Accuracy_for_GradientBoostingClassifier) SGD = SGDClassifier(loss="log", penalty="l2", max_iter=5) SGD.fit(x_train, y_train) y_pred = SGD.predict(x_val) Accuracy_for_SGDClassifier = round(accuracy_score(y_pred, y_val)* 100, 2) print("Accuracy_for_SGDClassifier: ",Accuracy_for_SGDClassifier) KN = KNeighborsClassifier() KN.fit(x_train, y_train) y_pred = KN.predict(x_val) Accuracy_for_KNeighborsClassifier = round(accuracy_score(y_pred, y_val)* 100, 2) print("Accuracy_for_KNeighborsClassifier: ",Accuracy_for_KNeighborsClassifier )
Titanic - Machine Learning from Disaster
10,862,355
<categorify><EOS>
ID = test_data['PassengerId'] Predictions = GBC.predict(test_data.drop('PassengerId', axis=1)) output = pd.DataFrame({ 'PassengerId' : ID, 'Survived': Predictions }) output.to_csv('submission.csv', index=False )
Titanic - Machine Learning from Disaster
6,959,732
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<compute_test_metric>
%matplotlib inline
Titanic - Machine Learning from Disaster
6,959,732
def corrijaValoresAcimaDeCem(valor): if(valor > 100): print(valor) return 0 else: return valor<categorify>
testandtrain_df = pd.read_csv('/kaggle/input/titanic/train.csv') validation_df = pd.read_csv('/kaggle/input/titanic/test.csv')
Titanic - Machine Learning from Disaster
6,959,732
df['comissionados_por_servidor'] = df['comissionados_por_servidor'].map(corrijaValoresAcimaDeCem )<feature_engineering>
print("Training dataset(rows, columns):", testandtrain_df.shape) print("Validation dataset(rows, columns):", validation_df.shape )
Titanic - Machine Learning from Disaster
6,959,732
df['comissionados_por_servidor'] = df['comissionados_por_servidor'].fillna(np.mean(df['comissionados_por_servidor']))<categorify>
validation_df[validation_df.Fare.isna() ]
Titanic - Machine Learning from Disaster
6,959,732
df['ranking_igm'] = df['ranking_igm'].map(retiraSinalGrau )<data_type_conversions>
temp1_df = pd.concat([testandtrain_df.copy() , validation_df.copy() ], sort = False) temp1_df = temp1_df.filter(["Pclass", "Fare"]) temp1_df = temp1_df.dropna() print("Combined dataframe of all passengers except those with missing 'Fare' values ", "Shape(rows, columns):", temp1_df.shape )
Titanic - Machine Learning from Disaster
6,959,732
df['ranking_igm'] = df['ranking_igm'].astype('category' )<feature_engineering>
avg_fares = temp1_df.groupby('Pclass' ).mean() avg_fares
Titanic - Machine Learning from Disaster
6,959,732
df['ranking_igm'] = df['ranking_igm'].cat.codes<compute_test_metric>
validation_df.loc[152, "Fare"] = avg_fares.loc[3, 'Fare']
Titanic - Machine Learning from Disaster
6,959,732
def retirarOutliers(valor): if(valor > 2174): return 2174 else: return valor<categorify>
validation_df[validation_df.index == 152]
Titanic - Machine Learning from Disaster
6,959,732
df['hab_p_medico'] = df['hab_p_medico'].map(retirarOutliers )<statistical_test>
testandtrain_df[testandtrain_df.Embarked.isna() ]
Titanic - Machine Learning from Disaster
6,959,732
def retirarOutliers(valor): if(valor < 0.3): print(valor) return 0.3 else: return valor<categorify>
testandtrain_df.Embarked.value_counts() + validation_df.Embarked.value_counts()
Titanic - Machine Learning from Disaster
6,959,732
df['perc_pop_econ_ativa'] = df['perc_pop_econ_ativa'].map(retirarOutliers )<concatenate>
testandtrain_df.loc[61, "Embarked"] = "S" testandtrain_df.loc[829, "Embarked"] = "S"
Titanic - Machine Learning from Disaster
6,959,732
def limparAnosEstudos(valor): if(valor < 1.9): return 2 elif(valor > 11): return 10 else: return valor <categorify>
for df in [testandtrain_df, validation_df]: df.drop(columns = ['Cabin', 'Ticket'], inplace = True )
Titanic - Machine Learning from Disaster
6,959,732
df['anos_estudo_empreendedor'] = df['anos_estudo_empreendedor'].map(limparAnosEstudos )<concatenate>
testandtrain_df.drop(columns = ['PassengerId'], inplace = True )
Titanic - Machine Learning from Disaster
6,959,732
def limparJornada(valor): if(valor > 50): return 50 elif(valor < 30): return 30 else: return valor<categorify>
for df in [testandtrain_df, validation_df]: for row in df.index: df.loc[row, 'Title'] = df.loc[row, 'Name'].split(", ")[1].split(".")[0]
Titanic - Machine Learning from Disaster
6,959,732
df['jornada_trabalho'] = df['jornada_trabalho'].map(limparJornada )<concatenate>
temp2_df = pd.concat([testandtrain_df.copy() , validation_df.copy() ], sort = False) print("Number of unique titles(in both dataframes):", temp2_df.Title.nunique()) print("Number of null titles(in both dataframes):", temp2_df.Title.isna().sum()) temp2_df.groupby("Title" ).count().Name
Titanic - Machine Learning from Disaster
6,959,732
def limparAnosEstudo(valor): if(valor > 11): return 11 elif(valor < 7.5): return 7.5 else: return valor<categorify>
prof_titles = ["Capt", "Col", "Dr", "Major", "Rev"] other_titles = ["Don", "Dona", "Jonkheer", "Lady", "Mlle", "Mme", "Ms", "Sir", "the Countess"] for df in [testandtrain_df, validation_df]: for row in df.index: if df.loc[row, 'Title'] in prof_titles: df.loc[row, 'Title'] = "Professional" elif df.loc[row, 'Title'] in other_titles: df.loc[row, 'Title'] = "Other"
Titanic - Machine Learning from Disaster
6,959,732
df['exp_anos_estudo'] = df['exp_anos_estudo'].map(limparAnosEstudo )<concatenate>
for df in [testandtrain_df, validation_df]: df.drop(columns = ['Name'], inplace = True )
Titanic - Machine Learning from Disaster
6,959,732
def limparParticipacao(valor): if(valor < 50): return 55 else: return valor<categorify>
temp3_df = pd.concat([testandtrain_df.copy() , validation_df.copy() ], sort = False) title_ages = temp3_df.groupby("Title" ).Age.mean() title_ages
Titanic - Machine Learning from Disaster
6,959,732
df['participacao_transf_receita'] = df['participacao_transf_receita'].map(limparParticipacao )<compute_test_metric>
for df in [testandtrain_df, validation_df]: for row in df.index: if pd.isna(df.loc[row, 'Age']): df.loc[row, 'Age'] = title_ages[df.loc[row, 'Title']]
Titanic - Machine Learning from Disaster
6,959,732
def limparNotaMat(valor): if(valor > 6.32): return 6.32 else: return valor<categorify>
print("Total null values in both dataframes:", testandtrain_df.isna().sum().sum() + validation_df.isna().sum().sum() )
Titanic - Machine Learning from Disaster
6,959,732
df['nota_mat'] = df['nota_mat'].map(limparNotaMat )<set_options>
for df in [testandtrain_df, validation_df]: df["Family_Onboard"] = df["SibSp"] + df["Parch"] df.drop(columns = ['SibSp', 'Parch'], inplace = True )
Titanic - Machine Learning from Disaster
6,959,732
np.percentile(df['populacao'], 75) np.percentile(df['populacao'], 25 )<define_variables>
testandtrain_df[testandtrain_df["Fare"] == 0]
Titanic - Machine Learning from Disaster
6,959,732
irq = np.percentile(df['populacao'], 75)- np.percentile(df['populacao'], 25) <feature_engineering>
validation_df[validation_df["Fare"] == 0]
Titanic - Machine Learning from Disaster
6,959,732
df['populacao'] = irq<set_options>
print("Training dataset(rows, columns):", testandtrain_df.shape) print("Validation dataset(rows, columns):", validation_df.shape)
Titanic - Machine Learning from Disaster
6,959,732
np.percentile(df['gasto_pc_saude'], 75) <set_options>
temp4_df = pd.concat([testandtrain_df.copy() , validation_df.copy() ], sort = False) temp4_df = temp4_df[temp4_df.Fare != 0] temp4_df.shape
Titanic - Machine Learning from Disaster
6,959,732
np.percentile(df['gasto_pc_saude'], 25 )<categorify>
temp4_df = pd.concat([testandtrain_df.copy() , validation_df.copy() ], sort=False) print("Number of passengers in each bin/grouping(out of 1,309 - both dataframes):- ") temp4_df.groupby("FareBinned" ).Fare.count()
Titanic - Machine Learning from Disaster
6,959,732
df['gasto_pc_saude'] = df['gasto_pc_saude'].map(limparGastoSaude )<compute_test_metric>
testandtrain_df.groupby("FareBinned" ).Survived.agg([("Count", "count"),("Survival(mean)", "mean")], axis = "rows")
Titanic - Machine Learning from Disaster
6,959,732
def limpaTaxaEmpreendedorismo(valor): if(valor > 0.4): return 0.4 elif(valor < 0.12): return 0.12 else: return valor<categorify>
for df in [testandtrain_df, validation_df]: df.drop(columns = ["Fare"], inplace = True )
Titanic - Machine Learning from Disaster
6,959,732
df['taxa_empreendedorismo'] = df['taxa_empreendedorismo'].map(limpaTaxaEmpreendedorismo )<concatenate>
testandtrain_df.groupby("Family_Onboard" ).Survived.agg([("Count", "count"),("Survival(mean)", "mean")], axis = "rows" )
Titanic - Machine Learning from Disaster
6,959,732
def limpaGastoEducacao(valor): if(valor > 1100): return 1100 elif(valor < 250): return 250 else: return valor<categorify>
for df in [testandtrain_df, validation_df]: df.drop(columns = ["Age", "Family_Onboard"], inplace = True )
Titanic - Machine Learning from Disaster
6,959,732
df['gasto_pc_educacao'] = df['gasto_pc_educacao'].map(limpaGastoEducacao )<feature_engineering>
for df in [testandtrain_df, validation_df]: df['Sex'] = df['Sex'].map({"female": 1, "male": 0} )
Titanic - Machine Learning from Disaster
6,959,732
df['area'] = 1173.985<split>
dummy_cols = ["Pclass", "Embarked", "Title", "FareBinned", "AgeBinned", "FamilyBinned"] dummy_prefixes = ["Pclass", "Port", "Title", "Fare", "Age", "Family"] testandtrain_df = pd.get_dummies(testandtrain_df, columns = dummy_cols, prefix = dummy_prefixes) validation_df = pd.get_dummies(validation_df, columns = dummy_cols, prefix = dummy_prefixes )
Titanic - Machine Learning from Disaster
6,959,732
train_raw = df[~df['nota_mat'].isnull() ]<compute_test_metric>
testandtrain_df.corr() ["Survived"][:].sort_values(ascending = False )
Titanic - Machine Learning from Disaster
6,959,732
for coluna in train_raw.columns: if(coluna == 'ranking_igm'): continue corr = np.corrcoef(train_raw['nota_mat'],train_raw[coluna])[0,1] if(corr < 0.4 and corr > -0.4): print(str(coluna)+ ': ' + str(corr)) <compute_test_metric>
print("Survival % split for train.csv data") testandtrain_df.Survived.value_counts(normalize = True )
Titanic - Machine Learning from Disaster
6,959,732
for coluna in train_raw.columns: if(coluna == 'ranking_igm'): continue corr = np.corrcoef(train_raw['nota_mat'],train_raw[coluna])[0,1] if(corr < -0.4): print(str(coluna)+ ': ' + str(corr))<split>
X = testandtrain_df.iloc[:, 1:] y = testandtrain_df.iloc[:, 0] X_train, X_test, y_train, y_test = train_test_split(X, y, stratify = y, test_size = 0.3, random_state = 0)
Titanic - Machine Learning from Disaster
6,959,732
test = df[df['nota_mat'].isnull() ]<drop_column>
X_train
Titanic - Machine Learning from Disaster
6,959,732
del test['nota_mat']<import_modules>
X_test
Titanic - Machine Learning from Disaster
6,959,732
from sklearn.model_selection import train_test_split<import_modules>
dt_model = tree.DecisionTreeClassifier(random_state = 0) dt_model.fit(X_train, y_train )
Titanic - Machine Learning from Disaster
6,959,732
from sklearn.model_selection import train_test_split<split>
print("Train Accuracy:", dt_model.score(X_train, y_train)) print("Test Accuracy:", dt_model.score(X_test, y_test))
Titanic - Machine Learning from Disaster
6,959,732
train, valid = train_test_split(train_raw, random_state=42 )<define_variables>
train_accuracy = [] test_accuracy = [] trial_range = [0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5] for test_split in trial_range: temp_X_train, temp_X_test, temp_y_train, temp_y_test = train_test_split(X, y, stratify = y, test_size = test_split, random_state=1) temp_dt = tree.DecisionTreeClassifier(random_state = 0) temp_dt.fit(temp_X_train, temp_y_train) train_accuracy.append(temp_dt.score(temp_X_train, temp_y_train)) test_accuracy.append(temp_dt.score(temp_X_test, temp_y_test)) testtrainsplit_df = pd.DataFrame({"test_split": trial_range, "train_acc": train_accuracy, "test_acc": test_accuracy}) plt.figure(figsize =(20,5)) plt.plot(testtrainsplit_df["test_split"], testtrainsplit_df["train_acc"], marker="o") plt.plot(testtrainsplit_df["test_split"], testtrainsplit_df["test_acc"], marker="o") plt.xlabel("Ratio of test data(vs train data)") plt.xticks(trial_range) plt.ylabel("Model accuracy score") plt.title("Decision Tree model accuracy with different test:train ratios") plt.legend()
Titanic - Machine Learning from Disaster
6,959,732
removed_cols = ['nota_mat', 'Unnamed: 0', 'gasto_pc_saude'] <define_variables>
train_accuracy = [] test_accuracy = [] trial_range = range(1,11) for depth in trial_range: temp_dt = tree.DecisionTreeClassifier(random_state = 0, max_depth = depth) temp_dt.fit(X_train, y_train) train_accuracy.append(temp_dt.score(X_train, y_train)) test_accuracy.append(temp_dt.score(X_test, y_test)) maxdepth_df = pd.DataFrame({"max_depth": trial_range, "train_acc": train_accuracy, "test_acc": test_accuracy}) maxdepth_df
Titanic - Machine Learning from Disaster
6,959,732
feats = [c for c in df.columns if c not in removed_cols]<import_modules>
max_depth_fixed = 4
Titanic - Machine Learning from Disaster
6,959,732
from sklearn.ensemble import RandomForestRegressor, ExtraTreesRegressor from sklearn.ensemble import AdaBoostRegressor, GradientBoostingRegressor from sklearn.tree import DecisionTreeRegressor from sklearn.linear_model import LinearRegression from sklearn.neighbors import KNeighborsRegressor from sklearn.svm import SVR from xgboost import XGBClassifier<choose_model_class>
train_accuracy = [] test_accuracy = [] trial_range = range(2,51) for samples in trial_range: temp_dt = tree.DecisionTreeClassifier(random_state = 0, max_depth = max_depth_fixed, min_samples_leaf = samples) temp_dt.fit(X_train, y_train) train_accuracy.append(temp_dt.score(X_train, y_train)) test_accuracy.append(temp_dt.score(X_test, y_test)) minsamples_df = pd.DataFrame({"min_samples_leaf": trial_range, "train_acc": train_accuracy, "test_acc": test_accuracy}) plt.figure(figsize =(20,5)) plt.plot(minsamples_df["min_samples_leaf"], minsamples_df["train_acc"], marker = "o") plt.plot(minsamples_df["min_samples_leaf"], minsamples_df["test_acc"], marker = "o") plt.xlabel("Minimum samples in terminal nodes") plt.xticks(range(0, max(trial_range)+ 2, 2)) plt.ylabel("Model accuracy score") plt.title("Decision Tree model accuracy with varying 'min_samples_leaf'") plt.legend()
Titanic - Machine Learning from Disaster
6,959,732
models = {'RandomForest': RandomForestRegressor(random_state=42), 'ExtraTrees': ExtraTreesRegressor(random_state=42), 'GBM': GradientBoostingRegressor(random_state=42), 'DecisionTree': DecisionTreeRegressor(random_state=42), 'AdaBoost': AdaBoostRegressor(random_state=42), 'KNN 1': KNeighborsRegressor(n_neighbors=1), 'KNN 3': KNeighborsRegressor(n_neighbors=3), 'KNN 11': KNeighborsRegressor(n_neighbors=11), 'SVR': SVR() , 'Linear Regression': LinearRegression() }<import_modules>
dt_model = tree.DecisionTreeClassifier(random_state = 0, max_depth = max_depth_fixed, min_samples_leaf = 10) dt_model.fit(X_train, y_train) print("Train Accuracy:", dt_model.score(X_train, y_train)) print("Test Accuracy:", dt_model.score(X_test, y_test))
Titanic - Machine Learning from Disaster
6,959,732
from sklearn.metrics import mean_squared_error<import_modules>
regression = LogisticRegression(solver = 'lbfgs') regression.fit(X_train, y_train) print("Logistic Regression model") print("="*25) print("Train Accuracy:", regression.score(X_train, y_train)) print("Test Accuracy:", regression.score(X_test, y_test))
Titanic - Machine Learning from Disaster
6,959,732
from sklearn.metrics import mean_squared_error<compute_train_metric>
random_forest = RandomForestClassifier(n_estimators = 100) random_forest.fit(X_train, y_train) print("Random Forest Classifier model") print("="*30) print("Train Accuracy:", random_forest.score(X_train, y_train)) print("Test Accuracy:", random_forest.score(X_test, y_test))
Titanic - Machine Learning from Disaster
6,959,732
def run_model(model, train, valid, feats, y_name): model.fit(train[feats], train[y_name]) preds = model.predict(valid[feats]) return mean_squared_error(valid[y_name], preds)**(1/2 )<filter>
xgb = XGBClassifier() xgb.fit(X_train, y_train) print("XGB Classifier model") print("="*20) print("Train Accuracy:", xgb.score(X_train, y_train)) print("Test Accuracy:", xgb.score(X_test, y_test))
Titanic - Machine Learning from Disaster
6,959,732
train_feat = train[feats]<find_best_params>
validation_df
Titanic - Machine Learning from Disaster
6,959,732
scores = [] for name, model in models.items() : score = run_model(model, train, valid, feats, 'nota_mat') scores.append(score) print(name+':', score )<train_model>
X_validate = validation_df.drop("PassengerId", axis = 1 )
Titanic - Machine Learning from Disaster
6,959,732
rf = RandomForestRegressor(random_state=42) rf.fit(train[feats], train['nota_mat']) pd.Series(rf.feature_importances_, index=feats ).sort_values().plot.barh()<choose_model_class>
dt_model.fit(X, y) prediction = dt_model.predict(X_validate) prediction
Titanic - Machine Learning from Disaster
6,959,732
<train_model><EOS>
output = pd.DataFrame({'PassengerId': validation_df.PassengerId, 'Survived': prediction}) output.to_csv('my_submission.csv', index = False )
Titanic - Machine Learning from Disaster
6,490,094
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<predict_on_test>
sns.set(style="darkgrid") warnings.filterwarnings('ignore') SEED = 42
Titanic - Machine Learning from Disaster
6,490,094
train_preds = alg.predict(train[feats] )<compute_test_metric>
def concat_df(train_data, test_data): return pd.concat([train_data, test_data], sort=True ).reset_index(drop=True) def divide_df(all_data): return all_data.loc[:890], all_data.loc[891:].drop(['Survived'], axis=1) df_train = pd.read_csv('.. /input/titanic/train.csv') df_test = pd.read_csv('.. /input/titanic/test.csv') df_all = concat_df(df_train, df_test) df_train.name = 'Training Set' df_test.name = 'Test Set' df_all.name = 'All Set' dfs = [df_train, df_test] print('Number of Training Examples = {}'.format(df_train.shape[0])) print('Number of Test Examples = {} '.format(df_test.shape[0])) print('Training X Shape = {}'.format(df_train.shape)) print('Training y Shape = {} '.format(df_train['Survived'].shape[0])) print('Test X Shape = {}'.format(df_test.shape)) print('Test y Shape = {} '.format(df_test.shape[0])) print(df_train.columns) print(df_test.columns )
Titanic - Machine Learning from Disaster
6,490,094
mean_squared_error(train['nota_mat'], train_preds)**(1/2 )<predict_on_test>
def display_missing(df): for col in df.columns.tolist() : print('{} column missing values: {}'.format(col, df[col].isnull().sum())) print(' ') for df in dfs: print('{}'.format(df.name)) display_missing(df )
Titanic - Machine Learning from Disaster
6,490,094
valid_preds = alg.predict(valid[feats] )<compute_test_metric>
age_by_pclass_sex = df_all.groupby(['Sex', 'Pclass'] ).median() ['Age'] for pclass in range(1, 4): for sex in ['female', 'male']: print('Median age of Pclass {} {}s: {}'.format(pclass, sex, age_by_pclass_sex[sex][pclass])) print('Median age of all passengers: {}'.format(df_all['Age'].median())) df_all['Age'] = df_all.groupby(['Sex', 'Pclass'])['Age'].apply(lambda x: x.fillna(x.median()))
Titanic - Machine Learning from Disaster
6,490,094
mean_squared_error(valid['nota_mat'], valid_preds)**(1/2 )<predict_on_test>
df_all[df_all['Embarked'].isnull() ]
Titanic - Machine Learning from Disaster
6,490,094
test['nota_mat'] = np.exp(alg.predict(test[feats]))<save_to_csv>
df_all['Embarked'] = df_all['Embarked'].fillna('S' )
Titanic - Machine Learning from Disaster
6,490,094
test[['codigo_mun', 'nota_mat']].to_csv('Edison_Martins_13.csv', index=False )<load_from_csv>
med_fare = df_all.groupby(['Pclass', 'Parch', 'SibSp'] ).Fare.median() [3][0][0] df_all['Fare'] = df_all['Fare'].fillna(med_fare )
Titanic - Machine Learning from Disaster
6,490,094
test = pd.read_csv('.. /input/test.csv',low_memory=False) df = pd.read_csv('.. /input/train.csv',low_memory=False )<feature_engineering>
idx = df_all[df_all['Deck'] == 'T'].index df_all.loc[idx, 'Deck'] = 'A'
Titanic - Machine Learning from Disaster