kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
14,331,351
y_train.value_counts() /y_train.shape[0]<train_model>
preds = np.zeros(test.shape[0]) kf = KFold(n_splits=10,random_state=48,shuffle=True) rmse=[] n=0 for trn_idx, test_idx in kf.split(train[features],target): X_tr,X_val=train[features].iloc[trn_idx],train[features].iloc[test_idx] y_tr,y_val=target.iloc[trn_idx],target.iloc[test_idx] model = lgb.LGBMRegressor(**Best_tri...
Tabular Playground Series - Jan 2021
14,331,351
<prepare_x_and_y><EOS>
final_results = [x*0.72 + y*0.28 for x, y in zip(results, preds)] sub['target']=final_results sub.to_csv('submission.csv', index=False )
Tabular Playground Series - Jan 2021
17,103,400
<SOS> metric: RMSE Kaggle data source: tabular-playground-series-jan-2021<import_modules>
import optuna import xgboost as xgb import numpy as np import pandas as pd from sklearn.model_selection import KFold from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split
Tabular Playground Series - Jan 2021
17,103,400
<init_hyperparams>
train = pd.read_csv('.. /input/tabular-playground-series-jan-2021/train.csv') test = pd.read_csv('.. /input/tabular-playground-series-jan-2021/test.csv') sub = pd.read_csv('.. /input/tabular-playground-series-jan-2021/sample_submission.csv' )
Tabular Playground Series - Jan 2021
17,103,400
best_params = {'bagging_fraction': 0.5818772519688797, 'colsample_bytree': 0.3035307099891744, 'feature_fraction': 0.795967379488282, 'gamma': 0.6896677451866189, 'learning_rate': 0.011336192527320772, 'max_depth': 20, 'min_child_samples': 140, 'num_leaves': 230, 'reg_alpha': 0.06035695642758, 'reg_lambda': 0.012734543...
columns = [col for col in train.columns.to_list() if col not in ['id','target']]
Tabular Playground Series - Jan 2021
17,103,400
X_train = final_train.copy() y_train = X_train.pop('isFraud') X_test = final_test.copy() X_train,X_test = X_train.align(other=X_test,join='left', axis=1 )<train_model>
data=train[columns] target=train['target']
Tabular Playground Series - Jan 2021
17,103,400
print("XGBoost version:", xgb.__version__) clf = xgb.XGBClassifier( n_estimators=2000, **best_params, tree_method='gpu_hist', verbose=50, early_stopping_rounds=100 ) clf.fit(X_train, y_train) y_preds = clf.predict_proba(X_test)[:,1]<save_to_csv>
def objective(trial,data=data,target=target): train_x, test_x, train_y, test_y = train_test_split(data, target, test_size=0.15,random_state=42) param = { 'tree_method':'gpu_hist', 'lambda': trial.suggest_loguniform('lambda', 1e-3, 10.0), 'alpha': trial.suggest_loguniform('alpha', 1e-3, 10.0), 'colsample_bytree': trial...
Tabular Playground Series - Jan 2021
17,103,400
sub['isFraud'] = y_preds sub.to_csv('XGB_hypopt_model.csv', index=False )<import_modules>
Best_trial= {'lambda': 0.0042687338951820425, 'alpha': 6.2637008222060935, 'colsample_bytree': 0.4, 'subsample': 0.6, 'n_estimators': 4000, 'learning_rate': 0.01, 'max_depth': 11, 'random_state': 2020, 'min_child_weight': 171, 'tree_method':'gpu_hist' }
Tabular Playground Series - Jan 2021
17,103,400
for dirname, _, filenames in os.walk('/kaggle/input'): for filename in filenames: print(os.path.join(dirname, filename)) <load_from_csv>
preds = np.zeros(test.shape[0]) kf = KFold(n_splits=5,random_state=48,shuffle=True) rmse=[] models = [] n=0 for trn_idx, test_idx in kf.split(train[columns],train['target']): X_tr,X_val=train[columns].iloc[trn_idx],train[columns].iloc[test_idx] y_tr,y_val=train['target'].iloc[trn_idx],train['target'].iloc[test_idx] m...
Tabular Playground Series - Jan 2021
17,103,400
train_transaction = pd.read_csv('/kaggle/input/ieee-fraud-detection/train_transaction.csv') train_identity = pd.read_csv('/kaggle/input/ieee-fraud-detection/train_identity.csv') test_transaction = pd.read_csv('/kaggle/input/ieee-fraud-detection/test_transaction.csv') test_identity = pd.read_csv('/kaggle/input/ieee-f...
sub['target']=preds sub.to_csv('submission.csv', index=False )
Tabular Playground Series - Jan 2021
17,103,400
train_transaction = reduce_mem_usage(train_transaction, verbose = True) train_identity = reduce_mem_usage(train_identity,verbose = True) test_transaction = reduce_mem_usage(test_transaction, verbose=True) test_identity = reduce_mem_usage(test_identity,verbose = True )<set_options>
import matplotlib.pyplot as plt
Tabular Playground Series - Jan 2021
14,305,889
pd.set_option('display.max_columns', None )<merge>
train_df = pd.read_csv("/kaggle/input/tabular-playground-series-jan-2021/train.csv", index_col=["id"]) test_df = pd.read_csv("/kaggle/input/tabular-playground-series-jan-2021/test.csv", index_col=["id"]) X = train_df.iloc[:, :-1].to_numpy() y = train_df.iloc[:, -1].to_numpy() X_test = test_df.to_numpy()
Tabular Playground Series - Jan 2021
14,305,889
final_train = pd.merge(train_transaction, train_identity, how = 'left', on = 'TransactionID') final_test = pd.merge(test_transaction, test_identity, how = 'left', on = 'TransactionID') <drop_column>
def train(model): X_train, X_test, y_train, y_test = train_test_split(X, y.flatten() , test_size=0.1, random_state=156) y_train = y_train.reshape(-1, 1) y_test = y_test.reshape(-1, 1) model = model.fit(X_train, y_train, early_stopping_rounds=100, verbose=False, eval_set=[(X_test, y_test)]) score = mean_squared_erro...
Tabular Playground Series - Jan 2021
14,305,889
del train_transaction del train_identity del test_transaction del test_identity<rename_columns>
def objectiveXGB(trial: Trial, X, y, test): param = { "n_estimators" : trial.suggest_int('n_estimators', 500, 4000), 'max_depth':trial.suggest_int('max_depth', 8, 16), 'min_child_weight':trial.suggest_int('min_child_weight', 1, 300), 'gamma':trial.suggest_int('gamma', 1, 3), 'learning_rate': 0.01, 'colsample_bytree':tr...
Tabular Playground Series - Jan 2021
14,305,889
final_test = final_test.rename(columns = {"id-01": "id_01", "id-02": "id_02", "id-03": "id_03", "id-06": "id_06", "id-05": "id_05", "id-04": "id_04", "id-07": "id_07", "id-08": "id_08", "id-09": "id_09", "id-10": "id_10", "id-11": "id_11", "id-12": "id_12", "id-15": "id_15", "id-14": "id_14", "id-13": "id_13", "id-16":...
study = optuna.create_study(direction='minimize',sampler=TPESampler()) study.optimize(lambda trial : objectiveXGB(trial, X, y, X_test), n_trials=50) print('Best trial: score {}, params {}'.format(study.best_trial.value,study.best_trial.params)) best_param = study.best_trial.params xgbReg = train(xgb.XGBRegressor(**be...
Tabular Playground Series - Jan 2021
14,305,889
def getNulls(data): total = data.isnull().sum() percent = data.isnull().sum() / data.isnull().count() missing_data = pd.concat([total, percent], axis = 1, keys = ['total', 'precent']) return missing_data<count_missing_values>
def objectiveLGBM(trial: Trial, X, y, test): param = { 'objective': 'regression', 'metric': 'root_mean_squared_error', 'verbosity': -1, 'boosting_type': 'gbdt', 'lambda_l1': trial.suggest_loguniform('lambda_l1', 1e-8, 10.0), 'lambda_l2': trial.suggest_loguniform('lambda_l2', 1e-8, 10.0), 'num_leaves': trial.suggest_int...
Tabular Playground Series - Jan 2021
14,305,889
missing_data_train = getNulls(final_train) missing_data_train.head(434 ).T<drop_column>
study = optuna.create_study(direction='minimize',sampler=TPESampler()) study.optimize(lambda trial : objectiveLGBM(trial, X, y, X_test), n_trials=20) print('Best trial: score {}, params {}'.format(study.best_trial.value,study.best_trial.params)) best_param2 = study.best_trial.params lgbm = LGBMRegressor(**best_param2...
Tabular Playground Series - Jan 2021
14,305,889
del missing_data_train<concatenate>
final_model = xgb.XGBRegressor(n_estimators= 2000, max_depth= 16,tree_method='gpu_hist', predictor='gpu_predictor') sgd = SGDRegressor(max_iter=1000) hgb = HistGradientBoostingRegressor(max_depth=3, min_samples_leaf=1) cat = CatBoostRegressor(task_type="GPU", verbose=False) estimators = [ lgbm, cat, sgd, hgb, xgbRe...
Tabular Playground Series - Jan 2021
14,305,889
ntrain = final_train.shape[0] ntest = final_test.shape[0] all_data = pd.concat([final_train, final_test], axis = 0, sort = False )<drop_column>
submission = pd.read_csv("/kaggle/input/tabular-playground-series-jan-2021/test.csv", index_col=["id"]) y_hat = final_model.predict(S_test) submission["target"] = y_hat submission[["target"]].to_csv("/kaggle/working/submission_stacking.csv") joblib.dump(final_model, '/kaggle/working/skacking.pkl' )
Tabular Playground Series - Jan 2021
14,305,889
all_data = all_data.drop(columns=['isFraud'] )<drop_column>
submission = pd.read_csv("/kaggle/input/tabular-playground-series-jan-2021/test.csv", index_col=["id"]) lgbm = LGBMRegressor(**best_param2, device="gpu",gpu_use_dp=True, objective='regression', learning_rate= 0.01, metric='root_mean_squared_error', boosting_type='gbdt') lgbm = lgbm.fit(X, y, verbose=False) y_hat = l...
Tabular Playground Series - Jan 2021
14,305,889
<define_variables><EOS>
submission = pd.read_csv("/kaggle/input/tabular-playground-series-jan-2021/test.csv", index_col=["id"]) params = {'n_estimators': 3520, 'max_depth': 11, 'min_child_weight': 231, 'gamma': 2, 'colsample_bytree': 0.7, 'lambda': 0.014950936465569798, 'alpha': 0.28520156840812494, 'subsample': 0.6} xgbReg = train(xgb.XGBRe...
Tabular Playground Series - Jan 2021
14,589,590
<SOS> metric: RMSE Kaggle data source: tabular-playground-series-jan-2021<define_variables>
sns.set(font_scale=1.4) warnings.filterwarnings("ignore")
Tabular Playground Series - Jan 2021
14,589,590
num_cols_to_shrink_all = detect_num_cols_to_shrink(num_all_cols, all_data) convert_to_int8 = num_cols_to_shrink_all[0] convert_to_int16 = num_cols_to_shrink_all[1] convert_to_int32 = num_cols_to_shrink_all[2] convert_to_float16 = num_cols_to_shrink_all[3] convert_to_float32 = num_cols_to_shrink_all[4]<data_type_conver...
def root_mean_squared_error(y_true, y_pred): return K.sqrt(K.mean(K.square(y_pred - y_true)) )
Tabular Playground Series - Jan 2021
14,589,590
print("starting with converting process.... ") for col in convert_to_int16: all_data[col] = all_data[col].astype('int16') for col in convert_to_int32: all_data[col] = all_data[col].astype('int32') for col in convert_to_float16: all_data[col] = all_data[col].astype('float16') for col in convert_to_float32: all_data[...
def add_pca(train_df, test_df, cols, n_comp=20, fit_test = True, prefix='pca_', fit_test_first=False): pca = PCA(n_components=n_comp, random_state=42) pca_titles = [prefix+'_pca_'+str(x)for x in range(n_comp)] temp_train = train_df.copy() temp_test = test_df.copy() for c in cols: fv = temp_train[c].mean() temp_train[c...
Tabular Playground Series - Jan 2021
14,589,590
v = [1, 3, 4, 6, 8, 11] v += [13, 14, 17, 20, 23, 26, 27, 30] v += [36, 37, 40, 41, 44, 47, 48] v += [54, 56, 59, 62, 65, 67, 68, 70] v += [76, 78, 80, 82, 86, 88, 89, 91] v += [96, 98, 99, 104] v += [107, 108, 111, 115, 117, 120, 121, 123] v += [124, 127, 129, 130, 136] v += [138, 139, 142, 147, 156, 162] v += [165, 1...
PATH = '/kaggle/input/tabular-playground-series-jan-2021/' train = pd.read_csv(PATH+'train.csv') test = pd.read_csv(PATH+'test.csv') submission = pd.read_csv(PATH+'sample_submission.csv') FT_COLS = [x for x in train.columns if 'cont' in x] TARGET='target' print(train.shape) train.head(10 )
Tabular Playground Series - Jan 2021
14,589,590
cols = ['V'+str(x)for x in v] for i in all_data_cols: if(i.startswith("V")) and i not in cols: all_data = all_data.drop(columns=[i]) all_data<drop_column>
original_feature_dict = {'cont1': 5, 'cont2': 10, 'cont3': 8, 'cont4': 8, 'cont5': 5, 'cont6': 6, 'cont7': 4, 'cont8': 3, 'cont9': 7, 'cont10':3, 'cont11': 4, 'cont12': 2, 'cont13': 3, 'cont14': 5,} pca_dict = { 'extra_pca_0': 4, 'extra_pca_1': 1, 'extra_pca_2': 1, 'extra_pca_3': 2, 'extra_pca_4': 1, 'extra_pca_5': 1 }...
Tabular Playground Series - Jan 2021
14,589,590
for c in ['C3','M5','id_08','id_33']: cols.remove(c) all_data = all_data.drop(columns=[i]) for c in ['card4','id_07','id_14','id_21','id_30','id_32','id_34']: cols.remove(c) all_data = all_data.drop(columns=[i]) for c in ['id_'+str(x)for x in range(22,28)]: cols.remove(c) all_data = all_data.drop(columns=[i]) for...
mixture_title_cols=[] for f in FT_COLS+pca_titles2: train, test, titles = split_distributions(train, test,f,TARGET, n_comp=ft_dict[f], prefix=f+'_dim', add_labels=True) mixture_title_cols+=titles mixture_value_cols = [] for count,f in enumerate(FT_COLS+pca_titles2): for d in range(ft_dict[f]): t_median = train[f][trai...
Tabular Playground Series - Jan 2021
14,589,590
numerical = all_data.select_dtypes(include='number') categorical = all_data.select_dtypes(exclude = 'number') numeric_transformer = Pipeline(steps=[('mean',SimpleImputer(strategy='constant',fill_value=-1)) ]) categorical_transformer = Pipeline(steps=[('constant', SimpleImputer(strategy='constant',fill_value=-1)) ] )...
print('Total Original Features', len(FT_COLS)) print('Total Submixtures Labels', len(mixture_title_cols)) print('Total Submixtures Values', len(mixture_value_cols)) print('Total Feature Columns', len(FT_COLS)+len(mixture_title_cols)+len(mixture_value_cols))
Tabular Playground Series - Jan 2021
14,589,590
final_train = all_data[ : ntrain] final_test = all_data[ntrain : ]<drop_column>
NAN_VALUE = 0.0 for d in mixture_value_cols: train[d] = train[d].fillna(value=NAN_VALUE) test[d] = test[d].fillna(value=NAN_VALUE )
Tabular Playground Series - Jan 2021
14,589,590
del all_data<data_type_conversions>
SCALE = True if SCALE: train, test = st_scale(train, test, FT_COLS) for f in FT_COLS: train[f] = np.clip(train[f], -2, 2) test[f] = np.clip(test[f], -2, 2) SCALE_DISTS = True if SCALE_DISTS: for d in mixture_value_cols: TEMP_MAX = np.abs(train[d] ).max() train[d] = train[d] / TEMP_MAX test[d] = test[d] / TEMP_MAX
Tabular Playground Series - Jan 2021
14,589,590
for i,f in enumerate(final_train.columns): if(np.str(final_train[f].dtype)=='category')|(final_train[f].dtype=='object'): df_comb = pd.concat([final_train[f],final_test[f]],axis=0) df_comb,_ = df_comb.factorize(sort=True) if df_comb.max() >32000: print(f,'needs int32') final_train[f] = df_comb[:len(final_train)].ast...
train['outlier_filter'] = np.where(train[TARGET]<4, True, False) print('
Tabular Playground Series - Jan 2021
14,589,590
y.value_counts()<choose_model_class>
print('CV Benchmark - Random Guess of Median') cv_bm = np.sqrt(mse(train[TARGET], np.full(( train[TARGET].shape), train[TARGET].median()))) cv_bm
Tabular Playground Series - Jan 2021
14,589,590
model = xgb.XGBClassifier(n_estimators=2000, max_depth=12, learning_rate=0.02, subsample=0.8, colsample_bytree=0.4, missing=-1, eval_metric='auc', tree_method='hist' )<prepare_x_and_y>
def run_training(model, train_df, test_df,sample_submission, fold_col, orig_features, mixture_val_cols,mixture_label_cols, target_col, benchmark, outlier_col=None, nn=False, epochs=10,batch_size=32, verbose=False, dense=70, dout=0.15, dense_reg = 0.000001,act='elu'): FOLD_VALUES = sorted([x for x in train_df[fold_col]....
Tabular Playground Series - Jan 2021
14,589,590
X_train = final_train y_train = y X_test = final_test<drop_column>
def keras_model(ft_orig, mixture_values, mixture_labels, n_layer=3,bnorm=True,dout=0.2, dense=20,act='elu', dense_reg = 0.000001, descend_fraction = 0.9): input1 = L.Input(shape=(len(ft_orig)) , name='input_orig') input1_do = L.Dropout(0.1 )(input1) XA = L.Dense(dense, activation=act, activity_regularizer=tf.keras.re...
Tabular Playground Series - Jan 2021
14,589,590
del final_train del y del final_test<drop_column>
oof, test_predictions, fold_errors = run_training(model, train, test,submission, 'fold', FT_COLS, mixture_value_cols, mixture_title_cols, TARGET, cv_bm, outlier_col='outlier_filter', epochs=25, batch_size=256, verbose=False, dense=70, dout=0.15, dense_reg = 0.000001, act='elu', )
Tabular Playground Series - Jan 2021
14,589,590
final_col = X_train['TransactionID'] X_train = X_train.drop(columns=['TransactionID'] )<feature_engineering>
print('Save Out of Fold Predictions') oof = pd.DataFrame(columns=['oof_prediction'], index=train['id'], data=oof + TARGET_MEAN) oof.to_csv('oof_predictions.csv', index=True) oof.head(10 )
Tabular Playground Series - Jan 2021
14,589,590
START_DATE = datetime.datetime.strptime('2017-11-30', '%Y-%m-%d') X_train['DT_M'] = X_train['TransactionDT'].apply(lambda x:(START_DATE + datetime.timedelta(seconds = x))) X_train['DT_M'] =(X_train['DT_M'].dt.year-2017)*12 + X_train['DT_M'].dt.month X_test['DT_M'] = X_test['TransactionDT'].apply(lambda x:(START_DATE ...
print('fold errors', fold_errors) print('fold error std', np.array(fold_errors ).std() )
Tabular Playground Series - Jan 2021
14,589,590
cols = list(X_train.columns) cols.remove('TransactionDT' )<define_variables>
submission['target'] = test_predictions + TARGET_MEAN submission.to_csv('submission.csv', index=False) submission.head(5 )
Tabular Playground Series - Jan 2021
14,579,645
idxT = X_train.index[:3*len(X_train)//4] idxV = X_train.index[3*len(X_train)//4:]<train_on_grid>
import numpy as np import pandas as pd from math import sqrt from xgboost import XGBRegressor from lightgbm import LGBMRegressor from sklearn.impute import SimpleImputer from sklearn.ensemble import VotingRegressor from sklearn.feature_selection import VarianceThreshold from sklearn.metrics import make_scorer, mean_squ...
Tabular Playground Series - Jan 2021
14,579,645
oof = np.zeros(len(X_train)) preds = np.zeros(len(X_test)) skf = GroupKFold(n_splits=6) for i,(idxT, idxV)in enumerate(skf.split(X_train, y_train, groups=X_train['DT_M'])) : month = X_train.iloc[idxV]['DT_M'].iloc[0] print('Fold',i,'withholding month',month) print(' rows of train =',len(idxT),'rows of holdout =',len(...
RANDOM_STATE = 2021 CROSS_VALIDATION = 3
Tabular Playground Series - Jan 2021
14,579,645
def encode_FE(df1, df2, cols): for col in cols: df = pd.concat([df1[col],df2[col]]) vc = df.value_counts(dropna=True, normalize=True ).to_dict() vc[-1] = -1 nm = col+'_FE' df1[nm] = df1[col].map(vc) df1[nm] = df1[nm].astype('float32') df2[nm] = df2[col].map(vc) df2[nm] = df2[nm].astype('float32') print(nm,', ',end...
data_dir = '/kaggle/input/tabular-playground-series-jan-2021'
Tabular Playground Series - Jan 2021
14,579,645
encode_CB('card1','addr1') X_train['day'] =X_train.TransactionDT /(24*60*60) X_train['uid'] = X_train.card1_addr1.astype(str)+'_'+np.floor(X_train.day-X_train.D1 ).astype(str) X_test['day'] = X_test.TransactionDT /(24*60*60) X_test['uid'] =X_test.card1_addr1.astype(str)+'_'+np.floor(X_test.day-X_test.D1 ).astype(st...
df = pd.read_csv(f"{data_dir}/train.csv" ).set_index('id' ).convert_dtypes() display(df.shape) df.head(2 )
Tabular Playground Series - Jan 2021
14,579,645
%%time X_train['cents'] =(X_train['TransactionAmt'] - np.floor(X_train['TransactionAmt'])).astype('float32') X_test['cents'] =(X_test['TransactionAmt'] - np.floor(X_test['TransactionAmt'])).astype('float32') encode_FE(X_train,X_test,['uid']) encode_AG(['TransactionAmt','D4','D9','D10','D15'],['uid'],['mean','std'],f...
X = df.copy() y = X.pop('target') X_train, X_valid, y_train, y_valid = train_test_split( X, y, train_size=0.8, test_size=0.2, random_state=RANDOM_STATE, )
Tabular Playground Series - Jan 2021
14,579,645
for i in range(1,16): if i in [1,2,3,5,9]: continue X_train['D'+str(i)] = X_train['D'+str(i)] - X_train.TransactionDT/np.float32(24*60*60) X_test['D'+str(i)] = X_test['D'+str(i)] - X_test.TransactionDT/np.float32(24*60*60 )<drop_column>
preprocessor = Pipeline(steps=[ ('imputer', SimpleImputer()), ('log', FunctionTransformer(np.log1p)) , ('scaler', StandardScaler()), ] )
Tabular Playground Series - Jan 2021
14,579,645
cols = list(X_train.columns) cols.remove('TransactionDT') for c in ['DT_M','day','uid']: cols.remove(c) <prepare_x_and_y>
pipeline = Pipeline([ ('preprocessor', preprocessor), ('variance_drop', VarianceThreshold(threshold=(0.95 *(1 - 0.95)))) , ('voting', 'passthrough'), ] )
Tabular Playground Series - Jan 2021
14,579,645
idxT = X_train.index[:3*len(X_train)//4] idxV = X_train.index[3*len(X_train)//4:]<drop_column>
parameters = [ { 'voting': [VotingRegressor([ ('lgbm', LGBMRegressor(random_state=RANDOM_STATE)) , ('xgb', XGBRegressor(random_state=RANDOM_STATE)) ])], 'voting__lgbm__n_estimators': [2000], 'voting__lgbm__max_depth': [12], 'voting__lgbm__learning_rate': [0.01], 'voting__lgbm__num_leaves': [256], 'voting__lgbm__min_c...
Tabular Playground Series - Jan 2021
14,579,645
X_train = X_train.drop(columns=['uid'] )<define_variables>
total = CROSS_VALIDATION * len(ParameterGrid(parameters)) display(f"Number of combination that will be run by the GridSearch: {total}" )
Tabular Playground Series - Jan 2021
14,579,645
idxT = X_train.index[:3*len(X_train)//4] idxV = X_train.index[3*len(X_train)//4:]<train_on_grid>
custom_scoring = make_scorer( score_func=lambda y, y_pred: mean_squared_error(y, y_pred, squared=False), greater_is_better=False, )
Tabular Playground Series - Jan 2021
14,579,645
oof = np.zeros(len(X_train)) preds = np.zeros(len(X_test)) skf = GroupKFold(n_splits=6) for i,(idxT, idxV)in enumerate(skf.split(X_train, y_train, groups=X_train['DT_M'])) : month = X_train.iloc[idxV]['DT_M'].iloc[0] print('Fold',i,'withholding month',month) print(' rows of train =',len(idxT),'rows of holdout =',len(...
grid_search = GridSearchCV( pipeline, param_grid=parameters, cv=CROSS_VALIDATION, scoring=custom_scoring, n_jobs=-1, verbose=True, )
Tabular Playground Series - Jan 2021
14,579,645
test_transaction = pd.read_csv('/kaggle/input/ieee-fraud-detection/test_transaction.csv') final_col = test_transaction['TransactionID']<save_to_csv>
grid_search.fit(X_train, y_train )
Tabular Playground Series - Jan 2021
14,579,645
my_submission = pd.DataFrame({'TransactionID':final_col, 'isFraud': preds}) my_submission.to_csv('./submission.csv', index=False) my_submission.head(5 )<import_modules>
display(abs(grid_search.best_score_)) display(grid_search.best_params_ )
Tabular Playground Series - Jan 2021
14,579,645
print(tf.__version__ )<feature_engineering>
preds = grid_search.best_estimator_.predict(X_valid) mean_squared_error(y_valid, preds, squared=False )
Tabular Playground Series - Jan 2021
14,579,645
TRAIN_PREFIX = '.. /input/fish-data/fish/train' def load_annotations() : boxes = dict() for path in tqdm(glob('.. /input/fish-data/fish/boxes/*.json')) : label = os.path.basename(path ).split('_', 1)[0] with open(path)as src: for annotation in json.load(src): basename = os.path.basename(annotation['filename']) annotat...
X_test = pd.read_csv(f"{data_dir}/test.csv" ).set_index('id' ).convert_dtypes() display(X_test.shape) X_test.head(2 )
Tabular Playground Series - Jan 2021
14,579,645
<create_dataframe><EOS>
preds_test = grid_search.best_estimator_.predict(X_test) output = pd.DataFrame( {'Id': X_test.index, 'target': preds_test}) output.to_csv(f"submission.csv", index=False )
Tabular Playground Series - Jan 2021
14,044,928
<SOS> metric: RMSE Kaggle data source: tabular-playground-series-jan-2021<init_hyperparams>
!pip install pytorch_tabular !pip install torch_optimizer
Tabular Playground Series - Jan 2021
14,044,928
IMG_HEIGHT = 736 IMG_WIDTH = 1184 features = VGG16(weights='imagenet', include_top=False, input_shape=(IMG_HEIGHT, IMG_WIDTH, 3)) for layer in features.layers[:-5]: layer.trainable = False feature_tensor = features.layers[-1].output print(feature_tensor.shape )<define_variables>
import numpy as np import pandas as pd import time import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import KFold from sklearn.metrics import mean_squared_error from sklearn.preprocessing import StandardScaler from pytorch_tabular import TabularModel from pytorch_tabular.models import C...
Tabular Playground Series - Jan 2021
14,044,928
FEATURE_SHAPE =(feature_tensor.shape[1], feature_tensor.shape[2]) print(FEATURE_SHAPE) GRID_STEP_H = IMG_HEIGHT / FEATURE_SHAPE[0] GRID_STEP_W = IMG_WIDTH / FEATURE_SHAPE[1] ANCHOR_WIDTH = 150. ANCHOR_HEIGHT = 150. ANCHOR_CENTERS = np.mgrid[GRID_STEP_H/2:IMG_HEIGHT:GRID_STEP_H, GRID_STEP_W/2:IMG_WIDTH:GRID_STEP_W] ...
df_train = pd.read_csv('.. /input/tabular-playground-series-jan-2021/train.csv') display(df_train.head()) df_test = pd.read_csv('.. /input/tabular-playground-series-jan-2021/test.csv') display(df_test.head()) features = ['cont1', 'cont2', 'cont3', 'cont4', 'cont5', 'cont6', 'cont7', 'cont8', 'cont9', 'cont10', 'con...
Tabular Playground Series - Jan 2021
14,044,928
num_classes = counts.shape[0] num_classes<import_modules>
enc = KBinsDiscretizer(n_bins=10, encode='ordinal', strategy="quantile") enc.fit(df_train[features]) binned_df_train = enc.transform(df_train[features]) binned_df_test = enc.transform(df_test[features]) for i, feature in enumerate(features): df_train[f"{feature}_binned"] = binned_df_train[:,i] df_test[f"{feature}_b...
Tabular Playground Series - Jan 2021
14,044,928
from scipy.special import softmax<normalization>
def get_configs(train): epochs = 25 batch_size = 512 steps_per_epoch = int(( len(train)//batch_size)*0.9) data_config = DataConfig( target=['target'], continuous_cols=['cont1', 'cont2', 'cont3', 'cont4', 'cont5', 'cont6', 'cont7', 'cont8', 'cont9', 'cont10', 'cont11', 'cont12', 'cont13', 'cont14'], categorical_cols=[...
Tabular Playground Series - Jan 2021
14,044,928
def iou(rect, x_scale, y_scale, anchor_x, anchor_y, anchor_w=ANCHOR_WIDTH, anchor_h=ANCHOR_HEIGHT): rect_x1 =(rect['x'] - rect['width'] / 2)* x_scale rect_x2 =(rect['x'] + rect['width'] / 2)* x_scale rect_y1 =(rect['y'] - rect['height'] / 2)* y_scale rect_y2 =(rect['y'] + rect['height'] / 2)* y_scale anch_x1, anch_x2 =...
rnd_seed_cv = 1234 rnd_seed_reg = 1234 kf = KFold(n_splits=5, random_state=rnd_seed_cv, shuffle=True) df_train.drop(columns='id', inplace=True) df_test.drop(columns='id', inplace=True) df_test['target'] = 0
Tabular Playground Series - Jan 2021
14,044,928
annotation = boxes['shark'][3] encoded = encode_anchors(annotation, img_shape=(IMG_HEIGHT, IMG_WIDTH), iou_thr=0.1) decoded = decode_prediction(encoded, conf_thr=0.7) decoded = sorted(decoded, key = lambda e: -e['conf']) plt.figure(figsize=(6, 6), dpi=240) plt.imshow(draw_boxes(annotation, decoded)) plt.title('{} {...
def node(train, valid, df_test): data_config, trainer_config, optimizer_config, model_config = get_configs(train) tabular_model = TabularModel( data_config=data_config, model_config=model_config, optimizer_config=optimizer_config, trainer_config=trainer_config ) tabular_model.fit(train=train, validation=valid, opti...
Tabular Playground Series - Jan 2021
14,044,928
K = tf.keras.backend def confidence_loss(y_true, y_pred): conf_loss = K.binary_crossentropy(y_true[..., 6], y_pred[..., 6], from_logits=True) return conf_loss def smooth_l1(y_true, y_pred): abs_loss = K.abs(y_true[..., -4:] - y_pred[..., -4:]) square_loss = 0.5 * K.square(y_true[..., -4:] - y_pred[..., -4:]) mask = ...
CV_node = [] CV_lgb = [] CV_cb = [] preds_train_node = [] preds_train_lgb = [] preds_train_cb = [] preds_test_node = [] preds_test_lgb = [] preds_test_cb = [] cross_validated_preds = [] t1 = time.time() for train_index, test_index in kf.split(df_train): train = df_train.iloc[train_index] valid = df_train.iloc[test_inde...
Tabular Playground Series - Jan 2021
14,044,928
def load_img(path, target_size=(IMG_WIDTH, IMG_HEIGHT)) : img = cv2.imread(path, cv2.IMREAD_COLOR)[...,::-1] img_shape = img.shape img_resized = cv2.resize(img, target_size) return img_shape, tf.keras.applications.resnet_v2.preprocess_input(img_resized.astype(np.float32)) def data_generator(boxes, batch_size=32): boxe...
print('CV performance [RMSE]: ', np.mean(CV_node, axis=0)) print('CV performance [RMSE]: ', np.mean(CV_lgb, axis=0)) print('CV performance [RMSE]: ', np.mean(CV_cb, axis=0))
Tabular Playground Series - Jan 2021
14,044,928
output = tf.keras.layers.BatchNormalization()(feature_tensor) output = tf.keras.layers.Conv2D(11, kernel_size=(1, 1), activation='linear', kernel_regularizer='l2' )(output) model = tf.keras.models.Model(inputs=features.inputs, outputs=output) <define_search_space>
cross_val_pred_df = pd.concat(cross_validated_preds, sort=False) cross_val_pred_df.to_csv("cross_val_preds.csv") joblib.dump(preds_test_node, "preds_test_node.sav") joblib.dump(preds_test_lgb, "preds_test_lgb.sav") joblib.dump(preds_test_cb, "preds_test_cb.sav" )
Tabular Playground Series - Jan 2021
14,044,928
lr=3e-3<choose_model_class>
avg_cb_pred = np.mean(preds_test_cb, axis=0) avg_lgb_pred = np.mean(preds_test_lgb, axis=0) avg_node_pred = np.mean(preds_test_node, axis=0) pred_test = np.average([avg_node_pred, avg_lgb_pred, avg_cb_pred], axis=0, weights=[-0.15447081, 1.1021915 , 0.06145868] )
Tabular Playground Series - Jan 2021
14,044,928
def lr_exp_decay(epoch, lr): k = 0.5 return lr * np.exp(-k*epoch) batch_size = 32 steps_per_epoch = sum(map(len, boxes.values()), 0)/ batch_size gen = data_generator(boxes, batch_size=batch_size) checkpoint = tf.keras.callbacks.ModelCheckpoint( 'fishdetector.hdf5', monitor='loss', verbose=47, save_best_only=True, sa...
df_sub = pd.read_csv('.. /input/tabular-playground-series-jan-2021/sample_submission.csv') df_sub.target = pred_test df_sub.head()
Tabular Playground Series - Jan 2021
14,044,928
model.fit(gen, steps_per_epoch=steps_per_epoch, epochs=2, callbacks=[checkpoint, tf.keras.callbacks.LearningRateScheduler(lr_exp_decay, verbose=1)] )<predict_on_test>
df_sub.to_csv('submission.csv', index=False )
Tabular Playground Series - Jan 2021
14,038,334
test_images = glob('.. /input/fish-data/test_stg1/test_stg1/*.jpg')[:4] plt.figure(figsize=(6, 4 * len(test_images)) , dpi=240) for i, filename in enumerate(test_images): _, sample_img = load_img(filename) pred = model.predict(np.array([sample_img,])) decoded = decode_prediction(pred[0], conf_thr=0.1) decoded = non_...
train = pd.read_csv('/kaggle/input/tabular-playground-series-jan-2021/train.csv', index_col='id') test = pd.read_csv('/kaggle/input/tabular-playground-series-jan-2021/test.csv', index_col='id' )
Tabular Playground Series - Jan 2021
14,038,334
def make_predictions() : ptable = pd.DataFrame(columns=['image', 'ALB', 'BET', 'DOL', 'LAG', 'NoF', 'OTHER', 'SHARK','YFT']) for i, file in enumerate(tqdm(glob('.. /input/fish-data/test_stg1/test_stg1/*.jpg'))): bn = os.path.basename(file) _, sample_img = load_img(file) pred = model.predict(np.array([sample_img,])) ...
import seaborn as sns
Tabular Playground Series - Jan 2021
14,038,334
pred_table = make_predictions() pred_table.to_csv("neto_submit.csv", index=False) print(os.listdir("./"))<import_modules>
train[train['target'] <= 4.5]
Tabular Playground Series - Jan 2021
14,038,334
import numpy as np import pandas as pd import six import time from random import randint import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split from skimage.transform import resize from keras import Model from keras.callbacks import EarlyStopping, ModelCheckpoint, Red...
train.drop([241352, 284103, 300936, 307139, 355831], axis = 0, inplace=True) train[train['target'] <= 4.5]
Tabular Playground Series - Jan 2021
14,038,334
! unzip -q.. /input/tgs-salt-identification-challenge/train.zip -d train/ ! unzip -q.. /input/tgs-salt-identification-challenge/test.zip -d test/<load_from_csv>
target = train['target'] train.drop('target', axis=1, inplace=True )
Tabular Playground Series - Jan 2021
14,038,334
train = pd.read_csv(".. /input/tgs-salt-identification-challenge/train.csv") depths = pd.read_csv(".. /input/tgs-salt-identification-challenge/depths.csv") sub = pd.read_csv(".. /input/tgs-salt-identification-challenge/sample_submission.csv") image_path = "/kaggle/working/train/images/" mask_path = "/kaggle/working/...
X_train, X_valid, y_train, y_valid = train_test_split(train, target, test_size=0.15, random_state=0 )
Tabular Playground Series - Jan 2021
14,038,334
train = train[['id']].join(depths.set_index('id'), on='id') test = sub[['id']].join(depths.set_index('id'), on='id' )<feature_engineering>
lgbm = LGBMRegressor(tree_method='gpu_hist',learning_rate=0.07, max_depth=15, random_state=0, n_estimators=2000, n_jobs=-1) lgbm.fit(X_train, y_train, eval_set=[(X_valid, y_valid)]) lgbm.score(X_valid, y_valid )
Tabular Playground Series - Jan 2021
14,038,334
train["images"] = [np.array(load_img(image_path+"{}.png".format(idx), color_mode="grayscale"), dtype=np.uint8)/ 255 for idx in tqdm(train.id)] train["masks"] = [np.array(load_img(mask_path+"{}.png".format(idx), color_mode="grayscale"), dtype=np.uint8)/ 255 for idx in tqdm(train.id)]<feature_engineering>
xgb = XGBRegressor(learning_rate=0.005, max_depth=8, n_estimators=6000, n_jobs=-1, tree_method='gpu_hist', random_state=3) xgb.fit(X_train, y_train, eval_set=[(X_valid, y_valid)]) xgb.score(X_valid, y_valid )
Tabular Playground Series - Jan 2021
14,038,334
train["coverage"] = train.masks.map(np.sum)/ pow(img_size, 2 )<categorify>
ensemble = VotingRegressor(estimators=[("xgb", xgb),("lgbm", lgbm)], weights=[1.1,1]) ensemble.fit(X_train, y_train) ensemble.score(X_valid, y_valid )
Tabular Playground Series - Jan 2021
14,038,334
def cov_to_class(val): for i in range(0, 11): if val * 10 <= i : return i train["coverage_class"] = train.coverage.map(cov_to_class )<split>
model = ensemble.fit(train, target) model.score(train, target )
Tabular Playground Series - Jan 2021
14,038,334
ids_train, ids_valid, x_train, x_valid, y_train, y_valid, cover_train, cover_test, depth_train, depth_test = train_test_split( train.id.values, np.array(train.images.tolist() ).reshape(-1,img_size, img_size, 1), np.array(train.masks.tolist() ).reshape(-1, img_size, img_size, 1), train.coverage.values, train.z.values, ...
pred = model.predict(test) pred
Tabular Playground Series - Jan 2021
14,038,334
x_train = np.append(x_train, [np.fliplr(x)for x in x_train], axis=0) y_train = np.append(y_train, [np.fliplr(x)for x in y_train], axis=0 )<define_search_model>
id = pd.read_csv('/kaggle/input/tabular-playground-series-jan-2021/test.csv')['id']
Tabular Playground Series - Jan 2021
14,038,334
<choose_model_class><EOS>
output = pd.DataFrame({'id': id, 'target': pred}) output.to_csv("submission.csv", index=False) print("saved" )
Tabular Playground Series - Jan 2021
14,481,856
<SOS> metric: RMSE Kaggle data source: tabular-playground-series-jan-2021<choose_model_class>
for dirname, _, filenames in os.walk('/kaggle/input'): for filename in filenames: print(os.path.join(dirname, filename)) input_path = Path('/kaggle/input/tabular-playground-series-jan-2021/' )
Tabular Playground Series - Jan 2021
14,481,856
def _bn_relu(input): norm = BatchNormalization(axis=CHANNEL_AXIS )(input) return Activation("relu" )(norm) def _conv_bn_relu(**conv_params): filters = conv_params["filters"] kernel_size = conv_params["kernel_size"] strides = conv_params.setdefault("strides",(1, 1)) kernel_initializer = conv_params.setdefault("ker...
train = pd.read_csv(input_path / 'train.csv', index_col='id') print(train.shape) train.head()
Tabular Playground Series - Jan 2021
14,481,856
def get_iou_vector(A, B): batch_size = A.shape[0] metric = [] for batch in range(batch_size): t, p = A[batch], B[batch] intersection = np.logical_and(t, p) union = np.logical_or(t, p) iou =(np.sum(intersection > 0)+ 1e-10)/(np.sum(union > 0)+ 1e-10) thresholds = np.arange(0.5, 1, 0.05) s = [] for thresh in threshol...
test = pd.read_csv(input_path / 'test.csv', index_col='id') print(test.shape) test.head()
Tabular Playground Series - Jan 2021
14,481,856
def UResNet34(input_shape=(128, 128, 1), classes=1, decoder_filters=16, decoder_block_type='upsampling', encoder_weights="imagenet", input_tensor=None, activation='sigmoid', **kwargs): backbone = ResnetBuilder.build_resnet_34(input_shape=input_shape,input_tensor=input_tensor) input_layer = backbone.input output_layer ...
train.isnull().sum()
Tabular Playground Series - Jan 2021
14,481,856
model1 = UResNet34(input_shape =(1,img_size,img_size)) model1.summary()<choose_model_class>
trainNorm = train.copy() for feature_name in train.columns: mean_value = train[feature_name].mean() std_value = train[feature_name].std() trainNorm[feature_name] =(train[feature_name] - mean_value)/ std_value trainNorm.head()
Tabular Playground Series - Jan 2021
14,481,856
early_stopping = EarlyStopping(monitor='my_iou_metric', mode = 'max',patience=10, verbose=1) model_checkpoint = ModelCheckpoint(model_path,monitor='my_iou_metric', mode = 'max', save_best_only=True, verbose=1) reduce_lr = ReduceLROnPlateau(monitor='my_iou_metric', mode = 'max',factor=0.5, patience=5, min_lr=0.0001, v...
testNorm = test.copy() for feature_name in test.columns: mean_value = test[feature_name].mean() std_value = test[feature_name].std() testNorm[feature_name] =(test[feature_name] - mean_value)/ std_value testNorm.head()
Tabular Playground Series - Jan 2021
14,481,856
model1 = load_model(model_path,custom_objects={'my_iou_metric': my_iou_metric}) input_x = model1.layers[0].input output_layer = model1.layers[-1].input model = Model(input_x, output_layer) model.compile(loss=lovasz_loss, optimizer='adam', metrics=[my_iou_metric_2]) model.summary()<choose_model_class>
X_train, X_test, y_train, y_test = train_test_split(trainNorm, target, test_size=0.2, random_state=7) print('X_train: ', X_train.shape) print('X_test: ', X_test.shape) print('y_train: ', y_train.shape) print('y_test: ', y_test.shape )
Tabular Playground Series - Jan 2021
14,481,856
early_stopping = EarlyStopping(monitor='val_my_iou_metric_2', mode = 'max',patience=20, verbose=1) model_checkpoint = ModelCheckpoint(model_path,monitor='val_my_iou_metric_2', mode = 'max', save_best_only=True, verbose=1) reduce_lr = ReduceLROnPlateau(monitor='val_my_iou_metric_2', mode = 'max',factor=0.5, patience=5...
def rmse_cv(model,X,y): rmse = np.sqrt(-cross_val_score(model, X, y, scoring="neg_mean_squared_error", cv=5)) return rmse
Tabular Playground Series - Jan 2021
14,481,856
def predict_result(model,x_test,img_size): x_test_reflect = np.array([np.fliplr(x)for x in x_test]) preds_test = model.predict(x_test ).reshape(-1, img_size, img_size) preds_test2_refect = model.predict(x_test_reflect ).reshape(-1, img_size, img_size) preds_test += np.array([ np.fliplr(x)for x in preds_test2_refect]...
models = [LinearRegression() , Ridge() , Lasso() , ElasticNet() , SGDRegressor() , BayesianRidge() , cb.CatBoostRegressor() , RandomForestRegressor() , ] names = ["LR", "Ridge", "Lasso", "ElasticNet", "SGD","BayesianRidge", "catboost","RandomForestRegressor"]
Tabular Playground Series - Jan 2021
14,481,856
model = load_model(model_path,custom_objects={'my_iou_metric_2': my_iou_metric_2, 'lovasz_loss': lovasz_loss}) preds_valid = predict_result(model,x_valid,img_size )<compute_train_metric>
%%time ModScores = {} for name, model in zip(names, models): score = rmse_cv(model, X_train, y_train) ModScores[name] = score.mean() print("{}: {:.2f}".format(name,score.mean())) print("_"*100) for key, value in sorted(ModScores.items() , key = itemgetter(1), reverse = False): print(key, round(value,3))
Tabular Playground Series - Jan 2021
14,481,856
thresholds_ori = np.linspace(0.3, 0.7, 31) thresholds = np.log(thresholds_ori/(1-thresholds_ori)) ious = np.array([iou_metric_batch(y_valid, preds_valid > threshold)for threshold in tqdm(thresholds)]) print(ious )<categorify>
model = cb.CatBoostRegressor() model.fit(X_train, y_train) final_predictions = model.predict(X_test) final_mse = mean_squared_error(y_test, final_predictions) final_rmse = np.sqrt(final_mse) print("RMSE on X_test ", round(final_rmse, 4))
Tabular Playground Series - Jan 2021
14,481,856
def rle_encode(im): pixels = im.flatten(order = 'F') pixels = np.concatenate([[0], pixels, [0]]) runs = np.where(pixels[1:] != pixels[:-1])[0] + 1 runs[1::2] -= runs[::2] return ' '.join(str(x)for x in runs )<predict_on_test>
final_predictions = model.predict(testNorm) final_predictions.shape subm = pd.read_csv(input_path / 'sample_submission.csv') print(subm.shape) subm.head() id_col=subm.id subm=id_col.to_frame() subm['target'] = final_predictions subm.set_index('id',inplace=True) subm.head() subm.to_csv('CBSubmission.csv') LoadSub =...
Tabular Playground Series - Jan 2021
14,481,856
preds_test = predict_result(model,x_test,img_size) t1 = time.time() pred_dict = {idx: rle_encode(np.round(preds_test[i])> threshold_best)for i, idx in enumerate(tqdm(test.id.values)) } t2 = time.time() print(f"Usedtime = {t2-t1} s" )<save_to_csv>
model = models.Sequential() model.add(layers.Dense(512, activation='relu', input_shape=(X_train.shape[1],))) model.add(layers.Dense(256, activation='relu')) model.add(layers.Dropout(0.2)) model.add(layers.Dense(64, activation='relu')) model.add(layers.Dense(1)) model.summary() model.compile(optimizer=optimizers.Adam()...
Tabular Playground Series - Jan 2021
14,481,856
submit = pd.DataFrame.from_dict(pred_dict,orient='index') submit.index.names = ['id'] submit.columns = ['rle_mask'] submit.to_csv(submission_file )<load_from_csv>
history = model.fit(X_train, y_train, validation_split=0.2, verbose=1, epochs=10 )
Tabular Playground Series - Jan 2021
14,481,856
train = pd.read_csv('.. /input/digit-recognizer/train.csv') test = pd.read_csv('.. /input/digit-recognizer/test.csv' )<prepare_x_and_y>
final_predictions = model.predict(X_test) final_mse = mean_squared_error(y_test, final_predictions) final_rmse = np.sqrt(final_mse) print("RMSE on X_test ", round(final_rmse, 4))
Tabular Playground Series - Jan 2021
14,481,856
x_train = train.drop('label', axis=1)/255.0 y_label = train['label'].values x_test = test/255.0<define_variables>
final_predictions = model.predict(testNorm) final_predictions.shape
Tabular Playground Series - Jan 2021
14,481,856
datagen = ImageDataGenerator( rotation_range=15, zoom_range = 0.1, width_shift_range=0.1, height_shift_range=0.1, )<import_modules>
subm = pd.read_csv(input_path / 'sample_submission.csv') print(subm.shape) subm.head()
Tabular Playground Series - Jan 2021
14,481,856
import tensorflow as tf<choose_model_class>
id_col=subm.id subm=id_col.to_frame() subm['target'] = final_predictions subm.set_index('id',inplace=True) subm.head()
Tabular Playground Series - Jan 2021
14,481,856
class ResidualUnit(tf.keras.layers.Layer): def __init__(self, filters, strides=1, activation='relu', **kwargs): super().__init__(**kwargs) self.activation = tf.keras.activations.get(activation) self.main_layers = [ tf.keras.layers.Conv2D(filters, 3, strides=strides, padding='SAME', use_bias=False), tf.keras.layers.Ba...
subm.to_csv('NNSubmission.csv' )
Tabular Playground Series - Jan 2021
14,445,592
model = tf.keras.models.Sequential() model.add(tf.keras.layers.Conv2D(64,(7,7), input_shape=(28, 28, 1), padding='SAME')) model.add(tf.keras.layers.BatchNormalization()) model.add(tf.keras.layers.Activation('relu')) model.add(tf.keras.layers.MaxPooling2D(2, 2)) prev_filters = 64 for filters in [64]*2 + [128]*2 + [256]...
import plotly.express as px import plotly.graph_objects as go import plotly.figure_factory as ff from plotly.subplots import make_subplots import matplotlib.pyplot as plt from pandas_profiling import ProfileReport import seaborn as sns from sklearn import metrics from scipy import stats from copy import deepcopy from s...
Tabular Playground Series - Jan 2021