Kaggle competition: Cassava Leaf Disease Classification
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<define_variables>
sys.path = [
'.. /input/efficientnet-pytorch/EfficientNet-PyTorch/EfficientNet-PyTorch-master',
] + sys.path
sys.path = [
'.. /input/ttach-kaggle/ttach/',
] + sys.path
package_path = '.. /input/pytorch-image-models/pytorch-image-models-master'
sys.path.append(package_path )<import_modules>
warnings.filterwarnings('ignore' )
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
import sklearn
import warnings
import joblib
from sklearn.metrics import roc_auc_score, log_loss
from sklearn import metrics
import warnings
import cv2
import pydicom
import timm
from scipy.ndimage.interpolation import zoom
from sklearn.metrics import log_loss<init_hyperparams>
DIR_INPUT = '/kaggle/input/cassava-leaf-disease-classification'
DIR_WEIGHTS = '/kaggle/input/cassava-pytorch-starter-train'
SEED = 42
N_FOLDS = 1
BATCH_SIZE = 16
SIZE = 512
CROP = 512
init_lr = 5e-5
n_epochs = 5
CFG = {
'fold_num': 10,
'seed': 719,
'model_arch': 'tf_efficientnet_b3_ns',
'img_size': 384,
'epochs': 100,
'train_bs': 28,
'valid_bs': 32,
'lr': 1e-2,
'num_workers': 10,
'accum_iter': 1,
'verbose_step': 2,
'device': 'cuda:0',
'tta': 10,
'used_epochs': [6,7,8,9],
'weights': [1,1,1,1]
}<load_from_csv>
modelname="efficientnet-b0"
modelname2="efficientnet-b2"
class enetv2(nn.Module):
def __init__(self, out_dim=1, ModelName="efficientnet-b0"):
super(enetv2, self ).__init__()
self.basemodel = EfficientNet.from_name(ModelName)
 self.myfc = nn.Linear(self.basemodel._fc.in_features, out_dim)
 self.basemodel._fc = nn.Identity()
def extract(self, x):
return self.basemodel(x)
 def forward(self, x):
x = self.basemodel(x)
 x = self.myfc(x)
 return x
train = pd.read_csv('.. /input/cassava-leaf-disease-classification/train.csv')
 train.head()<count_values>
transforms_test = A.Compose([
A.Resize(height=SIZE, width=SIZE, p=1.0),
] )
train.label.value_counts()<load_from_csv>
submission_df = pd.read_csv(DIR_INPUT + '/sample_submission.csv')
 submission_df.iloc[:, 1] = 0
submission_df.head()
submission = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv')
 submission.head()<categorify>
if submission_df.shape[0] == 1:
submission_df = pd.DataFrame([{'image_id': '2216849948.jpg', 'label': 0},{'image_id': '2216849948.jpg', 'label': 0}])
 submission_df.reset_index(drop=True, inplace=True)
 commit = True
else:
commit = False
submission_df.head()
class CassavaDataset(Dataset):
def __init__(
 self, df, data_root, transforms=None, output_label=True 
):
super().__init__()
self.df = df.reset_index(drop=True ).copy()
self.transforms = transforms
self.data_root = data_root
self.output_label = output_label
def __len__(self):
return self.df.shape[0]
def __getitem__(self, index: int):
if self.output_label:
target = self.df.iloc[index]['label']
path = "{}/{}".format(self.data_root, self.df.iloc[index]['image_id'])
 img = get_img(path)
 if self.transforms:
img = self.transforms(image=img)['image']
if self.output_label == True:
return img, target
else:
return img<import_modules>
dataset_test = CassavaDataset(df=submission_df, dataset='test', transforms=transforms_test)
 dataloader_test = DataLoader(dataset_test, batch_size=BATCH_SIZE, num_workers=4, shuffle=False )
HorizontalFlip, VerticalFlip, IAAPerspective, ShiftScaleRotate, CLAHE, RandomRotate90,
Transpose, ShiftScaleRotate, Blur, OpticalDistortion, GridDistortion, HueSaturationValue,
IAAAdditiveGaussianNoise, GaussNoise, MotionBlur, MedianBlur, IAAPiecewiseAffine, RandomResizedCrop,
IAASharpen, IAAEmboss, RandomBrightnessContrast, Flip, OneOf, Compose, Normalize, Cutout, CoarseDropout, ShiftScaleRotate, CenterCrop, Resize 
)
 HorizontalFlip, VerticalFlip, IAAPerspective, ShiftScaleRotate, CLAHE, RandomRotate90,
