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() ...
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.en...
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'] ...
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() ,KN...
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,activat...
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 = {...
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'...
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_b...
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...
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_...
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 ...
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_le...
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...
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'] = datase...
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]["Age...
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 = t...
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(accurac...
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 o...
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_co...
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_st...
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 = ...
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...
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_...
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), 'K...
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'...
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.g...
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