Kaggle competition: Cassava Leaf Disease Classification
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<drop_column>
package_path = '.. /input/pytorch-image-models/pytorch-image-models-master'
new_data=new_data.drop('homepage_end',axis=1 )<feature_engineering>
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
from albumentations import OneOf
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 albumentations import OneOf
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
new_data['original_and_new']=new_data['original_and_new'].apply(lambda x: 1 if x else 0 )<define_variables>
CFG = {
'folder' : 'effnetb5512',
'fold_num': [0],
'seed': 719,
'model_arch': 'tf_efficientnet_b5_ns',
'img_size': 512,
'epochs': 21,
'train_bs': 16,
'valid_bs': 16,
'lr': 1e-4,
'num_workers': 4,
'accum_iter': 1,
'verbose_step': 1,
'device': 'cuda:0',
'tta': 5,
'used_epochs': [3,4,5],
'weights': [1,1,1]
}
CFG1 = {
'folder' : 'b6-whole',
'fold_num': [0],
'seed': 719,
'model_arch': 'tf_efficientnet_b6_ns',
'img_size': 256,
'epochs': 21,
'train_bs': 16,
'valid_bs': 16,
'lr': 1e-4,
'num_workers': 4,
'accum_iter': 1,
'verbose_step': 1,
'device': 'cuda:0',
'tta': 5,
'used_epochs': [0,1,2,3,4,5,6,7,8,9,21,37],
'weights': [1,1,1,1,1,1,1,1,1,1,1,1]
}
CFG2 = {
'folder' : '08855cv',
'fold_num': [0],
'seed': 719,
'model_arch': 'tf_efficientnet_b6_ns',
'img_size': 512,
'epochs': 21,
'train_bs': 16,
'valid_bs': 16,
'lr': 1e-4,
'num_workers': 4,
'accum_iter': 1,
'verbose_step': 1,
'device': 'cuda:0',
'tta': 5,
'used_epochs': [2],
'weights': [1,]
}
CFG3 = {
'folder' : 'b3-ns-512-512',
'fold_num': [0],
'seed': 719,
'model_arch': 'tf_efficientnet_b3_ns',
'img_size': 512,
'epochs': 21,
'train_bs': 16,
'valid_bs': 16,
'lr': 1e-4,
'num_workers': 4,
'accum_iter': 1,
'verbose_step': 1,
'device': 'cuda:0',
'tta': 1,
'used_epochs': [1,2,3,4,5,6,7,8,9],
'weights': [1,1,1,1,1,1,1,1,1]
}
CFG4 = {
'folder' : 'testingcv',
'fold_num': [2],
'seed': 719,
'model_arch': 'tf_efficientnet_b2_ns',
'img_size': 256,
'epochs': 21,
'train_bs': 16,
'valid_bs': 16,
'lr': 1e-4,
'num_workers': 4,
'accum_iter': 1,
'verbose_step': 1,
'device': 'cuda:0',
'tta': 1,
'used_epochs': [2],
'weights': [1]
}
CFGs = [CFG4]
list_geres_name=['Comedy','Thriller','Action','Drama','Romance']<feature_engineering>
train = pd.read_csv('.. /input/cassava-leaf-disease-classification/train.csv')
 train.head()
for i in list_geres_name:
new_data['geres_name'+'_'+i]=new_data['geres_name'].apply(lambda x: 1 if i in x else 0 )<drop_column>
train.label.value_counts()
new_data=new_data.drop('geres_name',axis=1 )<data_type_conversions>
submission = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv')
 submission.head()
new_data['production_countries']=new_data['production_countries'].fillna('QQ' )<feature_engineering>
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
new_data['production_countries'].loc[new_data['production_countries']=='Unknow']['production_countries']='QQ'<count_unique_values>
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(size=CFG['img_size']):
return Compose([
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(size=CFG['img_size']):
return Compose([
CenterCrop(size,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(size = CFG['img_size']):
return Compose([
CenterCrop(size,size),
Transpose(p=0.5),
OneOf([HorizontalFlip(p=0.5),
VerticalFlip(p=0.5)],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.)
list_pro_coun=list(new_data['production_countries'])
 d = Counter([j for i in list_pro_coun for j in i] ).most_common(5)
 d<feature_engineering>
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
for i in d:
new_data['production_cou_name'+'_'+i[0]]=new_data['production_countries'].apply(lambda x: 1 if i[0] in x else 0 )<feature_engineering>
if __name__ == '__main__':
seed_everything(CFG['seed'])
 test = pd.DataFrame()
test['image_id'] = list(os.listdir('.. /input/cassava-leaf-disease-classification/test_images/'))
final_vals = []
final_preds = []
for cfg in CFGs:
test_ds = CassavaDataset(test, '.. /input/cassava-leaf-disease-classification/test_images/', transforms=get_inference_transforms(cfg['img_size']), output_label=False)
 val_preds = []
tst_preds = []
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 = CassvaImgClassifier(cfg['model_arch'], train.label.nunique() ).to(device)
 for fold in cfg["fold_num"]:
tst_preds = []
for i, epoch in enumerate(cfg['used_epochs']):
model.load_state_dict(torch.load('.. /input/'+cfg["folder"]+'/{}_fold_{}_{}'.format(cfg['model_arch'],fold,epoch)))
 with torch.no_grad() :
for _ in range(CFG['tta']):
tst_preds += [cfg['weights'][i]/sum(cfg['weights'])/cfg['tta']*inference_one_epoch(model, tst_loader, device)]
tst_preds = np.mean(tst_preds, axis=0)
 try:
final_preds+=tst_preds
except:
final_preds = tst_preds
del model
torch.cuda.empty_cache()
new_data['pro_country_count']=new_data['production_companies'].apply(lambda x:len(x))<groupby>
test['label'] = np.argmax(final_preds/len(CFGs), axis=1)
 print(test.head())
 test.to_csv('submission.csv', index=False )