Kaggle competition: Cassava Leaf Disease Classification
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<prepare_output>
OUTPUT_DIR = './'
MODEL_DIR = '.. /input/resnextv2/'
TRAIN_PATH = '.. /input/cassava-leaf-disease-classification/train_images'
TEST_PATH = '.. /input/cassava-leaf-disease-classification/test_images'
class_preds =np.argmax(preds,axis=1)
 pred_submission = [dls.vocab[i] for i in class_preds]<save_to_csv>
class CFG:
debug=False
num_workers=4
model_name='resnext50_32x4d'
size=512
batch_size=32
seed=42
target_size=5
target_col='label'
n_fold=5
trn_fold=[0, 1, 2, 3, 4]
train=False
inference=True
submission = pd.read_csv(dirname+'/sample_submission.csv')
 submission['Label']=pred_submission
submission.to_csv('submission.csv',index=False )<set_options>
class TestDataset(Dataset):
def __init__(self, df, transform=None):
self.df = df
self.file_names = df['image_id'].values
self.transform = transform
def __len__(self):
return len(self.df)
 def __getitem__(self, idx):
file_name = self.file_names[idx]
file_path = f'{TEST_PATH}/{file_name}'
image = cv2.imread(file_path)
 image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
 if self.transform:
augmented = self.transform(image=image)
 image = augmented['image']
return image
%matplotlib inline 
<train_model>
class CustomResNext(nn.Module):
def __init__(self, model_name='resnext50_32x4d', pretrained=False):
super().__init__()
self.model = timm.create_model(model_name, pretrained=pretrained)
 n_features = self.model.fc.in_features
self.model.fc = nn.Linear(n_features, CFG.target_size)
 def forward(self, x):
x = self.model(x)
 return x
train_on_gpu = torch.cuda.is_available()
if not train_on_gpu:
print('Training on CPU...')
 else:
print('Training on GPU...')
<set_options>
def inference(model, states, test_loader, device):
model.to(device)
 tk0 = tqdm(enumerate(test_loader), total=len(test_loader))
probs = []
for i,(images)in tk0:
images = images.to(device)
 avg_preds = []
for state in states:
model.load_state_dict(state['model'])
 model.eval()
with torch.no_grad() :
y_preds = model(images)
 avg_preds.append(y_preds.softmax(1 ).to('cpu' ).numpy())
 avg_preds = np.mean(avg_preds, axis=0)
 probs.append(avg_preds)
 probs = np.concatenate(probs)
 return probs
device = torch.device('cuda:0' )<load_from_csv>
test = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv')
 test.head()
<count_missing_values><EOS> 
model = CustomResNext(CFG.model_name, pretrained=False)
 states = [torch.load(MODEL_DIR+f'{CFG.model_name}_fold{fold}_best.pth')for fold in CFG.trn_fold]
test_dataset = TestDataset(test, transform=get_transforms(data='valid'))
test_loader = DataLoader(test_dataset, batch_size=CFG.batch_size, shuffle=False,
num_workers=CFG.num_workers, pin_memory=True)
 predictions = inference(model, states, test_loader, device)
 test['label'] = predictions.argmax(1)
 test[['image_id', 'label']].to_csv(OUTPUT_DIR+'submission.csv', index=False)
 test.head()