Kaggle competition: Digit Recognizer
<SOS> metric: categorizationaccuracy Kaggle data source: digit-recognizer<choose_model_class>
train = pd.read_csv(".. /input/digit-recognizer/train.csv")
 test = pd.read_csv(".. /input/digit-recognizer/test.csv" )
if __name__ == '__main__':
all_seed(CFG['seed'])
 folds = StratifiedKFold(n_splits=CFG['fold_num'] ).split(np.arange(train.shape[0]), train.label.values)
 for fold,(trn_idx, val_idx)in enumerate(folds):
if fold > 0:
break
print('Inference fold {} started'.format(fold))
valid_ = train.loc[val_idx,:].reset_index(drop=True)
 valid_ds = CassavaDataset(valid_, '.. /input/cassava-leaf-disease-classification/train_images/',
transforms = get_inference_transforms() , output_label=False)
 test = pd.DataFrame()
test['image_id'] = list(os.listdir('.. /input/cassava-leaf-disease-classification/test_images/'))
test_ds = CassavaDataset(test, '.. /input/cassava-leaf-disease-classification/test_images/',
transforms = get_inference_transforms() , output_label=False)
 val_loader = torch.utils.data.DataLoader(
 valid_ds,
batch_size = CFG['valid_bs'],
num_workers = CFG['num_workers'],
shuffle = False,
pin_memory = False, 
)
 tst_loader = torch.utils.data.DataLoader(
 test_ds,
batch_size = CFG['valid_bs'],
num_workers = CFG['num_workers'],
shuffle = False,
pin_memory = False, 
)
 device = torch.device(CFG['device'])
 model = EnsembleClassifier(CFG['model_arch'], train.label.nunique() ).to(device)
 val_preds = []
tst_preds = []
for i, epoch in enumerate(CFG['used_epochs']):
model.load(torch.load('.. /input/fork-pytorch-efficientnet-baseline-train-amp-a/{}_fold_{}_{}'.format(CFG['model_arch'], fold, epoch)))
 with torch.no_grad() :
for _ in range(CFG['tta']):
val_preds += [CFG['weights'][i]/sum(CFG['weights'])/CFG['tta']*inference_one_epoch(model, val_loader, device)]
tst_preds += [CFG['weights'][i]/sum(CFG['weights'])/CFG['tta']*inference_one_epoch(model, tst_loader, device)]
val_preds = np.mean(val_preds, axis=0)
 tst_preds = np.mean(tst_preds, axis=0)
 print('fold {} validation loss = {:.5f}'.format(fold, log_loss(valid_.label.values, val_preds)))
 print('fold {} validation accuracy = {:.5f}'.format(fold,(valid_.label.values==np.argmax(val_preds, axis=1)).mean()))
del model
torch.cuda.empty_cache()<feature_engineering>
X_train = train.drop(labels=["label"], axis=1)
 Y_train = train['label']
del train
X_train = X_train / 255.
 test = test / 255.
 X_train = X_train.values.reshape(-1, 28, 28, 1)
 test = test.values.reshape(-1, 28, 28, 1)
test['label'] = np.argmax(tst_preds, axis=1)
 test.head()<save_to_csv>
X_train, X_val, Y_train, Y_val = train_test_split(
 X_train,
Y_train,
test_size=0.1,
random_state=42
)
test.to_csv('submission.csv', index = False )<define_variables>
datagen = ImageDataGenerator(
 rotation_range=10,
zoom_range=(1.15, 0.95),
width_shift_range=0.1,
height_shift_range=0.1,
horizontal_flip=False,
vertical_flip=False,
shear_range=5
)
package_paths = [
'.. /input/pytorch-image-models/pytorch-image-models-master',
'.. /input/adamp-optimizer/AdamP-master/adamp'
]
for pth in package_paths:
sys.path.append(pth )<import_modules>
init = RandomNormal(stddev=0.02)
 model = Sequential([
Conv2D(32, 3, input_shape=(28, 28, 1), activation='relu', kernel_initializer=init),
BatchNormalization() ,
Conv2D(32, 3, activation='relu', kernel_initializer=init),
BatchNormalization() ,
Conv2D(32, 5, strides=2, padding='same', activation='relu', kernel_initializer=init),
BatchNormalization() ,
Dropout(0.4),
Conv2D(64, 3, activation='relu', kernel_initializer=init),
BatchNormalization() ,
Conv2D(64, 3, activation='relu', kernel_initializer=init),
BatchNormalization() ,
Conv2D(64, 5, strides=2, padding='same', activation='relu', kernel_initializer=init),
BatchNormalization() ,
Dropout(0.4),
Conv2D(128, 4, activation='relu', kernel_initializer=init),
BatchNormalization() ,
Flatten() ,
Dropout(0.4),
Dense(10, activation='softmax')
 ])
 model.summary()
from glob import glob
from sklearn.model_selection import GroupKFold, StratifiedKFold
import cv2
from skimage import io
import torch
from torch import nn
import os
from datetime import datetime
import time
import random
import cv2
import torchvision
from torchvision import transforms
import pandas as pd
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
from torch.utils.data import Dataset,DataLoader
from torch.utils.data.sampler import SequentialSampler, RandomSampler
from torch.cuda.amp import autocast, GradScaler
from torch.nn.modules.loss import _WeightedLoss
import torch.nn.functional as F
import timm
import sklearn
import warnings
import joblib
from sklearn.metrics import roc_auc_score, log_loss
from sklearn import metrics
import warnings
import cv2
from scipy.ndimage.interpolation import zoom<set_options>
model.compile(
 optimizer=Adam(lr=1e-3),
loss='sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy']
)
CFG = {
'valid': False,
'fold_num': 5,
'seed': 719,
'model_arch1': 'tf_efficientnet_b4_ns',
'model_arch2': 'tf_efficientnet_b4_ns',
'model_arch3' : 'regnety_040',
'model_arch4' : 'regnety_040',
'model_arch5': 'tf_efficientnet_b4_ns',
'model_arch6': 'regnety_040',
'ckpt_path2': 'regnety4noresetadamp',
'ckpt_path3': 'regnety4nocv',
'weight' : [1/6 for _ in range(6)],
'img_size1': 512,
'img_size2': 512,
'img_size3': 512,
'img_size4': 512,
'epochs': 10,
'tta_num' : 3,
'train_bs': 64,
'valid_bs': 64,
'T_0': 10,
'lr': 1e-4,
'min_lr': 1e-6,
'weight_decay':1e-6,
'num_workers': 4,
'accum_iter': 2,
'verbose_step': 1,
'device': 'cuda:0',
'used_epochs': [5, 6, 7, 8, 9]
}<load_from_csv>
learning_rate_reduction = ReduceLROnPlateau(
 monitor='val_sparse_categorical_accuracy',
patience=3,
verbose=1,
factor=0.5,
min_lr=0.00001
)
train = pd.read_csv('.. /input/cassava-leaf-disease-classification/train.csv')
 train.head()<load_from_csv>
history = model.fit(
 datagen.flow(X_train, Y_train, batch_size=64),
epochs=45,
validation_data=(X_val, Y_val),
callbacks=[learning_rate_reduction],
use_multiprocessing=True
)
<set_options><EOS> 
results = model.predict(test)
 results = np.argmax(results, axis=1)
 submission = pd.concat([
pd.Series(range(1,28001), name="ImageId"),
pd.Series(results, name="Label")
 ], axis=1)
 submission.to_csv("submission.csv", index=False )