kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
10,001,986
def quadratic_kappa(y_hat, y): return torch.tensor(cohen_kappa_score(torch.round(y_hat), y, weights='quadratic'),device='cuda:0') <choose_model_class>
from sklearn import metrics from sklearn.metrics import confusion_matrix from sklearn.metrics import roc_auc_score, accuracy_score, log_loss, auc from sklearn.metrics import accuracy_score import scikitplot as skplt from sklearn.inspection import permutation_importance import xgboost as xgb from xgboost import XGBClass...
Titanic - Machine Learning from Disaster
10,001,986
learn = cnn_learner(data,models.resnet152,metrics=[quadratic_kappa],model_dir='/kaggle',pretrained=True )<find_best_params>
Results = pd.DataFrame({'Model': [],'Accuracy': [], 'Recall':[], 'Precision':[], 'F1_score':[], 'Roc_Auc':[], 'Log_loss':[], 'Positive Samples':[], }) def model_evaluators(y_valid, preds, preds_proba, modelName): tn, fp, fn, tp = confusion_matrix(y_valid, preds ).ravel() acc_ =(tp + tn)/(tp + tn + fn + fp) sens_ = tp...
Titanic - Machine Learning from Disaster
10,001,986
learn.lr_find() <train_model>
predictors = [i for i in X_train.columns if i not in ['PassengerId']] def modelfit_eval(clf, X_train, y_train, X_valid, y_valid, predictors, clf_name): model = clf model.fit(X_train[predictors], y_train) preds = model.predict(X_valid[predictors]) preds_proba = model.predict_proba(X_valid[predictors])[:, 1] model_xgb ...
Titanic - Machine Learning from Disaster
10,001,986
lr=1e-2 learn.fit_one_cycle(3,lr )<categorify>
def modelfit(model, X_train, y_train, predictors, useTrainCV=True, cv_folds=5, early_stopping_rounds=50): if useTrainCV: xgb_param = model.get_xgb_params() xgtrain = xgb.DMatrix(X_train[predictors].values, label=y_train.values) cvresult = xgb.cv(xgb_param, xgtrain, num_boost_round=model.get_params() ['n_estimators'], ...
Titanic - Machine Learning from Disaster
10,001,986
learn.data = data =(src.transform(tfms,size=256 ).databunch().normalize(imagenet_stats))<train_model>
xgb1 = XGBClassifier(learning_rate =0.1, n_estimators=1000, max_depth=4, min_child_weight=0, gamma=0, subsample=0.8, colsample_bytree=0.8, objective= 'binary:logistic', nthread=4, scale_pos_weight=1, seed=27) modelfit(xgb1, X_train, y_train, predictors )
Titanic - Machine Learning from Disaster
10,001,986
learn.fit_one_cycle(5,max_lr=slice(1e-4))<find_best_params>
param_test1 = {'max_depth':range(3,10,1), 'min_child_weight':range(0,6,1)} gsearch1 = GridSearchCV(estimator = XGBClassifier(learning_rate =0.1, n_estimators=3, max_depth=4, min_child_weight=0, gamma=0, subsample=0.8, colsample_bytree=0.8, objective= 'binary:logistic', nthread=4, scale_pos_weight=1, seed=27), param_gri...
Titanic - Machine Learning from Disaster
10,001,986
learn.lr_find()<train_model>
param_test3 = {'gamma':[i/10.0 for i in range(0,10)]} gsearch3 = GridSearchCV(estimator = XGBClassifier(learning_rate =0.1, n_estimators=3, max_depth=4, min_child_weight=1, gamma=0, subsample=0.8, colsample_bytree=0.8, objective= 'binary:logistic', nthread=4, scale_pos_weight=1, seed=27), param_grid = param_test3, scor...
Titanic - Machine Learning from Disaster
10,001,986
learn.fit_one_cycle(5,max_lr=9e-04 )<predict_on_test>
xgb2 = XGBClassifier(learning_rate =0.1, n_estimators=1000, max_depth=4, min_child_weight=1, gamma=0.6, subsample=0.8, colsample_bytree=0.8, objective= 'binary:logistic', nthread=4, scale_pos_weight=1, seed=27) modelfit(xgb2, X_train, y_train, predictors )
Titanic - Machine Learning from Disaster
10,001,986
valid_preds = learn.get_preds(ds_type = DatasetType.Valid )<compute_test_metric>
param_test4 = {'subsample':[i/10.0 for i in range(6,10)], 'colsample_bytree':[i/10.0 for i in range(6,10)]} gsearch4 = GridSearchCV(estimator = XGBClassifier(learning_rate =0.1, n_estimators=8, max_depth=4, min_child_weight=1, gamma=0.6, subsample=0.8, colsample_bytree=0.8, objective= 'binary:logistic', nthread=4, scal...
Titanic - Machine Learning from Disaster
10,001,986
class OptimizedRounder(object): def __init__(self): self.coef_ = 0 def _kappa_loss(self, coef, X, y): X_p = np.copy(X) for i, pred in enumerate(X_p): if pred < coef[0]: X_p[i] = 0 elif pred >= coef[0] and pred < coef[1]: X_p[i] = 1 elif pred >= coef[1] and pred < coef[2]: X_p[i] = 2 elif pred >= coef[2] and pred < coe...
param_test5 = {'subsample':[i/100.0 for i in range(85,100,5)], 'colsample_bytree':[i/100.0 for i in range(75,90,5)]} gsearch5 = GridSearchCV(estimator = XGBClassifier(learning_rate =0.1, n_estimators=8, max_depth=4, min_child_weight=1, gamma=0.6, subsample=0.9, colsample_bytree=0.8, objective= 'binary:logistic', nthrea...
Titanic - Machine Learning from Disaster
10,001,986
optR = OptimizedRounder() optR.fit(valid_preds[0],valid_preds[1] )<load_from_csv>
param_test6 = {'reg_alpha':[1e-5, 0.0005, 1e-2, 0.1, 0.5, 1, 100]} gsearch6 = GridSearchCV(estimator = XGBClassifier(learning_rate =0.1, n_estimators=8, max_depth=4, min_child_weight=1, gamma=0.6, subsample=0.9, colsample_bytree=0.75, objective= 'binary:logistic', nthread=4, scale_pos_weight=1, seed=27), param_grid = p...
Titanic - Machine Learning from Disaster
10,001,986
sample_df = pd.read_csv(path/'sample_submission.csv' )<define_variables>
param_test7 = {'reg_alpha':[1e-07, 1e-06, 1e-05, 1e-04, 1e-03, 1e-02]} gsearch7 = GridSearchCV(estimator = XGBClassifier(learning_rate =0.1, n_estimators=8, max_depth=4, min_child_weight=1, gamma=0.6, subsample=0.9, colsample_bytree=0.75, objective= 'binary:logistic', nthread=4, scale_pos_weight=1, seed=27), param_grid...
Titanic - Machine Learning from Disaster
10,001,986
learn.data.add_test(ImageList.from_df(sample_df,path,folder='test_images',suffix='.png'))<predict_on_test>
xgb3 = XGBClassifier(learning_rate =0.1, n_estimators=8, max_depth=4, min_child_weight=1, gamma=0.6, subsample=0.9, colsample_bytree=0.75, reg_alpha=1e-07, objective= 'binary:logistic', nthread=4, scale_pos_weight=1, seed=27) modelfit(xgb3, X_train, y_train, predictors )
Titanic - Machine Learning from Disaster
10,001,986
preds,y = learn.get_preds(DatasetType.Test )<predict_on_test>
xgb4 = XGBClassifier(learning_rate =0.001, n_estimators=200, max_depth=4, min_child_weight=1, gamma=0.6, subsample=0.9, colsample_bytree=0.75, reg_alpha=1e-07, objective= 'binary:logistic', nthread=4, scale_pos_weight=1, seed=27) modelfit(xgb4, X_train, y_train, predictors )
Titanic - Machine Learning from Disaster
10,001,986
test_predictions = optR.predict(preds,coefficients )<data_type_conversions>
model_xgb = xgb4 model_xgb.fit(X_train[predictors], y_train) preds = model_xgb.predict(X_valid[predictors]) preds_proba = model_xgb.predict_proba(X_valid[predictors])[:, 1] res = model_evaluators(y_valid, preds, preds_proba, 'Hyperparametarized XGB') Results = Results.append(res, ignore_index=True) Results
Titanic - Machine Learning from Disaster
10,001,986
sample_df.diagnosis = test_predictions.astype(int) sample_df.head()<save_to_csv>
rf_grid_param = {'n_estimators': [100, 200, 300, 400], 'max_features': ['auto', 'sqrt', 'log2'], 'max_depth': [4, 5, 7, None], 'min_samples_split': [2, 3, 5, 7], 'min_samples_leaf': [1, 3, 5, 7]} dt_grid_param = {'criterion': ['gini', 'entropy'], 'max_features': ['auto', 'sqrt', 'log2'], 'max_depth': [4, 5, 7, None], '...
Titanic - Machine Learning from Disaster
10,001,986
sample_df.to_csv('submission.csv',index = False )<define_variables>
preds_proba = model_rf.best_estimator_.predict_proba(X_valid[predictors])[:, 1] X_valid['preds_proba'] = preds_proba X_valid['preds'] = preds_list[0] X_valid['true_preds'] = y_valid wrong_preds = X_valid.loc[(( X_valid.preds == 1)&(X_valid.true_preds == 0)) | (( X_valid.preds == 0)&(X_valid.true_preds == 1)) ].sort_va...
Titanic - Machine Learning from Disaster
10,001,986
train_csv = '.. /input/aptos2019-blindness-detection/train.csv' image_dataset = '.. /input/aptos2019-blindness-detection/train_images' sample_csv = '.. /input/aptos2019-blindness-detection/sample_submission.csv' test_dataset = '.. /input/aptos2019-blindness-detection/test_images' resnet_weights = '.. /input/resnet50-im...
print('Total Error examples:', wrong_preds.shape[0]) print('-------------------------') print(wrong_preds['preds'].value_counts()) print('-------------------------') print(wrong_preds['Sex_female'].value_counts()) print('-------------------------') print(wrong_preds['Embarked'].value_counts()) print('-----------...
Titanic - Machine Learning from Disaster
10,001,986
def cohens_kappa(y_true, y_pred): y_true_classes = tf.argmax(y_true, 1) y_pred_classes = tf.argmax(y_pred, 1) return tf.contrib.metrics.cohen_kappa(y_true_classes, y_pred_classes, 5)[1]<import_modules>
print('Unknown Decks and Lonely Travellers:', wrong_preds.loc[(( wrong_preds.Deck < 0.522068)&(wrong_preds.Deck > 0.522066)) & (( wrong_preds.FamilySize < -0.560974)&(wrong_preds.FamilySize > -0.560976)) ].shape[0]) print('Unknown Decks Lonely Travellers embarked from Southampton:', wrong_preds.loc[(( wrong_preds.Dec...
Titanic - Machine Learning from Disaster
10,001,986
img = Input(shape=(224,224,3)) base_model = Xception(include_top = False, weights=xception_weights, input_tensor=img, pooling='avg', input_shape = None) final_layer = base_model.layers[-1].output final_layer = Dropout(0.2 )(final_layer) dense_layer1 = Dense(512, activation='relu' )(final_layer) dense_layer1 = Drop...
def f(row): if(row['Title'] > 0.214010 and row['Title'] < 0.214012)and(row['FamilySize'] > -0.560976 and row['FamilySize'] < -0.560974): val = 1 else: val = 0 return val X['Mr_lonely'] = X.apply(f, axis=1) X_test_full['Mr_lonely'] = X_test_full.apply(f, axis=1) def f(row): if(row['Deck'] > 0.522066 and row['Deck'] < ...
Titanic - Machine Learning from Disaster
10,001,986
reduce_lr = ReduceLROnPlateau(monitor='val_loss', min_delta=0.0004, patience=5, factor=0.5, min_lr=1e-6, mode='auto', verbose=1 )<choose_model_class>
X_train, X_valid, y_train, y_valid = train_test_split(X, y, train_size=0.7, test_size=0.3, random_state=27) rf_grid_param = {'n_estimators': [200, 300, 400, 700], 'max_features': ['auto', 'sqrt', 'log2'], 'max_depth': [4, 5, 7, None], 'min_samples_split': [2, 3, 5, 7], 'min_samples_leaf': [1, 3, 5, 7]} model_rf, _ = m...
Titanic - Machine Learning from Disaster
10,001,986
early_stop = EarlyStopping(monitor='val_loss', min_delta=0.0001, patience=10, verbose=1, mode='auto' )<feature_engineering>
preds_test = model.predict(X_test_full[predictors]) output = pd.DataFrame({'PassengerId': X_test_full.PassengerId, 'Survived': preds_test}) output.to_csv('my_submission.csv', index=False) print("Your submission was successfully saved!" )
Titanic - Machine Learning from Disaster
11,436,872
df_train = pd.read_csv(train_csv) df_train["id_code"] = df_train["id_code"].apply(lambda x:x+".png") df_train["diagnosis"] = df_train['diagnosis'].astype('str') train_datagen = ImageDataGenerator(rescale = 1/255., horizontal_flip = True, vertical_flip = False, width_shift_range = 0.1, height_shift_range = 0.1, fill_...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import missingno as msno import seaborn as sns
Titanic - Machine Learning from Disaster
11,436,872
test_datagen = ImageDataGenerator(rescale=1./255, preprocessing_function=preprocess_image) sample_df = pd.read_csv(sample_csv) sample_df["id_code"]=sample_df["id_code"].apply(lambda x:x+".png") test_generator = test_datagen.flow_from_dataframe( dataframe=sample_df, directory = test_dataset, x_col="id_code", target_...
titanic_train_df = pd.read_csv('.. /input/titanic/train.csv') titanic_test_df = pd.read_csv('.. /input/titanic/test.csv') titanic_test_df1 = pd.read_csv('.. /input/titanic/test.csv' )
Titanic - Machine Learning from Disaster
11,436,872
y_true = val_generator.classes y_pred = np.argmax(model.predict_generator(val_generator),axis=1) print(confusion_matrix(y_true,y_pred)) target_names = ['0','1','2','3','4'] print(classification_report(val_generator.classes, y_pred, target_names=target_names))<save_to_csv>
titanic_train_df_survived = titanic_train_df[titanic_train_df['Survived'] == 1]
Titanic - Machine Learning from Disaster
11,436,872
filenames= test_generator.filenames results=pd.DataFrame({"id_code":filenames, "diagnosis":np.argmax(preds,axis = 1)}) results['id_code'] = results['id_code'].map(lambda x: str(x)[:-4]) results.to_csv("submission.csv",index=False )<set_options>
survived_gender = titanic_train_df_survived.groupby('Sex', as_index=False ).count()
Titanic - Machine Learning from Disaster
11,436,872
%reload_ext autoreload %autoreload 2 %matplotlib inline<import_modules>
titanic_train_df_embark = titanic_train_df.groupby('Embarked', as_index=False ).count() titanic_train_df_survived_embark = titanic_train_df_survived.groupby('Embarked', as_index=False ).count()
Titanic - Machine Learning from Disaster
11,436,872
import fastai from fastai import * from fastai.vision import * from fastai.callbacks import * import cv2 import pandas as pd import matplotlib.pyplot as plt<set_options>
titanic_train_df.drop(columns=['Name','Cabin','Ticket'] , inplace=True )
Titanic - Machine Learning from Disaster
11,436,872
print('Make sure cudnn is enabled:', torch.backends.cudnn.enabled )<set_options>
titanic_test_df.drop(columns=['Name','Cabin','Ticket'] , inplace=True)
Titanic - Machine Learning from Disaster
11,436,872
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 = 1667 seed_everything(SEED )<load_from_csv>
le=LabelEncoder() le.fit(titanic_train_df['Sex'] )
Titanic - Machine Learning from Disaster
11,436,872
def get_2015_df() : base_image_dir = os.path.join('.. ', 'input/resized-2015-2019-blindness-detection-images/') train_dir = os.path.join(base_image_dir,'resized train 15/') df = pd.read_csv(os.path.join(base_image_dir, 'labels/trainLabels15.csv')) df.columns = ['image', 'diagnosis'] df['path'] = df['image'].map(lambd...
titanic_train_df['Sex']= le.transform(titanic_train_df['Sex'] )
Titanic - Machine Learning from Disaster
11,436,872
def get_df_2019() : base_image_dir = os.path.join('.. ', 'input/resized-2015-2019-blindness-detection-images/') train_dir = os.path.join(base_image_dir,'resized train 19/') df = pd.read_csv(os.path.join(base_image_dir, 'labels/trainLabels19.csv')) df['path'] = df['id_code'].map(lambda x: os.path.join(train_dir,'{}.jp...
titanic_test_df['Sex'] = le.transform(titanic_test_df['Sex'] )
Titanic - Machine Learning from Disaster
11,436,872
base_image_dir = os.path.join('.. ', 'input/aptos2019-blindness-detection/') train_dir = os.path.join(base_image_dir,'train_images/') df = pd.read_csv(os.path.join(base_image_dir, 'train.csv')) df['path'] = df['id_code'].map(lambda x: os.path.join(train_dir,'{}.png'.format(x))) df = df.drop(columns=['id_code']) df ...
leembark=LabelEncoder() leembark.fit(titanic_train_df['Embarked'].astype(str))
Titanic - Machine Learning from Disaster
11,436,872
tfms = get_transforms(do_flip=True, flip_vert=True, max_rotate=0.10, max_zoom=1.3, max_warp=0.0, max_lighting=0.2) data =( src.transform(tfms,size=128) .databunch() .normalize(imagenet_stats) )<compute_test_metric>
titanic_train_df['Embarked'] = leembark.transform(titanic_train_df['Embarked'].astype(str)) titanic_test_df['Embarked'] = leembark.transform(titanic_test_df['Embarked'].astype(str))
Titanic - Machine Learning from Disaster
11,436,872
def quadratic_kappa(y_hat, y): return torch.tensor(cohen_kappa_score(torch.round(y_hat), y, weights='quadratic'),device='cuda:0' )<choose_model_class>
titanic_train_df_x = titanic_train_df.drop(columns=['Survived'] )
Titanic - Machine Learning from Disaster
11,436,872
learn = cnn_learner(data, base_arch=models.resnet50 ,metrics=[quadratic_kappa],model_dir='/kaggle',pretrained=True )<train_model>
titanic_train_df_y =titanic_train_df['Survived'].to_frame()
Titanic - Machine Learning from Disaster
11,436,872
learn.fit_one_cycle(3, 1e-2 )<normalization>
si = SimpleImputer(missing_values=np.nan, strategy='mean' )
Titanic - Machine Learning from Disaster
11,436,872
learn.data = data =( src.transform(tfms,size=256) .databunch() .normalize(imagenet_stats) ) learn.lr_find() learn.recorder.plot()<train_model>
titanic_train_df_x = si.fit_transform(titanic_train_df_x )
Titanic - Machine Learning from Disaster
11,436,872
lr = 1e-2 learn.fit_one_cycle(5, lr )<find_best_params>
titanic_test_df = si.transform(titanic_test_df )
Titanic - Machine Learning from Disaster
11,436,872
learn.unfreeze() learn.lr_find() learn.recorder.plot()<train_model>
sc = StandardScaler()
Titanic - Machine Learning from Disaster
11,436,872
learn.fit_one_cycle(10, slice(1e-6,1e-4))<set_options>
titanic_train_df_x = sc.fit_transform(titanic_train_df_x )
Titanic - Machine Learning from Disaster
11,436,872
learn.export() learn.save('resnet_old_image_weight' )<find_best_params>
titanic_test_df = sc.transform(titanic_test_df )
Titanic - Machine Learning from Disaster
11,436,872
interp = ClassificationInterpretation.from_learner(learn) losses,idxs = interp.top_losses() len(data.valid_ds)==len(losses)==len(idxs )<predict_on_test>
from sklearn.svm import SVC
Titanic - Machine Learning from Disaster
11,436,872
valid_preds = learn.get_preds(ds_type=DatasetType.Valid )<import_modules>
clf_svm = SVC(C=0.8 )
Titanic - Machine Learning from Disaster
11,436,872
import numpy as np import pandas as pd import os import scipy as sp from functools import partial from sklearn import metrics from collections import Counter import json<compute_test_metric>
clf_svm.fit(titanic_train_df_x, titanic_train_df_y )
Titanic - Machine Learning from Disaster
11,436,872
class OptimizedRounder(object): def __init__(self): self.coef_ = 0 def _kappa_loss(self, coef, X, y): X_p = np.copy(X) for i, pred in enumerate(X_p): if pred < coef[0]: X_p[i] = 0 elif pred >= coef[0] and pred < coef[1]: X_p[i] = 1 elif pred >= coef[1] and pred < coef[2]: X_p[i] = 2 elif pred >= coef[2] and pred < coe...
svm_pred = clf_svm.predict(titanic_test_df )
Titanic - Machine Learning from Disaster
11,436,872
optR = OptimizedRounder() optR.fit(valid_preds[0],valid_preds[1] )<load_from_csv>
result_df = pd.DataFrame({'PassengerID':titanic_test_df1['PassengerId'],'Survived':svm_pred} )
Titanic - Machine Learning from Disaster
11,436,872
<save_to_csv><EOS>
result_df.to_csv('csv_to_submit.csv', index = False)
Titanic - Machine Learning from Disaster
2,804,369
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<set_options>
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns
Titanic - Machine Learning from Disaster
2,804,369
%reload_ext autoreload %autoreload 2 %matplotlib inline<import_modules>
data_train = pd.read_csv(".. /input/train.csv") data_test = pd.read_csv(".. /input/test.csv" )
Titanic - Machine Learning from Disaster
2,804,369
from fastai import * from fastai.vision import * import pandas as pd import matplotlib.pyplot as plt import numpy as np import os import scipy as sp from functools import partial from sklearn import metrics from collections import Counter from fastai.callbacks import * import PIL import cv2<set_options>
def cabin_imputer(cabin): if cabin != "Unknown": return cabin[0] return cabin def age_to_cat(age): if np.isnan(age): return "Unknown" elif age < 13: return "Kid" elif age <= 18: return "Teen" elif age > 60: return "Elder" else: return "Adult" def substrings_in_string(big_string, substrings): for substring in substrings...
Titanic - Machine Learning from Disaster
2,804,369
def seed_everything(seed=1358): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True seed_everything()<define_variables>
data_train = pd.read_csv(".. /input/train.csv") data_test = pd.read_csv(".. /input/test.csv") y_data = data_train.Survived x_data_train = clear_dataset(data_train) x_data_test = clear_dataset(data_test )
Titanic - Machine Learning from Disaster
2,804,369
PATH = '/kaggle/input/aptos2019-blindness-detection/' train_img_path = PATH +'train_images/' test_img_path = PATH +'test_images/' train_file_name = PATH +'train.csv' test_file_name = PATH +'test.csv' bs=24 sz=224<load_from_csv>
x_data_train.drop(["PassengerId", "Survived"], axis=1,inplace=True) x_data_test.drop(["PassengerId"], axis=1,inplace=True )
Titanic - Machine Learning from Disaster
2,804,369
df = pd.read_csv(PATH +'train.csv') df.head()<feature_engineering>
test_encoded = pd.get_dummies(x_data_test) train_encoded = pd.get_dummies(x_data_train) test_encoded= test_encoded.reindex(columns = train_encoded.columns, fill_value=0 )
Titanic - Machine Learning from Disaster
2,804,369
tfms = get_transforms(do_flip=True, flip_vert=True, max_rotate=0.10, max_zoom=1.3, max_warp=0.0, max_lighting=0.2 )<categorify>
pca = PCA(n_components = 2, whiten= True) x_pca = pca.fit_transform(train_encoded) print("variance ratio: ", pca.explained_variance_ratio_) print("sum: ",sum(pca.explained_variance_ratio_))
Titanic - Machine Learning from Disaster
2,804,369
data =( src.transform(get_transforms() ,size=224) .databunch() .normalize(imagenet_stats) ) data<compute_test_metric>
x_train, x_val, y_train, y_val = train_test_split(train_encoded, y_data, test_size=0.25, random_state=42 )
Titanic - Machine Learning from Disaster
2,804,369
learn = cnn_learner(data, base_arch=models.resnet34 ,metrics=[error_rate],model_dir='/kaggle/working',pretrained=True )<train_model>
def get_metrics(y_test, y_predicted): precision = precision_score(y_test, y_predicted, pos_label=None, average='weighted') recall = recall_score(y_test, y_predicted, pos_label=None, average='weighted') f1 = f1_score(y_test, y_predicted, pos_label=None, average='weighted') accuracy = accuracy_score(y_test, y_predicte...
Titanic - Machine Learning from Disaster
2,804,369
lr = 1e-2 learn.fit_one_cycle(2, lr )<save_model>
clf = RandomForestClassifier(n_estimators=300, max_depth=6,max_features=11,criterion="gini",n_jobs=-1, random_state=42) clf.fit(x_train, y_train) y_predicted = clf.predict(x_val) accuracy, precision, recall, f1 = get_metrics(y_val, y_predicted) print("accuracy = %.3f, precision = %.3f, recall = %.3f, f1 = %.3f" %(a...
Titanic - Machine Learning from Disaster
2,804,369
learn.save('stage-1' )<train_model>
y_predicted = clf.predict(x_train) accuracy, precision, recall, f1 = get_metrics(y_train, y_predicted) print("accuracy = %.3f, precision = %.3f, recall = %.3f, f1 = %.3f" %(accuracy, precision, recall, f1))
Titanic - Machine Learning from Disaster
2,804,369
learn.fit_one_cycle(5, slice(1e-4,lr/5))<import_modules>
clf = XGBClassifier(n_estimators= 300, learning_rate=0.3, max_depth=4) clf.fit(x_train, y_train) y_predicted = clf.predict(x_val) accuracy, precision, recall, f1 = get_metrics(y_val, y_predicted) print("accuracy = %.3f, precision = %.3f, recall = %.3f, f1 = %.3f" %(accuracy, precision, recall, f1))
Titanic - Machine Learning from Disaster
2,804,369
learn.export('/kaggle/working/blindness-detection.pkl' )<define_variables>
y_predicted = clf.predict(x_train) accuracy, precision, recall, f1 = get_metrics(y_train, y_predicted) print("train accuracy = %.3f, precision = %.3f, recall = %.3f, f1 = %.3f" %(accuracy, precision, recall, f1))
Titanic - Machine Learning from Disaster
2,804,369
train_csv = ".. /input/aptos2019-blindness-detection/train.csv" test_csv = ".. /input/aptos2019-blindness-detection/test.csv" train_dir = ".. /input/aptos2019-blindness-detection/train_images/" test_dir = ".. /input/aptos2019-blindness-detection/test_images/"<load_from_csv>
clf = LogisticRegression(C=2.0, solver="newton-cg", penalty="l2", n_jobs=-1) clf.fit(x_train, y_train) y_predicted = clf.predict(x_val) accuracy, precision, recall, f1 = get_metrics(y_val, y_predicted) print("accuracy = %.3f, precision = %.3f, recall = %.3f, f1 = %.3f" %(accuracy, precision, recall, f1))
Titanic - Machine Learning from Disaster
2,804,369
df = pd.read_csv(train_csv) size = 256,256<train_on_grid>
y_predicted = clf.predict(x_train) accuracy, precision, recall, f1 = get_metrics(y_train, y_predicted) print("train accuracy = %.3f, precision = %.3f, recall = %.3f, f1 = %.3f" %(accuracy, precision, recall, f1))
Titanic - Machine Learning from Disaster
2,804,369
def load_image(path): img = cv2.resize(cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB), size) img = get_cropped_image(img) return img<categorify>
clf = GaussianNB() clf.fit(x_train, y_train) y_predicted = clf.predict(x_val) accuracy, precision, recall, f1 = get_metrics(y_val, y_predicted) print("accuracy = %.3f, precision = %.3f, recall = %.3f, f1 = %.3f" %(accuracy, precision, recall, f1))
Titanic - Machine Learning from Disaster
2,804,369
labels = df["diagnosis"].values.tolist() labels = keras.utils.to_categorical(labels )<split>
y_predicted = clf.predict(x_train) accuracy, precision, recall, f1 = get_metrics(y_train, y_predicted) print("train accuracy = %.3f, precision = %.3f, recall = %.3f, f1 = %.3f" %(accuracy, precision, recall, f1))
Titanic - Machine Learning from Disaster
2,804,369
images, x_val, labels, y_val = train_test_split(images, labels, test_size = 0.15 )<define_variables>
clf = BernoulliNB(alpha=0.2) clf.fit(x_train, y_train) y_predicted = clf.predict(x_val) accuracy, precision, recall, f1 = get_metrics(y_val, y_predicted) print("accuracy = %.3f, precision = %.3f, recall = %.3f, f1 = %.3f" %(accuracy, precision, recall, f1))
Titanic - Machine Learning from Disaster
2,804,369
train_aug = ImageDataGenerator(horizontal_flip = True, zoom_range = 0.25, rotation_range = 360, vertical_flip = True) train_generator = train_aug.flow(images, labels, batch_size = 8 )<choose_model_class>
y_predicted = clf.predict(x_train) accuracy, precision, recall, f1 = get_metrics(y_train, y_predicted) print("train accuracy = %.3f, precision = %.3f, recall = %.3f, f1 = %.3f" %(accuracy, precision, recall, f1))
Titanic - Machine Learning from Disaster
2,804,369
input_layer = Input(shape =(256,256,3)) base_model = DenseNet121(include_top = False, input_tensor = input_layer, weights = ".. /input/densenet-keras/DenseNet-BC-121-32-no-top.h5") x = GlobalAveragePooling2D()(base_model.output) x = Dropout(0.5 )(x) out = Dense(5, activation = 'softmax' )(x) model = Model(inputs = ...
clf = SVC(C=40) clf.fit(x_train, y_train) y_predicted = clf.predict(x_val) accuracy, precision, recall, f1 = get_metrics(y_val, y_predicted) print("accuracy = %.3f, precision = %.3f, recall = %.3f, f1 = %.3f" %(accuracy, precision, recall, f1))
Titanic - Machine Learning from Disaster
2,804,369
optimizer = keras.optimizers.Adam(lr=3e-4) es = EarlyStopping(monitor='val_loss', mode='min', patience = 5, restore_best_weights = True) rlrop = ReduceLROnPlateau(monitor='val_loss', mode='min', patience = 2, factor = 0.5, min_lr=1e-6) callback_list = [es, rlrop] model.compile(optimizer = optimizer, loss = "categori...
y_predicted = clf.predict(x_train) accuracy, precision, recall, f1 = get_metrics(y_train, y_predicted) print("train accuracy = %.3f, precision = %.3f, recall = %.3f, f1 = %.3f" %(accuracy, precision, recall, f1))
Titanic - Machine Learning from Disaster
2,804,369
model.fit_generator(generator = train_generator, steps_per_epoch = len(train_generator), epochs = 20, validation_data =(x_val, y_val), callbacks = callback_list )<set_options>
clf = RandomForestClassifier(n_estimators=100, max_depth=6,max_features=11, min_samples_leaf=0.0001,criterion="gini",n_jobs=-1, random_state=42) accuracies = cross_val_score(clf, train_encoded, y_data, cv=5, scoring="accuracy") print("CV accuracy", accuracies.mean() )
Titanic - Machine Learning from Disaster
2,804,369
del train_generator, images gc.collect()<predict_on_test>
clf = clf = LogisticRegression(C=0.9, solver="newton-cg", penalty="l2", n_jobs=-1) accuracies = cross_val_score(clf, train_encoded, y_data, cv=5, scoring="accuracy") print("CV accuracy", accuracies.mean() )
Titanic - Machine Learning from Disaster
2,804,369
predprobs = model.predict(test_images )<define_variables>
submission = pd.read_csv(".. /input/gender_submission.csv" )
Titanic - Machine Learning from Disaster
2,804,369
<save_to_csv><EOS>
clf = RandomForestClassifier(n_estimators=100, max_depth=6,max_features=11, min_samples_leaf=0.0001,criterion="gini",n_jobs=-1, random_state=42) clf.fit(train_encoded, y_data) test_preds = clf.predict(test_encoded) submission.Survived = test_preds submission.to_csv('rf_submission.csv', index=False )
Titanic - Machine Learning from Disaster
8,166,755
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<set_options>
for dirname, _, filenames in os.walk('/kaggle/input'): for filename in filenames: print(os.path.join(dirname, filename))
Titanic - Machine Learning from Disaster
8,166,755
%reset -f %matplotlib inline %config InlineBackend.figure_format = 'retina' print(PIL.PILLOW_VERSION) train_on_gpu = torch.cuda.is_available() if not train_on_gpu: print('CUDA is not available.Training on CPU...') else: print('CUDA is available! Training on GPU...') device = torch.device("cuda:0" if torch.cuda.is_av...
train=pd.read_csv('/kaggle/input/titanic/train.csv') test=pd.read_csv('/kaggle/input/titanic/test.csv') dataset = pd.concat(objs=[train, test], axis=0,sort=False ).reset_index(drop=True )
Titanic - Machine Learning from Disaster
8,166,755
! ls -la.. /input/ data_dir = '.. /input/aptos2019-blindness-detection/' train_dir = data_dir + '/train_images/' test_dir= data_dir + '/test_images/' nThreads = 4 batch_size = 32 use_gpu = torch.cuda.is_available()<categorify>
dataset['Ticket_Frequency'] = dataset.groupby('Ticket')['Ticket'].transform('count') dataset['Cabin_n'] = dataset['Cabin'].str[0] dataset['Cabin_n'].fillna('M',inplace=True) dataset['Deck'] = dataset['Cabin'].apply(lambda s: s[0] if pd.notnull(s)else 'M') dataset['Deck'] = dataset['Deck'].replace(['A', 'B', 'C'], 'A...
Titanic - Machine Learning from Disaster
8,166,755
class GenericDataset() : def __init__(self, labels, root_dir, subset=False, transform=None): self.labels = labels self.root_dir = root_dir self.transform = transform def __len__(self): return len(self.labels) def __getitem__(self, idx): img_name = self.labels.iloc[idx, 0] fullname = join(self.root_dir, img_name) imag...
kfold = StratifiedKFold(n_splits=10 )
Titanic - Machine Learning from Disaster
8,166,755
class GenericDatasetTTA() : def __init__(self, labels, root_dir, subset=False, transform=None,TTA=8): self.labels = labels self.root_dir = root_dir self.transform = transform self.TTA = TTA def __len__(self): return len(self.labels) def __getitem__(self, idx): img_name = self.labels.iloc[idx, 0] fullname = join(self.r...
random_state = 2 classifiers = [] classifiers.append(SVC(random_state=random_state)) classifiers.append(DecisionTreeClassifier(random_state=random_state)) classifiers.append(AdaBoostClassifier(DecisionTreeClassifier(random_state=random_state),random_state=random_state,learning_rate=0.1)) classifiers.append(RandomForest...
Titanic - Machine Learning from Disaster
8,166,755
__all__ = ['SENet', 'senet154', 'se_resnet50', 'se_resnet101', 'se_resnet152', 'se_resnext50_32x4d', 'se_resnext101_32x4d'] pretrained_settings = { 'senet154': { 'imagenet': { 'url': 'http://data.lip6.fr/cadene/pretrainedmodels/senet154-c7b49a05.pth', 'input_space': 'RGB', 'input_size': [3, 224, 224], 'input_range': ...
gbm = GradientBoostingClassifier(random_state=2) gbm.fit(X_train,Y_train) print('Score: ',gbm.score(X_test,Y_test)) feature_importances = pd.DataFrame(gbm.feature_importances_,index = X_test.columns,columns=['importance'] ).sort_values('importance', ascending=False) feature_importances.head(34 )
Titanic - Machine Learning from Disaster
8,166,755
<set_options><EOS>
test_n=dataset[dataset['Survived'].isnull() ] test_n.drop(labels = ["Survived"], axis = 1, inplace = True) submission=pd.DataFrame(columns=['PassengerId','Survived']) submission['PassengerId']=test_n['PassengerId'] test_n.drop(labels = ["PassengerId"], axis = 1, inplace = True) Y_pred=gbm.predict(test_n) submission...
Titanic - Machine Learning from Disaster
8,698,078
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<prepare_x_and_y>
plt.rc("font", size=14) sns.set(style="dark") sns.set(style="darkgrid", color_codes=True) RED = "\033[1;31m" BLUE = "\033[1;34m" CYAN = "\033[1;36m" GREEN = "\033[0;32m"
Titanic - Machine Learning from Disaster
8,698,078
N = test_df.shape[0] x_test = np.empty(( N, im_size, im_size, 3), dtype=np.uint8) try: for i, image_id in enumerate(test_df['id_code']): x_test[i, :, :, :] = preprocess_image( f'.. /input/aptos2019-blindness-detection/test_images/{image_id}.png', desired_size=im_size ) print('Test dataset correctly processed') exc...
titanic_df = pd.read_csv(".. /input/titanic/train.csv") test_df = pd.read_csv(".. /input/titanic/test.csv") titanic_df.head(5)
Titanic - Machine Learning from Disaster
8,698,078
print(os.listdir(".. /input/kerasefficientnetsmaster/keras-efficientnets-master/keras-efficientnets-master/keras_efficientnets")) sys.path.append(os.path.abspath('.. /input/kerasefficientnetsmaster/keras-efficientnets-master/keras-efficientnets-master/')) effnet = EfficientNetB5(input_shape=(im_size,im_size,3), weights...
train_data = titanic_df train_data["Age"].fillna(28, inplace=True) train_data["Embarked"].fillna("S", inplace=True) train_data.drop('Cabin', axis=1, inplace=True )
Titanic - Machine Learning from Disaster
8,698,078
y_test = model.predict(x_test) coef = [0.5, 1.5, 2.5, 3.5] for i, pred in enumerate(y_test): if pred < coef[0]: y_test[i] = 0 elif pred >= coef[0] and pred < coef[1]: y_test[i] = 1 elif pred >= coef[1] and pred < coef[2]: y_test[i] = 2 elif pred >= coef[2] and pred < coef[3]: y_test[i] = 3 else: y_test[i] = 4 test_df[...
train_data['TravelBuds']=train_data["SibSp"]+train_data["Parch"] train_data['TravelAlone']=np.where(train_data['TravelBuds']>0, 0, 1) train_data.drop('SibSp', axis=1, inplace=True) train_data.drop('Parch', axis=1, inplace=True) train_data.drop('TravelBuds', axis=1, inplace=True) train2 = pd.get_dummies(train_data, ...
Titanic - Machine Learning from Disaster
8,698,078
import pandas as pd from sklearn.preprocessing import OneHotEncoder,LabelEncoder from sklearn.model_selection import train_test_split<load_from_csv>
test_df["Age"].fillna(28, inplace=True) test_df["Fare"].fillna(14.45, inplace=True) test_df.drop('Cabin', axis=1, inplace=True )
Titanic - Machine Learning from Disaster
8,698,078
train=pd.read_csv(".. /input/train_V2.csv") <load_from_csv>
test_df['TravelBuds']=test_df["SibSp"]+test_df["Parch"] test_df['TravelAlone']=np.where(test_df['TravelBuds']>0, 0, 1) test_df.drop('SibSp', axis=1, inplace=True) test_df.drop('Parch', axis=1, inplace=True) test_df.drop('TravelBuds', axis=1, inplace=True) test2 = pd.get_dummies(test_df, columns=["Pclass"]) test3 =...
Titanic - Machine Learning from Disaster
8,698,078
test=pd.read_csv(".. /input/test_V2.csv" )<categorify>
df_final['IsMinor']=np.where(train_data['Age']<=16, 1, 0 )
Titanic - Machine Learning from Disaster
8,698,078
le=LabelEncoder() enc=OneHotEncoder() train.loc[(train.matchType!='solo')&(train.matchType!='duo')&(train.matchType!='squad')&(train.matchType!='solo-fpp')&(train.matchType!='duo-fpp')&(train.matchType!='squad-fpp'),'matchType']='other' train['matchType']=train['matchType'].map({'solo':0 , 'duo':1, 'squad':2, 'solo-fpp...
final_test['IsMinor']=np.where(final_test['Age']<=16, 1, 0 )
Titanic - Machine Learning from Disaster
8,698,078
train.isnull().sum()<count_missing_values>
cols=["Age", "Fare", "TravelAlone", "Pclass_1", "Pclass_2","Embarked_C","Embarked_S","Sex_male","IsMinor"] X=df_final[cols] Y=df_final['Survived']
Titanic - Machine Learning from Disaster
8,698,078
train.isnull().sum()<data_type_conversions>
cols2=["Age", "Pclass_1", "Pclass_2","Embarked_C","Embarked_S","Sex_male"] X2=df_final[cols2] Y=df_final['Survived'] logit_model=sm.Logit(Y,X2) result=logit_model.fit() sys.stdout.write(GREEN) print(result.summary() )
Titanic - Machine Learning from Disaster
8,698,078
train.dropna(inplace=True) train.isnull().sum()<categorify>
logreg = LogisticRegression() logreg.fit(X2, Y) print("Model Accuracy : {:.2f}%".format(logreg.score(X2, Y)*100))
Titanic - Machine Learning from Disaster
8,698,078
data=enc.fit(train[['matchType']]) temp=enc.transform(train[['matchType']] )<create_dataframe>
train, test = train_test_split(df_final, test_size=0.25 )
Titanic - Machine Learning from Disaster
8,698,078
temp1=pd.DataFrame(temp.toarray() ,columns=["solo", "duo", "squad", "solo-fpp", "duo-fpp", "squad-fpp","other"]) temp1=temp1.set_index(train.index.values) temp1 train=pd.concat([train,temp1],axis=1) <drop_column>
cols2=["Age", "Pclass_1", "Pclass_2","Embarked_C","Embarked_S","Sex_male"] X3=train[cols2] Y3=train['Survived'] logit_model3=sm.Logit(Y3,X3 )
Titanic - Machine Learning from Disaster
8,698,078
train['killsasist']=train['kills']+train['assists']+train['roadKills'] train['total_distance']=train['swimDistance']+train['rideDistance']+train['walkDistance'] train['external_booster']=train['boosts']+train['weaponsAcquired']+train['heals'] train=train.drop(['assists','kills','swimDistance','rideDistance','walkDistan...
logreg = LogisticRegression() logreg.fit(X3, Y3) sys.stdout.write(GREEN) print("Model Accuracy : {:.2f}%".format(logreg.score(X3, Y3)*100))
Titanic - Machine Learning from Disaster
8,698,078
train=train.drop(['killPoints','maxPlace','winPoints'],axis=1 )<categorify>
logreg.fit(X3, Y3) X3_test = test[cols2] Y3_test = test['Survived'] Y3test_pred = logreg.predict(X3_test) sys.stdout.write(GREEN) print('Accuracy of logistic regression classifier on test set: {:.2f}'.format(logreg.score(X3_test, Y3_test)*100))
Titanic - Machine Learning from Disaster
8,698,078
train['Players_all']=train.groupby('matchId')['Id'].transform('count') train['players_group']=train.groupby('groupId')['Id'].transform('count' )<prepare_x_and_y>
logreg.fit(X3, Y3) Y3_pred = logreg.predict(X3) y_true = Y3 y_scores = Y3_pred sys.stdout.write(GREEN) print("Model ROC_AUC : {:.2f}%".format(roc_auc_score(y_true, y_scores)) )
Titanic - Machine Learning from Disaster
8,698,078
Y=train.winPlacePerc train = train.drop(["Id", "groupId", "matchId","winPlacePerc"], axis=1) del train['matchType'] train.head()<split>
cols=["Age", "Fare", "TravelAlone", "Pclass_1", "Pclass_2","Embarked_C","Embarked_S","Sex_male","IsMinor"] X=df_final[cols] Y=df_final['Survived'] random_forest = RandomForestClassifier(n_estimators=100) random_forest.fit(X, Y) sys.stdout.write(GREEN) print('ROC AUC: %0.3f' % random_forest.score(X, Y))
Titanic - Machine Learning from Disaster
8,698,078
<import_modules>
final_test_RF=final_test[cols] Y_pred_RF = random_forest.predict(final_test_RF )
Titanic - Machine Learning from Disaster
8,698,078
<train_model>
submission = pd.DataFrame({ "PassengerId": test_df["PassengerId"], "Survived": Y_pred_RF }) submission.to_csv('titanic_RF.csv', index=False )
Titanic - Machine Learning from Disaster
8,698,078
d_train = lgb.Dataset(train, label=Y) params = {} params['learning_rate'] = 0.05 params['boosting_type'] = 'gbdt' params['objective'] = 'regression' params['metric'] = 'mae' params['sub_feature'] = 0.9 params['num_leaves'] = 511 params['min_data'] = 1 params['max_depth'] = 30 params['min_gain_to_split']= 0.00001 clf =...
tree1 = tree.DecisionTreeClassifier(criterion='gini', splitter='best',max_depth=3, min_samples_leaf=20 )
Titanic - Machine Learning from Disaster