Transpose, ShiftScaleRotate, Blur, OpticalDistortion, GridDistortion, HueSaturationValue,
IAAAdditiveGaussianNoise, GaussNoise, MotionBlur, MedianBlur, IAAPiecewiseAffine, RandomResizedCrop,
IAASharpen, IAAEmboss, RandomBrightnessContrast, Flip, OneOf, Compose, Normalize, Cutout, CoarseDropout, ShiftScaleRotate, CenterCrop, Resize 
)
 def get_train_transforms() :
return Compose([
RandomResizedCrop(CFG['img_size'], CFG['img_size']),
Transpose(p=0.5),
HorizontalFlip(p=0.5),
VerticalFlip(p=0.5),
ShiftScaleRotate(p=0.5),
HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=0.5),
RandomBrightnessContrast(brightness_limit=(-0.1,0.1), contrast_limit=(-0.1, 0.1), p=0.5),
Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),
CoarseDropout(p=0.5),
Cutout(p=0.5),
ToTensorV2(p=1.0),
], p=1.)
def get_valid_transforms() :
return Compose([
CenterCrop(CFG['img_size'], CFG['img_size'], p=1.) ,
Resize(CFG['img_size'], CFG['img_size']),
Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),
ToTensorV2(p=1.0),
], p=1.)
def get_inference_transforms() :
return Compose([
RandomResizedCrop(CFG['img_size'], CFG['img_size']),
Transpose(p=0.5),
HorizontalFlip(p=0.5),
VerticalFlip(p=0.5),
HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=0.5),
RandomBrightnessContrast(brightness_limit=(-0.1,0.1), contrast_limit=(-0.1, 0.1), p=0.5),
Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),
ToTensorV2(p=1.0),
], p=1.)<choose_model_class>
submissions = None
device = torch.device("cuda:0")if torch.cuda.is_available() else torch.device('cpu')
 for i_fold in range(N_FOLDS):
model = enetv2(5, modelname2 ).to(device)
 model.to(device)
 checkpoint2 = torch.load(f".. /input/cassavadata/efficientnet-b2_512_final_epoch10_fold0.pth", map_location=device)
 model.load_state_dict(checkpoint2)
 model.eval()
transforms = tta.Compose(
 [
tta.HorizontalFlip() ,
] 
)
 tta_models = []
for model in [model]:
tta_models.append(tta.ClassificationTTAWrapper(model, transforms))
for net in tta_models:
test_preds = None
for step, batch in enumerate(dataloader_test):
images = batch
images = images.to(device, dtype=torch.float)
 with torch.no_grad() :
outputs = net(images)
 preds = torch.softmax(outputs, dim=1 ).data.cpu()
if test_preds is None:
test_preds = preds
else:
test_preds = torch.cat(( test_preds, preds), dim=0)
 if submissions is None:
submissions = test_preds
else:
submissions += test_preds
class CassvaImgClassifier(nn.Module):
def __init__(self, model_arch, n_class, pretrained=False):
super().__init__()
self.model = timm.create_model(model_arch, pretrained=pretrained)
 n_features = self.model.classifier.in_features
self.model.classifier = nn.Linear(n_features, n_class)
 def forward(self, x):
x = self.model(x)
 return x
class EnsembleClassifier(nn.Module):
def __init__(self, model_arch, n_class, pretrained=False):
super().__init__()
self.model1 = VisionTransformer.from_name('ViT-B_16', num_classes=5)
 self.model1.load_state_dict(torch.load('.. /input/vit-model-1/ViT-B_16.pt'))
self.model2 = CassvaImgClassifier(model_arch, n_class, pretrained)
 def forward(self, x):
x1 = self.model1(x)
 x2 = self.model2(x)
 return 0.6 * x1 + 0.4 * x2
def load(self, state_dict):
self.model2.load_state_dict(state_dict )<split>
pl_df = pd.read_csv(DIR_INPUT + '/sample_submission.csv')
 if pl_df.shape[0] == 1:
pl_df = pd.DataFrame([{'image_id': '2216849948.jpg', 'label': 0},{'image_id': '2216849948.jpg', 'label': 0}])
 pl_df.reset_index(drop=True, inplace=True)
 pl_df['label'] = torch.argmax(submissions, dim=1)
 pl_df["pl"] = np.ones_like(torch.argmax(submissions, dim=1))
