kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
4,851,629
def woe(X, y): tmp = pd.DataFrame() tmp["variable"] = X tmp["target"] = y var_counts = tmp.groupby("variable")["target"].count() var_events = tmp.groupby("variable")["target"].sum() var_nonevents = var_counts - var_events tmp["var_counts"] = tmp.variable.map(var_counts) tmp["var_events"] = tmp.variable.map(var_events)...
print('Area Under Curve: {}, Accuracy: {}'.format(dt_auc, dt_acc))
Titanic - Machine Learning from Disaster
4,851,629
iv_values = [] feats = ["var_{}".format(i)for i in range(200)] y = train["target"] for f in feats: X = pd.qcut(train[f], 10, duplicates='drop') _, _, iv = woe(X, y) iv_values.append(iv) iv_inds = np.argsort(iv_values)[::-1][:50] iv_values = np.array(iv_values)[iv_inds] feats = np.array(feats)[iv_inds] <import_modul...
rf = ens.RandomForestClassifier()
Titanic - Machine Learning from Disaster
4,851,629
from sklearn.linear_model import LogisticRegression from sklearn.model_selection import StratifiedKFold, cross_val_predict from sklearn.metrics import roc_auc_score from sklearn.preprocessing import StandardScaler<find_best_model_class>
threshold = np.arange(1, 10, 0.5)*1e-1
Titanic - Machine Learning from Disaster
4,851,629
feats = ["var_{}".format(i)for i in range(200)] X = train[feats] X_test = test[feats] y = train["target"] cvlist = list(StratifiedKFold(5, random_state=12345786 ).split(X, y)) scaler = StandardScaler() X_sc = scaler.fit_transform(X) X_test_sc = scaler.fit_transform(X_test) lr = LogisticRegression() y_preds_lr = cross...
scores = [] for i in threshold: selector = sklearn.feature_selection.VarianceThreshold(threshold= i) selected_features = selector.fit_transform(features) rf.fit(selected_features, target) y_pred = rf.predict(features.loc[:, selector.get_support() ]) scores.append(sklearn.metrics.accuracy_score(target, y_pred)) plt....
Titanic - Machine Learning from Disaster
4,851,629
import lightgbm as lgb <import_modules>
print('The highest accuracy score is obtained after execluding features whose variance is less than: ', np.round(threshold[np.argmax(np.array(scores)) ],3))
Titanic - Machine Learning from Disaster
4,851,629
from scipy.stats import gmean<define_search_space>
print('The highest accuracy score is:', np.max(np.array(scores)) )
Titanic - Machine Learning from Disaster
4,851,629
np.mean([0.9, 0.9, 0.9, 0.98, 0.9] )<define_search_space>
number_of_features = list(range(1,13))
Titanic - Machine Learning from Disaster
4,851,629
gmean([0.9, 0.9, 0.9, 0.98, 0.9] )<install_modules>
print("Maximum accuracy score is :", max(scores_k))
Titanic - Machine Learning from Disaster
4,851,629
!pip install -U lightgbm<train_model>
print("Optimal number of features :", np.argmax(np.array(scores_k)) + 1 )
Titanic - Machine Learning from Disaster
4,851,629
model = lgb.LGBMClassifier(boosting_type='gbdt', n_estimators=200000, learning_rate=0.02, num_leaves=2, subsample=0.4, colsample_bytree=0.4, seed=1) y_preds_lgb = np.zeros(( len(y))) test_preds_allfolds = [] for i,(tr_idx, val_idx)in enumerate(cvlist): X_dev, y_dev = X.iloc[tr_idx], y.iloc[tr_idx] X_val, y_val = X.il...
print("Optimal number of features : %d" % selector.n_features_ )
Titanic - Machine Learning from Disaster
4,851,629
sub = test[["ID_code"]] sub["target"] = y_test_preds_lgb sub.to_csv("submission_lgbm2_v1.csv", index=False )<compute_test_metric>
print("Maximum accuracy score is :", np.max(selector.grid_scores_))
Titanic - Machine Learning from Disaster
4,851,629
weighted_preds = y_preds_lr* 0.05 + y_preds_lgb * 0.95 weighted_test_preds = y_test_preds_lr* 0.05 + y_test_preds_lgb * 0.95 roc_auc_score(y, weighted_preds )<load_from_csv>
threshold = [0.001, 0.0025, 0.005, 0.01, 0.025 ,0.05, 0.1, 0.15]
Titanic - Machine Learning from Disaster
4,851,629
public_sub = pd.read_csv(".. /input/santander-lgb-new-features-rank-mean-10-folds/submission_LGBM.csv") public_sub.head()<prepare_output>
print("Maximum accuracy score is :", np.max(np.array(scores_sfm)) )
Titanic - Machine Learning from Disaster
4,851,629
sub["target"] = weighted_test_preds<save_to_csv>
print("Optimal threshold :", threshold[np.argmax(np.array(scores_sfm)) ] )
Titanic - Machine Learning from Disaster
4,851,629
sub["target"] = 0.2*sub["target"].rank() + 0.8*public_sub["target"] sub.to_csv("submission_blend.csv", index=False )<train_model>
rf_params = {'n_estimators': [200, 300, 400], 'criterion': ['gini'], 'min_samples_split': [ 22, 20, 25], 'max_features': ['auto', 'log2', None], 'class_weight': [{0: 0.6, 1: 0.4}, {0: 0.6, 1: 0.4}, {0: 0.5, 1: 0.5}]}
Titanic - Machine Learning from Disaster
4,851,629
concatenate, GaussianNoise, Reshape, TimeDistributed, LeakyReLU, PReLU, Embedding) class ROC_AUC(Callback): def __init__(self, validation_data): self.X_val, self.y_val = validation_data def on_epoch_end(self, epoch, logs={}): print("ROC AUC for this fold, is ", roc_auc_score(self.y_val, self.model.predict(X_val))) cl...
rs_rf = RandomizedSearchCV(rf, param_distributions= rf_params, scoring='accuracy', cv= StratifiedKFold(7), refit=True, n_iter= 200 )
Titanic - Machine Learning from Disaster
4,851,629
model = NNv1(opt_kwargs = {"lr": 0.01, "momentum": 0.9, "nesterov": True, "clipnorm": 1}) y_preds_nn = np.zeros(( len(y))) for tr_idx, val_idx in cvlist: X_dev, y_dev = X_sc[tr_idx], y.iloc[tr_idx] X_val, y_val = X_sc[val_idx], y.iloc[val_idx] roc_auc = ROC_AUC(( X_val, y_val)) model.fit(X_dev, y_dev, validation_data...
rs_rf.fit(x_train, y_train )
Titanic - Machine Learning from Disaster
4,851,629
roc_auc_score(y, y_preds_nn )<load_from_csv>
print('Best Parameters are: ', rs_rf.best_params_, ' Training accuracy score is: ', rs_rf.best_score_ )
Titanic - Machine Learning from Disaster
4,851,629
train = pd.read_csv('.. /input/siim-isic-melanoma-classification/train.csv') print('Examples WITH Melanoma') imgs = train.loc[train.target==1].sample(10 ).image_name.values plt.figure(figsize=(20,8)) for i,k in enumerate(imgs): img = cv2.imread('.. /input/jpeg-melanoma-128x128/train/%s.jpg'%k) img = cv2.cvtColor(img...
print('Validation accuracy score is: ', rs_rf.score(x_valid, y_valid))
Titanic - Machine Learning from Disaster
4,851,629
!pip install -q efficientnet >> /dev/null<import_modules>
param_name = 'max_depth' param_range = np.arange(1, 31) train_score, valid_score = [], [] for depth in param_range: rf = ens.RandomForestClassifier(n_estimators= 300, criterion='gini', max_features= 'auto', min_samples_split=22, class_weight= {0: 0.5, 1: 0.5},max_depth= depth) rf.fit(x_train, y_train) train_score.ap...
Titanic - Machine Learning from Disaster
4,851,629
import pandas as pd, numpy as np from kaggle_datasets import KaggleDatasets import tensorflow as tf, re, math import tensorflow.keras.backend as K import efficientnet.tfkeras as efn from sklearn.model_selection import KFold from sklearn.metrics import roc_auc_score import matplotlib.pyplot as plt<define_variables>
rf = ens.RandomForestClassifier(n_estimators= 300, criterion='gini', max_features= 'auto', min_samples_split=22, class_weight= {0: 0.5, 1: 0.5}, max_depth= 6) rf.fit(features,target )
Titanic - Machine Learning from Disaster
4,851,629
DEVICE = "TPU" SEED = 42 FOLDS = 5 IMG_SIZES = [384,384,384,384,384] INC2019 = [0,0,0,0,0] INC2018 = [1,1,1,1,1] BATCH_SIZES = [32]*FOLDS EPOCHS = [12]*FOLDS EFF_NETS = [6,6,6,6,6] WGTS = [1/FOLDS]*FOLDS TTA = 11<choose_model_class>
y_scores_rf = rf.predict_proba(x_test)[:, 1] rf_fpr, rf_tpr, rf_thresholds = sklearn.metrics.roc_curve(y_test, y_scores_rf) rf_auc = sklearn.metrics.auc(x=rf_fpr, y=rf_tpr )
Titanic - Machine Learning from Disaster
4,851,629
if DEVICE == "TPU": print("connecting to TPU...") try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() print('Running on TPU ', tpu.master()) except ValueError: print("Could not connect to TPU") tpu = None if tpu: try: print("initializing TPU...") tf.config.experimental_connect_to_cluster(tpu) tf.tpu.exp...
rf_acc = rf.score(x_test, y_test )
Titanic - Machine Learning from Disaster
4,851,629
GCS_PATH = [None]*FOLDS; GCS_PATH2 = [None]*FOLDS for i,k in enumerate(IMG_SIZES): GCS_PATH[i] = KaggleDatasets().get_gcs_path('melanoma-%ix%i'%(k,k)) GCS_PATH2[i] = KaggleDatasets().get_gcs_path('isic2019-%ix%i'%(k,k)) files_train = np.sort(np.array(tf.io.gfile.glob(GCS_PATH[0] + '/train*.tfrec'))) files_test = np.so...
print('Area Under Curve: {}, Accuracy: {}'.format(rf_auc, rf_acc))
Titanic - Machine Learning from Disaster
4,851,629
ROT_ = 180.0 SHR_ = 2.0 HZOOM_ = 8.0 WZOOM_ = 8.0 HSHIFT_ = 8.0 WSHIFT_ = 8.0<normalization>
bg = ens.BaggingClassifier()
Titanic - Machine Learning from Disaster
4,851,629
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift): rotation = math.pi * rotation / 180. shear = math.pi * shear / 180. def get_3x3_mat(lst): return tf.reshape(tf.concat([lst],axis=0), [3,3]) c1 = tf.math.cos(rotation) s1 = tf.math.sin(rotation) one = tf.constant([1],dtype='float32') ...
threshold = np.arange(1, 10, 0.5)*1e-1
Titanic - Machine Learning from Disaster
4,851,629
def read_labeled_tfrecord(example): tfrec_format = { 'image' : tf.io.FixedLenFeature([], tf.string), 'image_name' : tf.io.FixedLenFeature([], tf.string), 'patient_id' : tf.io.FixedLenFeature([], tf.int64), 'sex' : tf.io.FixedLenFeature([], tf.int64), 'age_approx' : tf.io.FixedLenFeature([], tf.int64), 'anatom_site_gene...
scores = [] for i in threshold: selector = sklearn.feature_selection.VarianceThreshold(threshold= i) selected_features = selector.fit_transform(features) bg.fit(selected_features, target) y_pred = bg.predict(features.loc[:, selector.get_support() ]) scores.append(sklearn.metrics.accuracy_score(target, y_pred)) plt....
Titanic - Machine Learning from Disaster
4,851,629
def get_dataset(files, augment = False, shuffle = False, repeat = False, labeled=True, return_image_names=True, batch_size=16, dim=256): ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO) ds = ds.cache() if repeat: ds = ds.repeat() if shuffle: ds = ds.shuffle(1024*8) opt = tf.data.Options() opt.experimental...
print('The highest accuracy score is obtained after execluding features whose variance is less than: ', np.round(threshold[np.argmax(np.array(scores)) ],3))
Titanic - Machine Learning from Disaster
4,851,629
EFNS = [efn.EfficientNetB0, efn.EfficientNetB1, efn.EfficientNetB2, efn.EfficientNetB3, efn.EfficientNetB4, efn.EfficientNetB5, efn.EfficientNetB6] def build_model(dim=128, ef=0): inp = tf.keras.layers.Input(shape=(dim,dim,3)) base = EFNS[ef](input_shape=(dim,dim,3),weights='imagenet',include_top=False) x = base(inp) ...
print('The highest accuracy score is:', np.max(np.array(scores)) )
Titanic - Machine Learning from Disaster
4,851,629
def get_lr_callback(batch_size=8): lr_start = 0.000005 lr_max = 0.00000125 * REPLICAS * batch_size lr_min = 0.000001 lr_ramp_ep = 5 lr_sus_ep = 0 lr_decay = 0.8 def lrfn(epoch): if epoch < lr_ramp_ep: lr =(lr_max - lr_start)/ lr_ramp_ep * epoch + lr_start elif epoch < lr_ramp_ep + lr_sus_ep: lr = lr_max else: lr =(lr_m...
number_of_features = list(range(1,13))
Titanic - Machine Learning from Disaster
4,851,629
VERBOSE = 0 DISPLAY_PLOT = True skf = KFold(n_splits=FOLDS,shuffle=True,random_state=SEED) oof_pred = []; oof_tar = []; oof_val = []; oof_names = []; oof_folds = [] preds = np.zeros(( count_data_items(files_test),1)) for fold,(idxT,idxV)in enumerate(skf.split(np.arange(15))): if DEVICE=='TPU': if tpu: tf.tpu.experimen...
print("Maximum accuracy score is :", max(scores_k))
Titanic - Machine Learning from Disaster
4,851,629
oof = np.concatenate(oof_pred); true = np.concatenate(oof_tar); names = np.concatenate(oof_names); folds = np.concatenate(oof_folds) auc = roc_auc_score(true,oof) print('Overall OOF AUC with TTA = %.3f'%auc) df_oof = pd.DataFrame(dict( image_name = names, target=true, pred = oof, fold=folds)) df_oof.to_csv('oof.csv...
print("Optimal number of features :", np.argmax(np.array(scores_k)) + 1 )
Titanic - Machine Learning from Disaster
4,851,629
ds = get_dataset(files_test, augment=False, repeat=False, dim=IMG_SIZES[fold], labeled=False, return_image_names=True) image_names = np.array([img_name.numpy().decode("utf-8") for img, img_name in iter(ds.unbatch())] )<save_to_csv>
bg_params = {'n_estimators': [20, 25, 100], 'base_estimator': [ None, svm], 'max_features': [0.6, 0.7, 0.8], 'oob_score' : [True, False], 'max_samples': [0.6,0.7,0.8]}
Titanic - Machine Learning from Disaster
4,851,629
submission = pd.DataFrame(dict(image_name=image_names, target=preds[:,0])) submission = submission.sort_values('image_name') submission.to_csv('submission.csv', index=False) submission.head()<install_modules>
rs_bg = RandomizedSearchCV(bg, param_distributions= bg_params, scoring='accuracy', cv=StratifiedKFold(7), n_iter= 2000,refit=True )
Titanic - Machine Learning from Disaster
4,851,629
!pip install tensorflow~=2.2.0 tensorflow_gcs_config~=2.2.0<install_modules>
rs_bg.fit(x_train, y_train )
Titanic - Machine Learning from Disaster
4,851,629
!pip install -q efficientnet !pip install pandas_summary !pip install tensorflow-addons<import_modules>
print('Best Parameters are: ', rs_bg.best_params_, ' Training accuracy score is: ', rs_bg.best_score_ )
Titanic - Machine Learning from Disaster
4,851,629
import os import re import numpy as np import pandas as pd import random import math import matplotlib.pyplot as plt from sklearn import metrics from sklearn.model_selection import KFold, StratifiedKFold import tensorflow as tf from kaggle_datasets import KaggleDatasets import efficientnet.tfkeras as efn from tensorflo...
print('Validation accuracy score is: ', rs_bg.score(x_valid, y_valid))
Titanic - Machine Learning from Disaster
4,851,629
def seed_all(seed): random.seed(seed) np.random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) os.environ['TF_DETERMINISTIC_OPS'] = str(seed) os.environ['TF_KERAS'] = str(seed) tf.random.set_seed(seed) seed_all(42 )<train_on_grid>
bg = ens.BaggingClassifier(n_estimators= 25, max_features= 0.8, base_estimator= svm, oob_score= True, max_samples= 0.8) bg.fit(features,target )
Titanic - Machine Learning from Disaster
4,851,629
DEVICE = 'TPU' MIXED_PRECISION = True XLA_ACCELERATE = True if DEVICE == 'TPU': print('Connecting to TPU...') try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() print('Running on TPU ', tpu.master()) except ValueError: print('Could not connect to TPU') tpu = None if tpu: try: print('initializing TPU...')...
y_scores_bg = bg.predict_proba(x_test)[:, 1] bg_fpr, bg_tpr, bg_thresholds = sklearn.metrics.roc_curve(y_test, y_scores_bg) bg_auc = sklearn.metrics.auc(x=bg_fpr, y=bg_tpr )
Titanic - Machine Learning from Disaster
4,851,629
CFG = dict( epochs = 30, batch_size = 128, lr = 0.00032, inp_size = 256, eff_B = 0, sprinkles_mode = 'normal', sprinkles_prob = 1, num_holes = 5, side_length = 256//10 ) <load_from_csv>
bg_acc = bg.score(x_test, y_test )
Titanic - Machine Learning from Disaster
4,851,629
BASEPATH = '.. /input/siim-isic-melanoma-classification' df_train = pd.read_csv(os.path.join(BASEPATH, 'train.csv')) df_test = pd.read_csv(os.path.join(BASEPATH, 'test.csv')) df_sub = pd.read_csv(os.path.join(BASEPATH, 'sample_submission.csv')) GCS_PATH = KaggleDatasets().get_gcs_path('melanoma-%ix%i'%(CFG['inp_size'],...
print('Area Under Curve: {}, Accuracy: {}'.format(bg_auc, bg_acc))
Titanic - Machine Learning from Disaster
4,851,629
def make_mask(num_holes,side_length,rows, cols, num_channels): row_range = tf.tile(tf.range(rows)[..., tf.newaxis], [1, num_holes]) col_range = tf.tile(tf.range(cols)[..., tf.newaxis], [1, num_holes]) r_idx = tf.random.uniform([num_holes], minval=0, maxval=rows-1, dtype=tf.int32) c_idx = tf.random.uniform([num_hol...
ada = ens.AdaBoostClassifier()
Titanic - Machine Learning from Disaster
4,851,629
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift): rotation = math.pi * rotation / 180. shear = math.pi * shear / 180. def get_3x3_mat(lst): return tf.reshape(tf.concat([lst],axis=0), [3,3]) c1 = tf.math.cos(rotation) s1 = tf.math.sin(rotation) one = tf.constant([1],dtype='float32') ...
threshold = np.arange(1, 10, 0.5)*1e-1
Titanic - Machine Learning from Disaster
4,851,629
def transform(image, label): DIM = CFG['inp_size'] XDIM = DIM%2 if 0.5 > tf.random.uniform([1], minval = 0, maxval = 1): rot = 15.* tf.random.normal([1],dtype='float32') else: rot = 180.* tf.random.normal([1],dtype='float32') shr = 5.* tf.random.normal([1],dtype='float32') h_zoom = 1.0 + tf.random.normal([1],dtype='...
scores = [] for i in threshold: selector = sklearn.feature_selection.VarianceThreshold(threshold= i) selected_features = selector.fit_transform(features) ada.fit(selected_features, target) y_pred = ada.predict(features.loc[:, selector.get_support() ]) scores.append(sklearn.metrics.accuracy_score(target, y_pred)) pl...
Titanic - Machine Learning from Disaster
4,851,629
def decode_image(image_data): image = tf.image.decode_jpeg(image_data, channels=3) image = tf.cast(image, tf.float32)/ 255.0 image = tf.reshape(image, [CFG['inp_size'], CFG['inp_size'], 3]) return image<normalization>
print('The highest accuracy score is obtained after execluding features whose variance is less than: ', np.round(threshold[np.argmax(np.array(scores)) ],3))
Titanic - Machine Learning from Disaster
4,851,629
def data_augment(data, label): data['img_inp'] = tf.image.random_flip_left_right(data['img_inp']) data['img_inp'] = tf.image.random_flip_up_down(data['img_inp']) data['img_inp'] = tf.image.random_hue(data['img_inp'], 0.01) data['img_inp'] = tf.image.random_saturation(data['img_inp'], 0.7, 1.3) data['img_inp'] = tf....
print('The highest accuracy score is:', np.max(np.array(scores)) )
Titanic - Machine Learning from Disaster
4,851,629
def read_labeled_tfrecord(example): LABELED_TFREC_FORMAT = { 'image': tf.io.FixedLenFeature([], tf.string), 'target': tf.io.FixedLenFeature([], tf.int64), 'age_approx': tf.io.FixedLenFeature([], tf.int64), 'sex': tf.io.FixedLenFeature([], tf.int64), 'anatom_site_general_challenge': tf.io.FixedLenFeature([], tf.int64)...
number_of_features = list(range(1,13))
Titanic - Machine Learning from Disaster
4,851,629
def read_unlabeled_tfrecord(example): UNLABELED_TFREC_FORMAT = { 'image': tf.io.FixedLenFeature([], tf.string), 'image_name': tf.io.FixedLenFeature([], tf.string), 'age_approx': tf.io.FixedLenFeature([], tf.int64), 'sex': tf.io.FixedLenFeature([], tf.int64), 'anatom_site_general_challenge': tf.io.FixedLenFeature([], ...
print("Maximum accuracy score is :", max(scores_k))
Titanic - Machine Learning from Disaster
4,851,629
def read_complete_tfrecord(example): LABELED_TFREC_FORMAT = { 'image': tf.io.FixedLenFeature([], tf.string), 'image_name': tf.io.FixedLenFeature([], tf.string), 'target': tf.io.FixedLenFeature([], tf.int64), 'age_approx': tf.io.FixedLenFeature([], tf.int64), 'sex': tf.io.FixedLenFeature([], tf.int64), 'anatom_site_ge...
print("Optimal number of features :", np.argmax(np.array(scores_k)) + 1 )
Titanic - Machine Learning from Disaster
4,851,629
def load_dataset(filenames, labeled = True, ordered = False): ignore_order = tf.data.Options() if not ordered: ignore_order.experimental_deterministic = False dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads = AUTO) dataset = dataset.with_options(ignore_order) dataset = dataset.map(read_labeled_tfrecor...
print("Optimal number of features : %d" % selector.n_features_ )
Titanic - Machine Learning from Disaster
4,851,629
def training_input(image, label, data): anatom = [tf.cast(data['anatom_site_general_challenge'][i], dtype = tf.float32)for i in range(7)] tab_data = [tf.cast(data[tfeat], dtype = tf.float32)for tfeat in ['age_approx', 'sex']] tabular = tf.stack(tab_data + anatom) return {'img_inp': image, 'meta_inp': tabular}, label...
print("Maximum accuracy score is :", np.max(selector.grid_scores_))
Titanic - Machine Learning from Disaster
4,851,629
def test_input(image, image_name, data): anatom = [tf.cast(data['anatom_site_general_challenge'][i], dtype = tf.float32)for i in range(7)] tab_data = [tf.cast(data[tfeat], dtype = tf.float32)for tfeat in ['age_approx', 'sex']] tabular = tf.stack(tab_data + anatom) return {'img_inp': image, 'meta_inp': tabular}, imag...
threshold = [0.001, 0.0025, 0.005, 0.01, 0.025 ,0.05, 0.1, 0.15]
Titanic - Machine Learning from Disaster
4,851,629
def validation_input(image, image_name, target, data): anatom = [tf.cast(data['anatom_site_general_challenge'][i], dtype = tf.float32)for i in range(7)] tab_data = [tf.cast(data[tfeat], dtype = tf.float32)for tfeat in ['age_approx', 'sex']] tabular = tf.stack(tab_data + anatom) return {'img_inp': image, 'meta_inp': ...
print("Maximum accuracy score is :", np.max(np.array(scores_sfm)) )
Titanic - Machine Learning from Disaster
4,851,629
def get_training_dataset(filenames, labeled = True, ordered = False): dataset = load_dataset(filenames, labeled = labeled, ordered = ordered) dataset = dataset.map(training_input, num_parallel_calls = AUTO) dataset = dataset.map(data_augment, num_parallel_calls = AUTO) dataset = dataset.map(transform, num_parallel...
print("Optimal threshold :", threshold[np.argmax(np.array(scores_sfm)) ] )
Titanic - Machine Learning from Disaster
4,851,629
NUM_TRAINING_IMAGES = int(count_data_items(training_files)* 0.8) NUM_VALIDATION_IMAGES = int(count_data_items(training_files)* 0.2) NUM_TEST_IMAGES = count_data_items(test_files) STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // CFG['batch_size'] print('Dataset: {} training images, {} validation images, {} unlabeled test ima...
ada_params = {'n_estimators': [90, 100, 110], 'base_estimator': [None, svm], 'learning_rate': [0.09 ,0.1, 0.11]}
Titanic - Machine Learning from Disaster
4,851,629
class IncreaseSprinklesHoles(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs={}): if epoch <= 10: CFG['num_holes'] = epoch + 5 CFG['side_length'] =(CFG['inp_size'] // 10)+(epoch // 2) if epoch >= 10: CFG['num_holes'] = epoch + 5 CFG['side_length'] =(CFG['inp_size'] // 5)+(epoch // 2) if epoch >= 15...
rs_ada = RandomizedSearchCV(ada, param_distributions= ada_params, scoring='accuracy', cv= StratifiedKFold(7), refit=True, n_iter= 500 )
Titanic - Machine Learning from Disaster
4,851,629
def get_model() : with strategy.scope() : img_inp = tf.keras.layers.Input(shape =(CFG['inp_size'], CFG['inp_size'], 3), name = 'img_inp') meta_inp = tf.keras.layers.Input(shape =(9), name = 'meta_inp') effs = [0,1,2,3,4,5,6,7] eff = effs[CFG['eff_B']] constructor = getattr(efn, f'EfficientNetB{eff}') efnetb = cons...
rs_ada.fit(x_train, y_train )
Titanic - Machine Learning from Disaster
4,851,629
roc_auc = metrics.roc_auc_score(oof_target, oof_prediction) print('Final OOF Roc Auc Score: ', roc_auc )<load_from_csv>
print('Best Parameters are: ', rs_ada.best_params_, ' Training accuracy score is: ', rs_ada.best_score_ )
Titanic - Machine Learning from Disaster
4,851,629
treino = pd.read_csv('/kaggle/input/riiid-test-answer-prediction/train.csv', usecols=[1, 2, 3, 4, 7, 8, 9], dtype={'timestamp': 'int64', 'user_id': 'int32', 'content_id': 'int16', 'content_type_id': 'int8', 'answered_correctly':'int8', 'prior_question_elapsed_time': 'float32', 'prior_question_had_explanation': 'boolean...
print('Validation accuracy score is: ', rs_ada.score(x_valid, y_valid))
Titanic - Machine Learning from Disaster
4,851,629
questions_df = pd.read_csv('/kaggle/input/riiid-test-answer-prediction/questions.csv', usecols=[0, 3], dtype={'question_id': 'int16', 'part': 'int8'} )<count_values>
ada = ens.AdaBoostClassifier(n_estimators= 110, learning_rate= 0.09) ada.fit(features, target )
Titanic - Machine Learning from Disaster
4,851,629
print(f'Number of Rows: {train_df.shape[0]}') print(f'Number of Cols: {train_df.shape[1]}' )<data_type_conversions>
y_scores_ada = ada.predict_proba(x_test)[:, 1] ada_fpr, ada_tpr, ada_thresholds = sklearn.metrics.roc_curve(y_test, y_scores_ada) ada_auc = sklearn.metrics.auc(x=ada_fpr, y=ada_tpr )
Titanic - Machine Learning from Disaster
4,851,629
train_df = train_df.astype(data_types_dict )<count_missing_values>
ada_acc = ada.score(x_test, y_test )
Titanic - Machine Learning from Disaster
4,851,629
train_df.isna().sum()<feature_engineering>
print('Area Under Curve: {}, Accuracy: {}'.format(ada_auc, ada_acc))
Titanic - Machine Learning from Disaster
4,851,629
treino = treino.loc[treino.content_type_id == False] treino['tempo_exercicio'] = pd.DataFrame(treino.prior_question_elapsed_time.shift(-1)) treino.loc[treino.timestamp == 0, ['prior_question_had_explanation']] = treino.loc[treino.timestamp == 0, ['prior_question_had_explanation']].fillna(False) treino = treino.sort_va...
gb = ens.GradientBoostingClassifier()
Titanic - Machine Learning from Disaster
4,851,629
treino = pd.merge(treino, questions_df, left_on = 'content_id', right_on = 'question_id', how = 'left') treino.part = treino.part - 1<drop_column>
threshold = np.arange(1, 10, 0.5)*1e-1
Titanic - Machine Learning from Disaster
4,851,629
treino.drop(['timestamp', 'content_type_id','question_id'], axis=1, inplace=True )<groupby>
scores = [] for i in threshold: selector = sklearn.feature_selection.VarianceThreshold(threshold= i) selected_features = selector.fit_transform(features) gb.fit(selected_features, target) y_pred = gb.predict(features.loc[:, selector.get_support() ]) scores.append(sklearn.metrics.accuracy_score(target, y_pred)) plt....
Titanic - Machine Learning from Disaster
4,851,629
tempo_medio_estudantef = treino[['user_id','tempo_exercicio']].groupby(['user_id'] ).agg(['mean']) tempo_medio_estudantef.columns = ['tempo_medio_estudante'] tempo_medio_exerciciof = treino[['content_id','tempo_exercicio']].groupby(['content_id'] ).agg(['mean']) tempo_medio_exerciciof.columns = ['tempo_medio_exercici...
print('The highest accuracy score is obtained after execluding features whose variance is less than: ', np.round(threshold[np.argmax(np.array(scores)) ],3))
Titanic - Machine Learning from Disaster
4,851,629
validation = pd.DataFrame()<remove_duplicates>
print('The highest accuracy score is:', np.max(np.array(scores)) )
Titanic - Machine Learning from Disaster
4,851,629
for i in range(4): last_records = treino.drop_duplicates('user_id', keep = 'last') treino = treino[~treino.index.isin(last_records.index)] validation = validation.append(last_records) del(last_records )<drop_column>
number_of_features = list(range(1,13))
Titanic - Machine Learning from Disaster
4,851,629
validation.drop(['tempo_exercicio'], axis=1, inplace=True )<create_dataframe>
print("Maximum accuracy score is :", max(scores_k))
Titanic - Machine Learning from Disaster
4,851,629
X = pd.DataFrame() for i in range(15): last_records = treino.drop_duplicates('user_id', keep = 'last') treino = treino[~treino.index.isin(last_records.index)] X = X.append(last_records) del(last_records )<groupby>
print("Optimal number of features :", np.argmax(np.array(scores_k)) + 1 )
Titanic - Machine Learning from Disaster
4,851,629
tempo_medio_estudante = treino[['user_id','tempo_exercicio']].groupby(['user_id'] ).agg(['mean']) tempo_medio_estudante.columns = ['tempo_medio_estudante'] tempo_medio_exercicio = treino[['content_id','tempo_exercicio']].groupby(['content_id'] ).agg(['mean']) tempo_medio_exercicio.columns = ['tempo_medio_exercicio'] ...
print("Optimal number of features : %d" % selector.n_features_ )
Titanic - Machine Learning from Disaster
4,851,629
X = pd.merge(X, acerto_medio_estudante, on=['user_id'], how="left") X = pd.merge(X, tempo_medio_estudante, on=['user_id'], how="left") X = pd.merge(X, acerto_medio_exercicio, on=['content_id'], how="left") X = pd.merge(X, tempo_medio_exercicio, on=['content_id'], how="left") X = pd.merge(X, acerto_medio_tipo_exerci...
print("Maximum accuracy score is :", np.max(selector.grid_scores_))
Titanic - Machine Learning from Disaster
4,851,629
validation = pd.merge(validation, acerto_medio_estudante, on=['user_id'], how="left") validation = pd.merge(validation, tempo_medio_estudante, on=['user_id'], how="left") validation = pd.merge(validation, acerto_medio_exercicio, on=['content_id'], how="left") validation = pd.merge(validation, tempo_medio_exercicio, ...
threshold = [0.001, 0.0025, 0.005, 0.01, 0.025 ,0.05, 0.1, 0.15]
Titanic - Machine Learning from Disaster
4,851,629
lb_make = LabelEncoder() X.prior_question_had_explanation.fillna(False, inplace = True) validation.prior_question_had_explanation.fillna(False, inplace = True) validation["prior_question_had_explanation_enc"] = lb_make.fit_transform(validation["prior_question_had_explanation"]) X["prior_question_had_explanation_enc"...
print("Maximum accuracy score is :", np.max(np.array(scores_sfm)) )
Titanic - Machine Learning from Disaster
4,851,629
X.isna().sum()<prepare_x_and_y>
print("Optimal threshold :", threshold[np.argmax(np.array(scores_sfm)) ] )
Titanic - Machine Learning from Disaster
4,851,629
y = X['answered_correctly'] X = X.drop(['answered_correctly'], axis=1) y_val = validation['answered_correctly'] X_val = validation.drop(['answered_correctly'], axis=1 )<data_type_conversions>
selector = sklearn.feature_selection.SelectKBest(k= 11) selector.fit(features, target) gb_selected_features = selector.get_support()
Titanic - Machine Learning from Disaster
4,851,629
X['acerto_medio_estudante'].fillna(acerto_medio_estudante.acerto_medio_estudante.mean() ,inplace=True) X['acerto_medio_exercicio'].fillna(acerto_medio_exercicio.acerto_medio_exercicio.mean() ,inplace=True) X['tempo_medio_estudante'].fillna(tempo_medio_estudante.tempo_medio_estudante.mean() ,inplace = True) X['tempo_...
gb_params = {'n_estimators': [150, 160, 170], 'loss': ['deviance', 'exponential'], 'subsample': [0.7, 0.8, 0.9], 'max_features': ['auto', 'log2', None]}
Titanic - Machine Learning from Disaster
4,851,629
params = { 'num_leaves': 350, 'max_bin':700, 'min_child_weight': 0.03454472573214212, 'feature_fraction': 0.58, 'bagging_fraction': 0.58, 'objective': 'binary', 'max_depth': -1, 'learning_rate': 0.05, "boosting_type": "gbdt", "bagging_seed": 11, "metric": 'auc', "verbosity": -1, 'reg_alpha': 0.3899927210061127, 'reg_la...
rs_gb = RandomizedSearchCV(gb, param_distributions= gb_params, scoring='accuracy', cv= StratifiedKFold(7), refit=True, n_iter= 2000 )
Titanic - Machine Learning from Disaster
4,851,629
model = lgb.train( params, lgb_train, valid_sets=[lgb_train, lgb_eval], verbose_eval=50, num_boost_round=10000, early_stopping_rounds=12 )<predict_on_test>
rs_gb.fit(x_train.loc[:,gb_selected_features], y_train )
Titanic - Machine Learning from Disaster
4,851,629
y_pred = model.predict(P_val) y_true = np.array(yp_val) y_predc = model.predict(P) y_truec = np.array(yp )<compute_test_metric>
print('Best Parameters are: ', rs_gb.best_params_, ' Training accuracy score is: ', rs_gb.best_score_ )
Titanic - Machine Learning from Disaster
4,851,629
confusion_matrix(y_true, y_pred.round() )<compute_test_metric>
print('Validation accuracy score is: ', rs_gb.score(x_valid.loc[:,gb_selected_features], y_valid))
Titanic - Machine Learning from Disaster
4,851,629
print(roc_auc_score(y_true, y_pred)) print(classification_report(y_true, y_pred.round())) print(roc_auc_score(y_truec, y_predc)) print(classification_report(y_truec, y_predc.round()))<import_modules>
param_name = 'max_depth' param_range = np.arange(1, 31) train_score, valid_score = [], [] for depth in param_range: gb = ens.GradientBoostingClassifier(n_estimators= 170, subsample= 0.9, max_features= 'auto', loss= 'exponential',max_depth= depth) gb.fit(x_train.loc[:,gb_selected_features], y_train) train_score.appen...
Titanic - Machine Learning from Disaster
4,851,629
import matplotlib.pyplot as plt import seaborn as sns<set_options>
gb = ens.GradientBoostingClassifier(n_estimators= 170, subsample= 0.9, max_features= 'auto', loss= 'exponential',max_depth= 4) gb.fit(features.loc[:, gb_selected_features],target )
Titanic - Machine Learning from Disaster
4,851,629
warnings.filterwarnings('ignore' )<import_modules>
y_scores_gb = gb.predict_proba(x_test.loc[:, gb_selected_features])[:, 1] gb_fpr, gb_tpr, gb_thresholds = sklearn.metrics.roc_curve(y_test, y_scores_gb) gb_auc = sklearn.metrics.auc(x=gb_fpr, y=gb_tpr )
Titanic - Machine Learning from Disaster
4,851,629
import pickle import riiideducation from tqdm import tqdm import glob import pandas as pd import numpy as np import plotly.graph_objects as go<define_variables>
gb_acc = gb.score(x_test.loc[:, gb_selected_features], y_test )
Titanic - Machine Learning from Disaster
4,851,629
metrics = [ 'questions_part', 'questions_difficulty', 'questions_count', 'questions_good_answer_reaction_time', 'questions_bad_answer_reaction_time', 'questions_batch_size', 'questions_variance', 'questions_difficulty_given_prev_explanation', 'questions_difficulty_given_prev_no_explanation', 'questions_conditionnal_pro...
print('Area Under Curve: {}, Accuracy: {}'.format(gb_auc, gb_acc))
Titanic - Machine Learning from Disaster
4,851,629
with open('.. /input/lgb-training/model.pkl', 'rb')as f: lgb = pickle.load(f )<load_from_csv>
xgboost = xgb.XGBClassifier()
Titanic - Machine Learning from Disaster
4,851,629
train = pd.read_csv('.. /input/riiid-test-answer-prediction/train.csv', nrows = 1000000, index_col = 0) questions = pd.read_csv('.. /input/riiid-test-answer-prediction/questions.csv') lectures = pd.read_csv('.. /input/riiid-test-answer-prediction/lectures.csv' )<groupby>
threshold = np.arange(1, 10, 0.5)*1e-2
Titanic - Machine Learning from Disaster
4,851,629
questions_to_difficulty =(1-train[train.content_type_id == False].groupby('content_id')['answered_correctly'].mean() )<groupby>
print('The highest accuracy score is obtained after execluding features whose variance is less than: ', np.round(threshold[np.argmax(np.array(scores)) ],3))
Titanic - Machine Learning from Disaster
4,851,629
subtrain = train[train.content_type_id ==0] subtrain['shift_elapse_time'] = subtrain['prior_question_elapsed_time'].shift(-1) good_answer_reaction_time = subtrain[subtrain.answered_correctly==True].dropna().groupby('content_id')['shift_elapse_time'].mean() bad_answer_reaction_time = subtrain[subtrain.answered_correctl...
print('The highest accuracy score is:', np.max(np.array(scores)) )
Titanic - Machine Learning from Disaster
4,851,629
( unique, counts)= np.unique(train.values[:,1], return_counts=True) qids = pd.Series(counts, index = unique ).sort_values(ascending=False)[:500] qids.head()<filter>
number_of_features = list(range(1,13))
Titanic - Machine Learning from Disaster
4,851,629
qids = qids.index<define_variables>
print("Maximum accuracy score is :", max(scores_k))
Titanic - Machine Learning from Disaster
4,851,629
memory = 100 train_arr = train[['user_id', 'content_id', 'content_type_id', 'answered_correctly']].values user_meta = {} user_meta_count = {} meta_proba_pos = {} meta_count_pos = {} meta_proba_neg = {} meta_count_neg = {} for i in tqdm(range(len(train))): user_id, content_id, content_type_id, answered_correctly = train...
print("Optimal number of features :", np.argmax(np.array(scores_k)) + 1 )
Titanic - Machine Learning from Disaster
4,851,629
with open('.. /input/riid-raw-samples/bad_answer_reaction_time', 'rb')as f: bad_answer_reaction_time = pickle.load(f) with open('.. /input/riid-raw-samples/good_answer_reaction_time', 'rb')as f: good_answer_reaction_time = pickle.load(f) with open('.. /input/riid-raw-samples/question_user_count', 'rb')as f: question_...
print("Optimal number of features : %d" % selector.n_features_ )
Titanic - Machine Learning from Disaster
4,851,629
proba_pos = {} proba_neg = {} THRESH_COUNT = 50 THRESH_PROBA = 0.01 for A,v in tqdm(meta_proba.items()): proba_pos[A] = {} proba_neg[A] = {} for B in v.keys() : if meta_count[A][B]>THRESH_COUNT: proba = meta_proba[A][B]/meta_count[A][B] improve = proba -(1-questions_to_difficulty[A]) if improve > THRESH_PROBA: proba_p...
print("Maximum accuracy score is :", np.max(selector.grid_scores_))
Titanic - Machine Learning from Disaster
4,851,629
all_prob = {} for k,v in proba_pos.items() : all_prob[k] = {} for kk,vv in v.items() : all_prob[k][(kk,1)] = vv for k,v in proba_neg.items() : if k not in all_prob.keys() : all_prob[k] = {} for kk,vv in v.items() : all_prob[k][(kk,0)] = vv all_q = set() for k,v in all_prob.items() : for kk in v.keys() : all_q.add(kk[0]...
threshold = [0.001, 0.0025, 0.005, 0.01, 0.025 ,0.05, 0.1, 0.15]
Titanic - Machine Learning from Disaster
4,851,629
mprob = pd.DataFrame(mprob1 ).T mprob.head()<predict_on_test>
print("Maximum accuracy score is :", np.max(np.array(scores_sfm)) )
Titanic - Machine Learning from Disaster
4,851,629
kmean = KMeans(n_clusters=20) c = kmean.fit_predict(mprob )<define_variables>
print("Optimal threshold :", threshold[np.argmax(np.array(scores_sfm)) ] )
Titanic - Machine Learning from Disaster
4,851,629
ids = glob.glob('.. /input/riid-cache-6/content/drive/My Drive/riid/*') ids = [int(elmt.split('/')[-1])for elmt in ids]<categorify>
xgboost = xgb.XGBClassifier() xgboost.fit(features, target )
Titanic - Machine Learning from Disaster