kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
13,636,756
ts = time.time() group = matrix.groupby(['date_block_num', 'item_category_id'] ).agg({'item_cnt_month': ['mean']}) group.columns = [ 'date_cat_avg_item_cnt' ] group.reset_index(inplace=True) matrix = pd.merge(matrix, group, on=['date_block_num','item_category_id'], how='left') matrix['date_cat_avg_item_cnt'] = matri...
train = data[:len(train_data)] X_train = train.drop(labels = "Survived", axis=1) y_train = train["Survived"] X_train, X_test, y_train, y_test = train_test_split(X_train, y_train, test_size=0.3, random_state=42)
Titanic - Machine Learning from Disaster
13,636,756
ts = time.time() group = matrix.groupby(['date_block_num', 'shop_id', 'item_category_id'] ).agg({'item_cnt_month': ['mean']}) group.columns = ['date_shop_cat_avg_item_cnt'] group.reset_index(inplace=True) matrix = pd.merge(matrix, group, on=['date_block_num', 'shop_id', 'item_category_id'], how='left') matrix['date_...
log_reg = LogisticRegression(random_state=42) log_reg.fit(X_train, y_train) print("Accuracy: ", log_reg.score(X_test,y_test))
Titanic - Machine Learning from Disaster
13,636,756
ts = time.time() group = matrix.groupby(['date_block_num', 'shop_id', 'type_code'] ).agg({'item_cnt_month': ['mean']}) group.columns = ['date_shop_type_avg_item_cnt'] group.reset_index(inplace=True) matrix = pd.merge(matrix, group, on=['date_block_num', 'shop_id', 'type_code'], how='left') matrix['date_shop_type_avg...
rf_reg = RandomForestClassifier(random_state=42) rf_reg.fit(X_train, y_train) print("Accuracy: ", rf_reg.score(X_test,y_test))
Titanic - Machine Learning from Disaster
13,636,756
ts = time.time() group = matrix.groupby(['date_block_num', 'shop_id', 'subtype_code'] ).agg({'item_cnt_month': ['mean']}) group.columns = ['date_shop_subtype_avg_item_cnt'] group.reset_index(inplace=True) matrix = pd.merge(matrix, group, on=['date_block_num', 'shop_id', 'subtype_code'], how='left') matrix['date_shop...
svm_clsf = SVC() svm_clsf.fit(X_train, y_train) print("Accuracy: ", svm_clsf.score(X_test,y_test))
Titanic - Machine Learning from Disaster
13,636,756
ts = time.time() group = matrix.groupby(['date_block_num', 'city_code'] ).agg({'item_cnt_month': ['mean']}) group.columns = [ 'date_city_avg_item_cnt' ] group.reset_index(inplace=True) matrix = pd.merge(matrix, group, on=['date_block_num', 'city_code'], how='left') matrix['date_city_avg_item_cnt'] = matrix['date_cit...
best_knn = [] for n in range(1,12): knn = KNeighborsClassifier(n_neighbors=n) knn.fit(X_train, y_train) best_knn.insert(n, knn.score(X_test,y_test)) best_knn
Titanic - Machine Learning from Disaster
13,636,756
ts = time.time() group = matrix.groupby(['date_block_num', 'item_id', 'city_code'] ).agg({'item_cnt_month': ['mean']}) group.columns = [ 'date_item_city_avg_item_cnt' ] group.reset_index(inplace=True) matrix = pd.merge(matrix, group, on=['date_block_num', 'item_id', 'city_code'], how='left') matrix['date_item_city_a...
knn_clsf = KNeighborsClassifier(n_neighbors=8) knn_clsf.fit(X_train, y_train) print("Accuracy: ", knn_clsf.score(X_test,y_test))
Titanic - Machine Learning from Disaster
13,636,756
ts = time.time() group = matrix.groupby(['date_block_num', 'type_code'] ).agg({'item_cnt_month': ['mean']}) group.columns = [ 'date_type_avg_item_cnt' ] group.reset_index(inplace=True) matrix = pd.merge(matrix, group, on=['date_block_num', 'type_code'], how='left') matrix['date_type_avg_item_cnt'] = matrix['date_typ...
voting_classfication = VotingClassifier(estimators = [('knn', knn_clsf),('lg', log_reg),('rfg', rf_reg),('svc', svm_clsf)], voting="hard", n_jobs=-1) voting_classfication.fit(X_train, y_train) print("Accuracy: ", voting_classfication.score(X_test,y_test))
Titanic - Machine Learning from Disaster
13,636,756
ts = time.time() group = matrix.groupby(['date_block_num', 'subtype_code'] ).agg({'item_cnt_month': ['mean']}) group.columns = [ 'date_subtype_avg_item_cnt' ] group.reset_index(inplace=True) matrix = pd.merge(matrix, group, on=['date_block_num', 'subtype_code'], how='left') matrix['date_subtype_avg_item_cnt'] = matr...
test_result = pd.Series(voting_classfication.predict(test), name = "Survived" ).astype(int) results = pd.concat([test_data["PassengerId"], test_result],axis = 1) results.to_csv("titanic_submission2.csv", index = False )
Titanic - Machine Learning from Disaster
13,636,756
ts = time.time() group = train.groupby(['item_id'] ).agg({'item_price': ['mean']}) group.columns = ['item_avg_item_price'] group.reset_index(inplace=True) matrix = pd.merge(matrix, group, on=['item_id'], how='left') matrix['item_avg_item_price'] = matrix['item_avg_item_price'].astype(np.float16) group = train.group...
from sklearn.model_selection import cross_val_score from sklearn.naive_bayes import GaussianNB from sklearn.linear_model import LogisticRegression from sklearn import tree from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.svm import SVC
Titanic - Machine Learning from Disaster
13,636,756
ts = time.time() group = train.groupby(['date_block_num','shop_id'] ).agg({'revenue': ['sum']}) group.columns = ['date_shop_revenue'] group.reset_index(inplace=True) matrix = pd.merge(matrix, group, on=['date_block_num','shop_id'], how='left') matrix['date_shop_revenue'] = matrix['date_shop_revenue'].astype(np.float...
gnb = GaussianNB() cv = cross_val_score(gnb,X_train,y_train,cv=5) print(cv) print(cv.mean() )
Titanic - Machine Learning from Disaster
13,636,756
matrix['month'] = matrix['date_block_num'] % 12<categorify>
lr = LogisticRegression(max_iter = 2000) cv = cross_val_score(lr,X_train,y_train,cv=5) print(cv) print(cv.mean() )
Titanic - Machine Learning from Disaster
13,636,756
days = pd.Series([31,28,31,30,31,30,31,31,30,31,30,31]) matrix['days'] = matrix['month'].map(days ).astype(np.int8 )<data_type_conversions>
lr = LogisticRegression(max_iter = 2000) cv = cross_val_score(lr,X_train,y_train,cv=5) print(cv) print(cv.mean() )
Titanic - Machine Learning from Disaster
13,636,756
ts = time.time() cache = {} matrix['item_shop_last_sale'] = -1 matrix['item_shop_last_sale'] = matrix['item_shop_last_sale'].astype(np.int8) for idx, row in matrix.iterrows() : key = str(row.item_id)+' '+str(row.shop_id) if key not in cache: if row.item_cnt_month!=0: cache[key] = row.date_block_num else: last_date_bl...
dt = tree.DecisionTreeClassifier(random_state = 1) cv = cross_val_score(dt,X_train,y_train,cv=5) print(cv) print(cv.mean() )
Titanic - Machine Learning from Disaster
13,636,756
ts = time.time() cache = {} matrix['item_last_sale'] = -1 matrix['item_last_sale'] = matrix['item_last_sale'].astype(np.int8) for idx, row in matrix.iterrows() : key = row.item_id if key not in cache: if row.item_cnt_month!=0: cache[key] = row.date_block_num else: last_date_block_num = cache[key] if row.date_block_num...
dt = tree.DecisionTreeClassifier(random_state = 1) cv = cross_val_score(dt,X_train,y_train,cv=5) print(cv) print(cv.mean() )
Titanic - Machine Learning from Disaster
13,636,756
ts = time.time() matrix['item_shop_first_sale'] = matrix['date_block_num'] - matrix.groupby(['item_id','shop_id'])['date_block_num'].transform('min') matrix['item_first_sale'] = matrix['date_block_num'] - matrix.groupby('item_id')['date_block_num'].transform('min') time.time() - ts<filter>
knn = KNeighborsClassifier() cv = cross_val_score(knn,X_train,y_train,cv=5) print(cv) print(cv.mean() )
Titanic - Machine Learning from Disaster
13,636,756
ts = time.time() matrix = matrix[matrix.date_block_num > 11] time.time() - ts<correct_missing_values>
knn = KNeighborsClassifier() cv = cross_val_score(knn,X_train,y_train,cv=5) print(cv) print(cv.mean() )
Titanic - Machine Learning from Disaster
13,636,756
ts = time.time() def fill_na(df): for col in df.columns: if('_lag_' in col)&(df[col].isnull().any()): if('item_cnt' in col): df[col].fillna(0, inplace=True) return df matrix = fill_na(matrix) time.time() - ts<drop_column>
rf = RandomForestClassifier(random_state = 1) cv = cross_val_score(rf,X_train,y_train,cv=5) print(cv) print(cv.mean() )
Titanic - Machine Learning from Disaster
13,636,756
del cache del group del items del shops del cats del train gc.collect() ;<drop_column>
rf = RandomForestClassifier(random_state = 1) cv = cross_val_score(rf,X_train,y_train,cv=5) print(cv) print(cv.mean() )
Titanic - Machine Learning from Disaster
13,636,756
matrix = matrix[[ 'date_block_num', 'shop_id', 'item_id', 'item_cnt_month', 'city_code', 'item_category_id', 'type_code', 'subtype_code', 'item_cnt_month_lag_1', 'item_cnt_month_lag_2', 'item_cnt_month_lag_3', 'item_cnt_month_lag_6', 'item_cnt_month_lag_12', 'date_avg_item_cnt_lag_1', 'date_item_avg_item_cnt_lag_1', 'd...
svc = SVC(probability = True) cv = cross_val_score(svc,X_train,y_train,cv=5) print(cv) print(cv.mean() )
Titanic - Machine Learning from Disaster
13,636,756
X_train = matrix[matrix.date_block_num < 34].drop(['item_cnt_month'], axis=1) y_train = matrix[matrix.date_block_num < 34]['item_cnt_month'] X_test = matrix[matrix.date_block_num == 34].drop(['item_cnt_month'], axis=1) <import_modules>
svc_poly = SVC(probability = True, kernel='poly', degree=2, gamma='auto', coef0=1, C=5) cv = cross_val_score(svc,X_train,y_train,cv=5) print(cv) print(cv.mean() )
Titanic - Machine Learning from Disaster
13,636,756
import lightgbm as lgb from sklearn.linear_model import LinearRegression<choose_model_class>
svc_rbf = SVC(probability = True, kernel='rbf', gamma=0.5, C=0.1) cv = cross_val_score(svc,X_train,y_train,cv=5) print(cv) print(cv.mean() )
Titanic - Machine Learning from Disaster
13,636,756
lr = LinearRegression() lr.fit(X_train.values, y_train) pred_lr = lr.predict(X_test.values )<init_hyperparams>
xgb = XGBClassifier(random_state =1) cv = cross_val_score(xgb,X_train,y_train,cv=5) print(cv) print(cv.mean() )
Titanic - Machine Learning from Disaster
13,636,756
lgb_params = { 'feature_fraction': 0.75, 'metric': 'rmse', 'nthread':1, 'min_data_in_leaf': 2**7, 'bagging_fraction': 0.75, 'learning_rate': 0.03, 'objective': 'mse', 'bagging_seed': 2**7, 'num_leaves': 2**7, 'bagging_freq':1, 'verbose':0 } model = lgb.train(lgb_params, lgb.Dataset(X_train, label=y_train), 100) pred_l...
voting_clf = VotingClassifier(estimators = [('lr',lr),('knn',knn),('rf',rf),('gnb',gnb),('svc',svc),('xgb',xgb), ('svc_poly', svc_poly),('svc_rbf', svc_rbf)], voting = 'soft' )
Titanic - Machine Learning from Disaster
13,636,756
X_test_level2 = np.c_[pred_lr, pred_lgb]<define_variables>
cv = cross_val_score(voting_clf,X_train,y_train,cv=5) print(cv) print(cv.mean() )
Titanic - Machine Learning from Disaster
13,636,756
dates = matrix['date_block_num'] dates_train = dates[dates < 34] dates_test = dates[dates == 34]<prepare_x_and_y>
svc_poly.fit(X_train,y_train) test_result = pd.Series(svc_poly.predict(test), name = "Survived" ).astype(int) results = pd.concat([test_data["PassengerId"], test_result],axis = 1) results.to_csv("titanic_submission.csv", index = False )
Titanic - Machine Learning from Disaster
13,636,756
dates_train_level2 = dates_train[dates_train.isin([27, 28, 29, 30, 31, 32, 33])] y_train_level2 = y_train[dates_train.isin([27, 28, 29, 30, 31, 32, 33])]<categorify>
from sklearn.model_selection import GridSearchCV from sklearn.model_selection import RandomizedSearchCV
Titanic - Machine Learning from Disaster
13,636,756
X_train_level2 = np.zeros([y_train_level2.shape[0], 2]) for cur_block_num in [27, 28, 29, 30, 31, 32, 33]: print(cur_block_num) X_train = matrix.loc[dates < cur_block_num].drop(['item_cnt_month'], axis=1) X_test = matrix.loc[dates == cur_block_num].drop(['item_cnt_month'], axis=1) y_train = matrix.loc[dates < cur_b...
def clf_performance(classifier, model_name): print(model_name) print('Best Score: ' + str(classifier.best_score_)) print('Best Parameters: ' + str(classifier.best_params_))
Titanic - Machine Learning from Disaster
13,636,756
alphas_to_try = np.linspace(0, 1, 1001) best_alpha = 0 r2_train_simple_mix = 0 for alpha in alphas_to_try: mix = alpha*X_train_level2[:,0] +(1-alpha)*X_train_level2[:,1] r2 = r2_score(y_train_level2, mix) if r2 > r2_train_simple_mix: best_alpha = alpha r2_train_simple_mix = r2<prepare_output>
lr = LogisticRegression() param_grid = {'max_iter' : [2000], 'penalty' : ['l1', 'l2'], 'C' : np.logspace(-4, 4, 20), 'solver' : ['liblinear']} clf_lr = GridSearchCV(lr, param_grid = param_grid, cv = 5, verbose = True, n_jobs = -1) best_clf_lr = clf_lr.fit(X_train,y_train) clf_performance(best_clf_lr,'Logistic Regress...
Titanic - Machine Learning from Disaster
13,636,756
test_preds = best_alpha*X_test_level2[:,0] +(1-best_alpha)*X_test_level2[:,1] test_preds = test_preds.clip(0,20 )<create_dataframe>
knn = KNeighborsClassifier() param_grid = {'n_neighbors' : [3,5,7,9], 'weights' : ['uniform', 'distance'], 'algorithm' : ['auto', 'ball_tree','kd_tree'], 'p' : [1,2]} clf_knn = GridSearchCV(knn, param_grid = param_grid, cv = 5, verbose = True, n_jobs = -1) best_clf_knn = clf_knn.fit(X_train,y_train) clf_performance(b...
Titanic - Machine Learning from Disaster
13,636,756
submissions = pd.DataFrame({ "ID": test.index, "item_cnt_month": test_preds }) submissions.item_cnt_month = submissions.item_cnt_month.fillna(0.0 )<save_to_csv>
svc = SVC(probability = True) param_grid = tuned_parameters = [{'kernel': ['rbf'], 'gamma': [.1,.5,1,2,5,10], 'C': [.1, 1, 10, 100, 1000]}, {'kernel': ['linear'], 'C': [.1, 1, 10, 100, 1000]}, {'kernel': ['poly'], 'degree' : [2,3,4,5], 'C': [.1, 1, 10, 100, 1000]}] clf_svc = GridSearchCV(svc, param_grid = param_grid, ...
Titanic - Machine Learning from Disaster
13,636,756
submissions.to_csv('submission.csv',index=False )<install_modules>
rf = RandomForestClassifier(random_state = 1) param_grid = {'n_estimators': [400,450,500,550], 'criterion':['gini','entropy'], 'bootstrap': [True], 'max_depth': [15, 20, 25], 'max_features': ['auto','sqrt', 10], 'min_samples_leaf': [2,3], 'min_samples_split': [2,3]} clf_rf = GridSearchCV(rf, param_grid = param_grid, c...
Titanic - Machine Learning from Disaster
13,636,756
!pip install efficientnet -U<set_options>
param_grid = { 'n_estimators': [450,500,550], 'colsample_bytree': [0.75,0.8,0.85], 'max_depth': [10], 'reg_alpha': [1], 'reg_lambda': [2, 5, 10], 'subsample': [0.55, 0.6,.65], 'learning_rate':[0.5], 'gamma':[.5,1,2], 'min_child_weight':[0.01], 'sampling_method': ['uniform'] } clf_xgb = GridSearchCV(xgb, param_grid = pa...
Titanic - Machine Learning from Disaster
13,636,756
<load_from_csv><EOS>
test_result = pd.Series(best_clf_xgb.predict(test), name = "Survived" ).astype(int) results = pd.concat([test_data["PassengerId"], test_result],axis = 1) results.to_csv("titanic_submission1.csv", index = False)
Titanic - Machine Learning from Disaster
13,644,205
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<compute_train_metric>
SEED = 7 print("Setup complete." )
Titanic - Machine Learning from Disaster
13,644,205
def sigmoid_focal_cross_entropy_with_logits( labels, logits, alpha=0.25, gamma=2.0): if gamma and gamma < 0: raise ValueError("Value of gamma should be greater than or equal to zero") logits = tf.convert_to_tensor(logits) labels = tf.convert_to_tensor(labels, dtype=logits.dtype) ce = tf.nn.sigmoid_cross_entropy_wit...
train = pd.read_csv(".. /input/titanic/train.csv") test = pd.read_csv(".. /input/titanic/test.csv") datasets = [train, test] train
Titanic - Machine Learning from Disaster
13,644,205
def get_optimizer(steps_per_epoch, lr_max, lr_min, decay_epochs, warmup_epochs, power=1): if decay_epochs > 0: learning_rate_fn = tf.keras.optimizers.schedules.PolynomialDecay( initial_learning_rate=lr_max, decay_steps=steps_per_epoch*decay_epochs, end_learning_rate=lr_min, power=power, ) else: learning_rate_fn = lr...
for ds in datasets: def rand_ages() : np.random.seed(SEED) return np.random.randint(low=ds['Age'].mean() - ds['Age'].std() , high=ds['Age'].mean() + ds['Age'].std() , size=ds['Age'].isnull().sum()) ds.loc[ds['Age'].isnull() , 'Age'] = rand_ages() ds['Age'] = pd.cut( ds['Age'], bins=[-np.inf, 14, 24, 64, np.inf], lab...
Titanic - Machine Learning from Disaster
13,644,205
config = { 'lr_max': 3e-4, 'lr_min': 3e-5, 'lr_decay_epochs': 14, 'lr_warmup_epochs': 1, 'lr_decay_power': 1, 'n_epochs': 12, 'label_smoothing': 0.05, 'focal_loss': False, 'tta': 5, 'save_best': None, 'pretrained_weights': 'imagenet', 'finetuned_weights': None, } fold_config = { 0: { 'engine': EfficientNetB0, 'input_pa...
def encode_freq_sorted(feature): sorted_indices = feature.value_counts().index sorted_dict = dict(zip(sorted_indices, range(len(sorted_indices)))) return feature.map(sorted_dict ).astype(int) for ds in datasets: ds['Sex'] = encode_freq_sorted(ds['Sex']) ds['Embarked'] = encode_freq_sorted(ds['Embarked']) ds['Title']...
Titanic - Machine Learning from Disaster
13,644,205
final_preds = np.average(test_preds_accum, axis=0, weights=[1,1,1,1,1]) final_preds_map = dict(zip(test_names_accum[0].astype('U13'), final_preds)) submission_data['target'] = submission_data.image_name.map(final_preds_map) submission_data.to_csv('submission.csv', index=False )<import_modules>
drop_features = ['Name', 'SibSp', 'Parch', 'Ticket', 'Cabin']
Titanic - Machine Learning from Disaster
13,644,205
import pandas as pd import numpy as np<import_modules>
drop_features.extend(['Pclass']) train = train.drop(columns=drop_features) test = test.drop(columns=drop_features) X = train.drop(columns=['PassengerId', 'Survived']) y = train['Survived'] X.head()
Titanic - Machine Learning from Disaster
13,644,205
import pandas as pd import numpy as np<load_from_csv>
X_train, X_val, y_train, y_val = train_test_split(X, y, train_size=0.75, random_state=SEED) X_test = test.drop(columns=['PassengerId'] )
Titanic - Machine Learning from Disaster
13,644,205
sub1 = pd.read_csv('.. /input/melanoma-dif-sub/pl_0.936.csv') sub2 = pd.read_csv('.. /input/melanoma-dif-sub/pl_0.940.csv') sub3 = pd.read_csv('.. /input/melanoma-dif-sub/sub_EfficientNetB2_384.csv') sub4 = pd.read_csv('.. /input/melanoma-dif-sub/sub_EfficientNetB3_384.csv') sub5 = pd.read_csv('.. /input/melanoma-d...
cross_valid = StratifiedKFold(n_splits=3, shuffle=True, random_state=SEED) def random_search(X, y, estimator, params, score="accuracy", cv=cross_valid, n_iter=100, random_state=SEED, n_jobs=-1): print(" classifier = RandomizedSearchCV(estimator=estimator, param_distributions=params, scoring=score, cv=cv, n_iter=n_it...
Titanic - Machine Learning from Disaster
13,644,205
!pip install -q efficientnet<import_modules>
random_forest = RandomForestClassifier(random_state=SEED) random_forest.get_params()
Titanic - Machine Learning from Disaster
13,644,205
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 import dill fr...
params = { 'bootstrap': [True, False], 'max_depth': [int(x)for x in np.linspace(10, 110, num = 11)], 'max_features': ['auto', 'sqrt'], 'min_samples_leaf': [1, 2, 4], 'min_samples_split': [2, 5, 10], 'n_estimators': [int(x)for x in np.linspace(200, 2000, num = 10)] } random_forest_tuned = random_search( X_train, y_trai...
Titanic - Machine Learning from Disaster
13,644,205
tpu = tf.distribute.cluster_resolver.TPUClusterResolver() print('Running on TPU ', tpu.master()) tf.config.experimental_connect_to_cluster(tpu) tf.tpu.experimental.initialize_tpu_system(tpu) strategy = tf.distribute.experimental.TPUStrategy(tpu )<load_from_csv>
y_pred = random_forest_tuned.predict(X_val) accuracy_random_forest = accuracy_score(y_val, y_pred) print("Accuracy:", accuracy_random_forest )
Titanic - Machine Learning from Disaster
13,644,205
AUTO = tf.data.experimental.AUTOTUNE GCS_PATH = KaggleDatasets().get_gcs_path('melanoma-384x384') EPOCHS = 30 BATCH_SIZE = 16 * strategy.num_replicas_in_sync AUG_BATCH = BATCH_SIZE IMAGE_SIZE = [384, 384] SEED = 333 LR = 1e-5 cutmix_rate = 0.30 TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train*.tfrec') TEST_FI...
svc = SVC(probability=True, random_state=SEED) svc.get_params()
Titanic - Machine Learning from Disaster
13,644,205
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift): rotation = math.pi * rotation / 180. shear = math.pi * shear / 180. c1 = tf.math.cos(rotation) s1 = tf.math.sin(rotation) one = tf.constant([1],dtype='float32') zero = tf.constant([0],dtype='float32') rotation_matrix = tf.reshape(tf...
params = { 'C': scipy.stats.expon(scale=78), 'class_weight':['balanced', None], 'gamma': scipy.stats.expon(scale=.1), 'kernel':['rbf', 'linear'] } svc_tuned = random_search(X_train, y_train, estimator=svc, params=params )
Titanic - Machine Learning from Disaster
13,644,205
def binary_focal_loss(gamma=2., alpha=.25): def binary_focal_loss_fixed(y_true, y_pred): pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred)) pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred)) epsilon = K.epsilon() pt_1 = K.clip(pt_1, epsilon, 1.- epsilon) pt_0 = K.clip(pt_0, epsilon...
y_pred = svc_tuned.predict(X_val) accuracy_svc = accuracy_score(y_val, y_pred) print("Accuracy:", accuracy_svc )
Titanic - Machine Learning from Disaster
13,644,205
DEVICE = "TPU" CFG = dict( net_count = 7, batch_size = 16, read_size = 256, crop_size = 250, net_size = 224, LR_START = 0.000005, LR_MAX = 0.000020, LR_MIN = 0.000001, LR_RAMPUP_EPOCHS = 5, LR_SUSTAIN_EPOCHS = 0, LR_EXP_DECAY = 0.8, epochs = 12, rot = 180.0, shr = 2.0, hzoom = 8.0, wzoom = 8.0, hshift = 8.0, wshift = ...
xgb = XGBClassifier(random_state=SEED, verbosity=0) xgb.get_params()
Titanic - Machine Learning from Disaster
13,644,205
!pip install -q efficientnet<set_options>
params = { 'colsample_bytree': list(np.arange(0.6, 1.0, step=0.05)) , 'gamma': list(np.arange(0.1, 15, step=0.2)) , 'learning_rate': [0.01, 0.05, 0.1, 0.15, 0.21], 'max_depth': list(range(2, 12)) , 'min_child_weight': list(range(1, 12)) , 'n_estimators': [10, 100, 500, 1000], 'reg_alpha': [10**i for i in range(-5, 1)],...
Titanic - Machine Learning from Disaster
13,644,205
random.seed(a=42) <load_from_csv>
y_pred = xgb_tuned.predict(X_val) accuracy_xgboost = accuracy_score(y_val, y_pred) print("Accuracy:", accuracy_xgboost )
Titanic - Machine Learning from Disaster
13,644,205
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-256x256') files_train =...
decision_tree = DecisionTreeClassifier(random_state=SEED) decision_tree.get_params()
Titanic - Machine Learning from Disaster
13,644,205
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...
params = { 'criterion': ["gini", "entropy"], 'max_depth': list(range(1, 32)) , 'max_features': list(range(1, X_train.shape[1]+1)) , 'min_samples_leaf': list(range(1, 9)) , 'min_samples_split': list(np.arange(0.1, 1.1, step=0.1)) } decision_tree_tuned = random_search( X_train, y_train, estimator=decision_tree, params=p...
Titanic - Machine Learning from Disaster
13,644,205
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') ...
y_pred = decision_tree_tuned.predict(X_val) accuracy_decision_tree = accuracy_score(y_val, y_pred) print("Accuracy:", accuracy_decision_tree )
Titanic - Machine Learning from Disaster
13,644,205
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...
knn = KNeighborsClassifier() knn.get_params()
Titanic - Machine Learning from Disaster
13,644,205
def get_dataset(files, cfg, augment = False, shuffle = False, repeat = False, labeled=True, return_image_names=True): 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_deterministic = Fa...
params = { 'leaf_size': list(range(20, 60)) , 'n_neighbors': list(range(3, 30)) , 'p': [1, 2] } knn_tuned = random_search(X_train, y_train, estimator=knn, params=params )
Titanic - Machine Learning from Disaster
13,644,205
def show_dataset(thumb_size, cols, rows, ds): mosaic = PIL.Image.new(mode='RGB', size=(thumb_size*cols +(cols-1), thumb_size*rows +(rows-1))) for idx, data in enumerate(iter(ds)) : img, target_or_imgid = data ix = idx % cols iy = idx // cols img = np.clip(img.numpy() * 255, 0, 255 ).astype(np.uint8) img = PIL.Image.f...
y_pred = knn_tuned.predict(X_val) accuracy_knn = accuracy_score(y_val, y_pred) print("Accuracy:", accuracy_knn )
Titanic - Machine Learning from Disaster
13,644,205
ds = tf.data.TFRecordDataset(files_train, num_parallel_reads=AUTO) ds = ds.take(1 ).cache().repeat() ds = ds.map(read_labeled_tfrecord, num_parallel_calls=AUTO) ds = ds.map(lambda img, target:(prepare_image(img, cfg=CFG, augment=True), target), num_parallel_calls=AUTO) ds = ds.take(12*5) ds = ds.prefetch(AUTO) sho...
logistic_regression = LogisticRegression(random_state=SEED) logistic_regression.get_params()
Titanic - Machine Learning from Disaster
13,644,205
ds = get_dataset(files_test, CFG, labeled=False ).unbatch().take(12*5) show_dataset(64, 12, 5, ds )<choose_model_class>
params = { 'C': scipy.stats.loguniform(1e-4, 100), 'penalty': ['l1', 'l2', 'elasticnet'], 'solver': ['newton-cg', 'lbfgs', 'liblinear'] } logistic_regression_tuned = random_search( X_train, y_train, estimator=logistic_regression, params=params )
Titanic - Machine Learning from Disaster
13,644,205
def get_lr_callback(cfg): lr_start = cfg['LR_START'] lr_max = cfg['LR_MAX'] * strategy.num_replicas_in_sync lr_min = cfg['LR_MIN'] lr_ramp_ep = cfg['LR_RAMPUP_EPOCHS'] lr_sus_ep = cfg['LR_SUSTAIN_EPOCHS'] lr_decay = cfg['LR_EXP_DECAY'] def lrfn(epoch): if epoch < lr_ramp_ep: lr =(lr_max - lr_start)/ lr_ramp_ep * epoch ...
y_pred = logistic_regression_tuned.predict(X_val) accuracy_logistic_regression = accuracy_score(y_val, y_pred) print("Accuracy:", accuracy_logistic_regression )
Titanic - Machine Learning from Disaster
13,644,205
def get_model(cfg): model_input = tf.keras.Input(shape=(cfg['net_size'], cfg['net_size'], 3), name='imgIn') dummy = tf.keras.layers.Lambda(lambda x:x )(model_input) outputs = [] for i in range(cfg['net_count']): constructor = getattr(efn, f'EfficientNetB{i}') x = constructor(include_top=False, weights='imagenet', in...
naive_bayes = GaussianNB() naive_bayes.get_params()
Titanic - Machine Learning from Disaster
13,644,205
def compile_new_model(cfg): with strategy.scope() : model = get_model(cfg) losses = [tf.keras.losses.BinaryCrossentropy(label_smoothing = cfg['label_smooth_fac']) for i in range(cfg['net_count'])] model.compile( optimizer = cfg['optimizer'], loss = losses, metrics = [tf.keras.metrics.AUC(name='auc')]) return model<...
params = { 'var_smoothing': [np.exp(-i)for i in range(1, 15)] } naive_bayes_tuned = random_search( X_train, y_train, estimator=naive_bayes, params=params, n_iter=15-1 )
Titanic - Machine Learning from Disaster
13,644,205
ds_train = get_dataset(files_train, CFG, augment=True, shuffle=True, repeat=True) ds_train = ds_train.map(lambda img, label:(img, tuple([label] * CFG['net_count']))) steps_train = count_data_items(files_train)/(CFG['batch_size'] * REPLICAS) model = compile_new_model(CFG) history = model.fit(ds_train, verbose = 1, s...
y_pred = naive_bayes_tuned.predict(X_val) accuracy_naive_bayes = accuracy_score(y_val, y_pred) print("Accuracy:", accuracy_naive_bayes )
Titanic - Machine Learning from Disaster
13,644,205
CFG['batch_size'] = 256 cnt_test = count_data_items(files_test) steps = cnt_test /(CFG['batch_size'] * REPLICAS)* CFG['tta_steps'] ds_testAug = get_dataset(files_test, CFG, augment=True, repeat=True, labeled=False, return_image_names=False) probs = model.predict(ds_testAug, verbose=1, steps=steps) probs = np.stack(p...
voting = VotingClassifier( estimators=[('rf', random_forest_tuned), ('xgb', xgb_tuned), ('knn', knn_tuned), ('svc', svc_tuned), ('lr', logistic_regression_tuned), ('dt', decision_tree_tuned), ('nb', naive_bayes_tuned)], voting='soft', n_jobs=-1) voting = voting.fit(X_train, y_train )
Titanic - Machine Learning from Disaster
13,644,205
ds = get_dataset(files_test, CFG, augment=False, repeat=False, 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>
y_pred = voting.predict(X_val) accuracy_voting = accuracy_score(y_val, y_pred) print("Accuracy:", accuracy_voting )
Titanic - Machine Learning from Disaster
13,644,205
<save_to_csv><EOS>
model = voting predictions = model.predict(X_test) output = pd.DataFrame({'PassengerId': test['PassengerId'], 'Survived': predictions}) output.to_csv('my_submission.csv', index=False) print("The results successfully saved!" )
Titanic - Machine Learning from Disaster
13,589,439
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<define_variables>
%matplotlib inline sns.set_style('darkgrid' )
Titanic - Machine Learning from Disaster
13,589,439
DATA_PATH = '/kaggle/input/efficientbx-melanoma-classification-with-tf' history_files = [f for f in listdir(DATA_PATH)if isfile(join(DATA_PATH, f)) and f.split('_')[0] == 'history'] submit_files = [f for f in listdir(DATA_PATH)if isfile(join(DATA_PATH, f)) and f.split('_')[0] == 'submit']<load_from_csv>
train_df = pd.read_csv('.. /input/titanic/train.csv') test_df = pd.read_csv('.. /input/titanic/test.csv' )
Titanic - Machine Learning from Disaster
13,589,439
list_results = [] for file_name_i in history_files: model_name_i = file_name_i[8:22] fold_name_i = file_name_i[23:29] df_i = pd.read_csv(os.path.join(DATA_PATH, file_name_i), index_col=0) auc_i = df_i[df_i.val_loss == df_i.val_loss.min() ]['val_auc'].iloc[0] loss_i = df_i.val_loss.min() list_results.append([model_name...
train_df.isnull().sum()
Titanic - Machine Learning from Disaster
13,589,439
model_names = ['EfficientNetB' + str(i)for i in range(8)] fold_names = ['fold_' + str(i)for i in range(4)] dict_df_history = {} for model_i in model_names: dict_df_history[model_i] = {} for fold_i in fold_names: file_name_i = 'history_' + model_i + '_' + fold_i + '.csv' df_history_i = pd.read_csv(os.path.join(DATA_PATH...
test_df.isnull().sum()
Titanic - Machine Learning from Disaster
13,589,439
sample_submit = pd.read_csv('/kaggle/input/siim-isic-melanoma-classification/sample_submission.csv') for model_name_i in model_names: target_list = [] for fold_i in fold_names: target_i = pd.read_csv(os.path.join(DATA_PATH, 'submit_' + model_name_i + '_' + fold_i + '.csv')) ['target'].values target_list.append(target_...
comp_df = pd.concat([train_df, test_df]) comp_df.reset_index(drop=True, inplace=True )
Titanic - Machine Learning from Disaster
13,589,439
!pip install xgboost <load_from_csv>
comp_df.isnull().sum()
Titanic - Machine Learning from Disaster
13,589,439
train= pd.read_csv('.. /input/siim-isic-melanoma-classification/train.csv') test= pd.read_csv('.. /input/siim-isic-melanoma-classification/test.csv') sub = pd.read_csv('.. /input/siim-isic-melanoma-classification/sample_submission.csv') train.head() train.target.value_counts() <data_type_conversions>
comp_df.drop('PassengerId',axis=1, inplace=True) comp_df.drop('Cabin',axis=1,inplace=True) comp_df.drop("Ticket",axis=1, inplace=True )
Titanic - Machine Learning from Disaster
13,589,439
train['sex'] = train['sex'].fillna('na') train['age_approx'] = train['age_approx'].fillna(0) train['anatom_site_general_challenge'] = train['anatom_site_general_challenge'].fillna('na') test['sex'] = test['sex'].fillna('na') test['age_approx'] = test['age_approx'].fillna(0) test['anatom_site_general_challenge'] = ...
p1 = comp_df[comp_df.Pclass==1]['Age'].median() p2 = comp_df[comp_df.Pclass==2]['Age'].median() p3 = comp_df[comp_df.Pclass==3]['Age'].median() def fill_age(row): if np.isnan(row.Age): if row.Pclass == 1: return p1 elif row.Pclass == 2: return p2 elif row.Pclass == 3: return p3 else: return row.Age comp_df.Age = comp_d...
Titanic - Machine Learning from Disaster
13,589,439
train['sex'] = train['sex'].astype("category" ).cat.codes +1 train['anatom_site_general_challenge'] = train['anatom_site_general_challenge'].astype("category" ).cat.codes +1 train.head()<data_type_conversions>
comp_df = comp_df[comp_df.Age<80]
Titanic - Machine Learning from Disaster
13,589,439
test['sex'] = test['sex'].astype("category" ).cat.codes +1 test['anatom_site_general_challenge'] = test['anatom_site_general_challenge'].astype("category" ).cat.codes +1 test.head()<prepare_x_and_y>
comp_df.Fare.isnull().sum()
Titanic - Machine Learning from Disaster
13,589,439
x_train = train[['sex', 'age_approx','anatom_site_general_challenge']] y_train = train['target'] x_test = test[['sex', 'age_approx','anatom_site_general_challenge']] train_DMatrix = xgb.DMatrix(x_train, label= y_train) test_DMatrix = xgb.DMatrix(x_test )<init_hyperparams>
comp_df.Fare.fillna(comp_df.Fare.median() , inplace=True )
Titanic - Machine Learning from Disaster
13,589,439
param = { 'booster':'gbtree', 'eta': 0.3, 'num_class': 2, 'max_depth': } epochs = 100<choose_model_class>
upper_limit = comp_df.Fare.quantile(0.75)+(1.5 * iqr(comp_df.Fare)) lower_limit = comp_df.Fare.quantile(0.25)-(1.5 * iqr(comp_df.Fare))
Titanic - Machine Learning from Disaster
13,589,439
clf = xgb.XGBClassifier(n_estimators=2000, max_depth=8, objective='multi:softprob', seed=0, nthread=-1, learning_rate=0.15, num_class = 2, scale_pos_weight =(32542/584)) <train_model>
comp_df[(comp_df.Fare>upper_limit)&(comp_df.Survived.notnull())].shape
Titanic - Machine Learning from Disaster
13,589,439
clf.fit(x_train, y_train )<predict_on_test>
comp_df[(comp_df.Fare>100)&(comp_df.Survived.notnull())].shape
Titanic - Machine Learning from Disaster
13,589,439
clf.predict_proba(x_test)[:,1] sub.target = clf.predict_proba(x_test)[:,1] sub_tabular = sub.copy()<load_from_csv>
train_df = comp_df[comp_df.Survived.notnull() ] test_df = comp_df[comp_df.Survived.isnull() ]
Titanic - Machine Learning from Disaster
13,589,439
sub_public_merge = pd.read_csv('/kaggle/input/submission-9/submission_935.csv') sub_mean = pd.read_csv('/kaggle/input/siim-isic-multiple-model-training-stacking-923/submission_mean.csv' )<prepare_output>
train_df.shape, test_df.shape train_df = train_df[train_df.Fare<=100] comp_df = pd.concat([train_df,test_df] )
Titanic - Machine Learning from Disaster
13,589,439
sub.target = sub_mean.target *0.1 + sub_public_merge.target *0.7 + sub_tabular.target *0.2<save_to_csv>
comp_df.Embarked.isnull().sum()
Titanic - Machine Learning from Disaster
13,589,439
sub.head() sub.to_csv('submission.csv', index = False )<install_modules>
comp_df.Embarked.value_counts()
Titanic - Machine Learning from Disaster
13,589,439
!pip install.. /input/python-datatable/datatable-0.11.0-cp37-cp37m-manylinux2010_x86_64.whl > /dev/null 2>&1<import_modules>
comp_df.Embarked.fillna('S',inplace=True )
Titanic - Machine Learning from Disaster
13,589,439
import numpy as np import random import pandas as pd import joblib import psutil<set_options>
comp_df.isnull().sum()
Titanic - Machine Learning from Disaster
13,589,439
_ = np.seterr(divide='ignore', invalid='ignore' )<define_variables>
comp_df['family_size'] = comp_df.SibSp + comp_df.Parch
Titanic - Machine Learning from Disaster
13,589,439
data_types_dict = { 'timestamp': 'int64', 'user_id': 'int32', 'content_id': 'int16', 'content_type_id':'int8', 'task_container_id': 'int16', 'answered_correctly': 'int8', 'prior_question_elapsed_time': 'float32', 'prior_question_had_explanation': 'bool' } target = 'answered_correctly'<load_from_csv>
comp_df.drop(['SibSp','Parch'], axis=1, inplace=True )
Titanic - Machine Learning from Disaster
13,589,439
print('start read train data...') train_df = dt.fread('.. /input/riiid-test-answer-prediction/train.csv', columns=set(data_types_dict.keys())).to_pandas()<train_model>
comp_df['title'] = comp_df.Name.str.extract(r'([\w]+[.])' )
Titanic - Machine Learning from Disaster
13,589,439
print('start handle lecture data...' )<load_from_csv>
comp_df.Sex = comp_df.Sex.map({'male':1,'female':0}) comp_df.Embarked = comp_df.Embarked.map({'C':0, 'Q':1,'S':2} )
Titanic - Machine Learning from Disaster
13,589,439
lectures_df = pd.read_csv('/kaggle/input/riiid-test-answer-prediction/lectures.csv' )<categorify>
comp_df.family_size= comp_df.apply(lambda x:4 if x.family_size>4 else x.family_size,axis=1 )
Titanic - Machine Learning from Disaster
13,589,439
lectures_df['type_of'] = lectures_df['type_of'].replace('solving question', 'solving_question') lectures_df = pd.get_dummies(lectures_df, columns=['part', 'type_of']) part_lectures_columns = [column for column in lectures_df.columns if column.startswith('part')] types_of_lectures_columns = [column for column in lectu...
comp_df['title'] = comp_df['title'].str.replace(r'Sir.', 'Mr.') comp_df['title'] = comp_df['title'].str.replace(r'Rev.','Mr.') comp_df['title'] = comp_df['title'].str.replace(r'Lady.','Ms.') comp_df['title'] = comp_df['title'].str.replace(r'Mrs.','Ms.') comp_df['title'] = comp_df['title'].str.replace(r'Miss.','Ms.'...
Titanic - Machine Learning from Disaster
13,589,439
train_lectures = train_df[train_df.content_type_id == True].merge(lectures_df, left_on='content_id', right_on='lecture_id', how='left' )<groupby>
comp_df.drop('Name',axis=1, inplace=True )
Titanic - Machine Learning from Disaster
13,589,439
user_lecture_stats_part = train_lectures.groupby('user_id',as_index = False)[part_lectures_columns + types_of_lectures_columns].sum()<data_type_conversions>
comp_df.title = comp_df.title.map({'other':0, 'scholar':1, 'Ms.':2, 'Mr.':3} )
Titanic - Machine Learning from Disaster
13,589,439
lecturedata_types_dict = { 'user_id': 'int32', 'part_1': 'int8', 'part_2': 'int8', 'part_3': 'int8', 'part_4': 'int8', 'part_5': 'int8', 'part_6': 'int8', 'part_7': 'int8', 'type_of_concept': 'int8', 'type_of_intention': 'int8', 'type_of_solving_question': 'int8', 'type_of_starter': 'int8' } user_lecture_stats_part = u...
comp_df.Age = pd.cut(comp_df.Age, 7, labels=[0,1,2,3,4,5,6]) comp_df.Fare = pd.cut(comp_df.Fare, 7, labels=[0,1,2,3,4,5,6]) comp_df.Age = comp_df.Age.astype('int') comp_df.Fare = comp_df.Fare.astype('int' )
Titanic - Machine Learning from Disaster
13,589,439
for column in user_lecture_stats_part.columns: if(column !='user_id'): user_lecture_stats_part[column] =(user_lecture_stats_part[column] > 0 ).astype('int8' )<drop_column>
train_df = comp_df[comp_df.Survived.notnull() ] test_df = comp_df[comp_df.Survived.isnull() ]
Titanic - Machine Learning from Disaster
13,589,439
del(train_lectures) gc.collect()<categorify>
test_df.drop('Survived',axis=1, inplace=True )
Titanic - Machine Learning from Disaster
13,589,439
user_lecture_agg = train_df.groupby('user_id')['content_type_id'].agg(['sum', 'count']) user_lecture_agg=user_lecture_agg.astype('int16' )<data_type_conversions>
x_train = train_df.drop('Survived',axis=1) y_train = train_df.Survived
Titanic - Machine Learning from Disaster
13,589,439
cum = train_df.groupby('user_id')['content_type_id'].agg(['cumsum', 'cumcount']) cum['cumcount']=cum['cumcount']+1 train_df['user_interaction_count'] = cum['cumcount'] train_df['user_interaction_timestamp_mean'] = train_df['timestamp']/cum['cumcount'] train_df['user_lecture_sum'] = cum['cumsum'] train_df['user_lecture...
from sklearn.model_selection import GridSearchCV, cross_val_score, RepeatedStratifiedKFold, train_test_split from xgboost import XGBClassifier from sklearn.metrics import classification_report
Titanic - Machine Learning from Disaster
13,589,439
del cum gc.collect()<train_model>
model = XGBClassifier() cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=5, random_state=11) scores = cross_val_score(model, x_train, y_train, cv=cv, n_jobs=-1, verbose=True, scoring='roc_auc') print(np.mean(scores),np.std(scores))
Titanic - Machine Learning from Disaster
13,589,439
print('start handle train_df...' )<data_type_conversions>
best_model = XGBClassifier(n_estimators=100, subsample=0.7, max_depth=3, learning_rate=0.01, colsample_bytree=1 )
Titanic - Machine Learning from Disaster