pl_df
if __name__ == '__main__':
seed_everything(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>
df_train = pd.read_csv(os.path.join(DIR_INPUT,"train.csv"))
df_train["pl"] = np.zeros_like(df_train["image_id"])
 df_train = pd.concat([df_train, pl_df] ).reset_index()
test['label'] = np.argmax(tst_preds, axis=1)
 test.head()<save_to_csv>
class CassavaDataset2(Dataset):
def __init__(self, df, dataset='train', transforms=None):
self.df = df
self.transforms=transforms
self.dataset=dataset
def __len__(self):
return self.df.shape[0]
def __getitem__(self, idx):
imageid = self.df.loc[idx, "image_id"]
label = self.df.loc[idx, "label"]
dir = self.df.loc[idx, "pl"]
if dir:
image_src = f'{DIR_INPUT}/test_images/{imageid}'
else:
image_src = f'{DIR_INPUT}/train_images/{imageid}'
image = cv2.imread(image_src)
 if self.transforms:
transformed = self.transforms(image=image)
 images = transformed['image']
images = images.astype(np.float32)
 images /= 255
images = images.transpose(2, 0, 1)
 return torch.tensor(images), torch.tensor(label)
 transforms_train = albumentations.Compose([
albumentations.ShiftScaleRotate(scale_limit=0.3, rotate_limit=180,p=0.5),
A.OneOf([
A.HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit= 0.2,
val_shift_limit=0.2, p=0.5),
A.RandomBrightnessContrast(brightness_limit=0.2,
contrast_limit=0.2, p=0.5),
],p=0.9),
A.Cutout(num_holes=12, max_h_size=64, max_w_size=64, fill_value=0, p=0.5),
albumentations.Rotate(p=0.5),
albumentations.Transpose(p=0.5),
albumentations.VerticalFlip(p=0.5),
albumentations.HorizontalFlip(p=0.5),
albumentations.Resize(SIZE, SIZE, p=1.0),
])
 dataset_train = CassavaDataset2(df=df_train, dataset='test', transforms=transforms_train)
 dataloader_train = DataLoader(dataset_train, batch_size=BATCH_SIZE, num_workers=4, shuffle=True)
 criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters() , lr=init_lr)
 scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, n_epochs )
test.to_csv('submission.csv', index=False )<define_variables>
scaler = torch.cuda.amp.GradScaler(enabled=False)
 def train_epoch(loader, optimizer):
model.train()
train_loss = []
bar = tqdm(loader)
 i = 0
for(data, target)in bar:
data, target = data.to(device), target.to(device ).long()
loss_func = criterion
optimizer.zero_grad()
with torch.cuda.amp.autocast(enabled=False):
logits = model(data ).squeeze(1)
 loss = loss_func(logits, target)
 scaler.scale(loss ).backward()
scaler.step(optimizer)
 scaler.update()
optimizer.zero_grad()
loss_np = loss.detach().cpu().numpy()
train_loss.append(loss_np)
 smooth_loss = sum(train_loss[-100:])/ min(len(train_loss), 100)
 bar.set_description('loss: %.5f, smth: %.5f' %(loss_np, smooth_loss))
i+=1
if commit and i==10:
break
return np.mean(train_loss )
tez_path = '.. /input/tez-lib/'
effnet_path = '.. /input/efficientnet-pytorch/'
timm_path = '.. /input/timm-pytorch-image-models/pytorch-image-models-master'
sys.path.append(tez_path)
 sys.path.append(effnet_path)
 sys.path.append(timm_path )<import_modules>
for epoch in range(1, n_epochs+1):
torch.cuda.empty_cache()
scheduler.step(epoch-1)
 train_loss = train_epoch(dataloader_train , optimizer )
import os
import albumentations
import pandas as pd
import numpy as np
import timm
import tez
from tez.datasets import ImageDataset
import torch
import torch.nn as nn
from torch.nn import functional as F
from tqdm import tqdm
from efficientnet_pytorch import EfficientNet<feature_engineering>
submissions = None
device = torch.device("cuda:0")if torch.cuda.is_available() else torch.device('cpu')
 for i_fold in range(N_FOLDS):
model.eval()
transforms = tta.Compose(
 [
tta.HorizontalFlip() ,
] 
)
 tta_models = []
for model in [model]:
tta_models.append(tta.ClassificationTTAWrapper(model, transforms))
for net in tta_models:
test_preds = None
for step, batch in enumerate(dataloader_test):
images = batch
images = images.to(device, dtype=torch.float)
 with torch.no_grad() :
outputs = net(images)
 preds = torch.softmax(outputs, dim=1 ).data.cpu()
if test_preds is None:
test_preds = preds
else:
test_preds = torch.cat(( test_preds, preds), dim=0)
 if submissions is None:
submissions = test_preds
else:
submissions += test_preds
<choose_model_class><EOS> 
submission_df['label'] = torch.argmax(submissions, dim=1)
 submission_df.to_csv('submission.csv', index=False)
 submission_df