Kaggle competition: RANZCR CLiP - Catheter and Line Position Challenge
X_train, X_test, Y_train, Y_test = train_test_split(x_train_final, y_train_final, test_size=0.2 )<drop_column>
Compose, OneOf, Normalize, Resize, RandomResizedCrop, RandomCrop, HorizontalFlip, VerticalFlip,
RandomBrightness, RandomContrast, RandomBrightnessContrast, Rotate, ShiftScaleRotate, Cutout,
IAAAdditiveGaussianNoise, Transpose 
)
 path = '.. /input/ranzcr-clip-catheter-line-classification/'
train_labels = pd.read_csv(path+'train.csv')
 IMAGE_SIZE = 640
BATCH_SIZE = 128
TEST_PATH = '.. /input/ranzcr-clip-catheter-line-classification/test'
keras.backend.clear_session()<train_model>
if torch.cuda.is_available() :
map_location=lambda storage, loc: storage.cuda()
else:
map_location='cpu'
model2 = get_model(num_classes, input_shape )<choose_model_class>
if torch.cuda.is_available() :
device= 'cuda'
else:
device='cpu'
print(device )
learning_rate_reduction2 = ReduceLROnPlateau(monitor='loss', patience=4, verbose=1, factor=0.5, min_lr=0.00001)
 checkpoint2 = ModelCheckpoint("bestmodel.model", monitor='loss', verbose=1, save_best_only=True)
 model2.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.002), metrics=['acc'] )<train_model>
def get_transforms() :
return Compose([
Resize(IMAGE_SIZE, IMAGE_SIZE),
Normalize(
 mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225], 
),
ToTensorV2()
] )
history2 = model2.fit_generator(
 train_datagen.flow(X_train, Y_train, batch_size=128),
steps_per_epoch=X_train.shape[0] // 128,
epochs=70,
validation_data=valid_datagen.flow(X_test, Y_test),
validation_steps=X_test.shape[0] // 128,
callbacks=[checkpoint2, learning_rate_reduction2],
class_weight = {0:2,1:1,2:1,3:1,4:1,5:1,6:2,7:2,8:1,9:1} )<load_pretrained>
class ResNet200D(nn.Module):
def __init__(self, model_name='resnet200d'):
super().__init__()
self.model = timm.create_model(model_name, pretrained=False)
 n_features = self.model.fc.in_features
self.model.global_pool = nn.Identity()
self.model.fc = nn.Identity()
self.pooling = nn.AdaptiveAvgPool2d(1)
 self.fc = nn.Linear(n_features, 11)
 def forward(self, x):
bs = x.size(0)
 features = self.model(x)
 pooled_features = self.pooling(features ).view(bs, -1)
 output = self.fc(pooled_features)
 return output
model2.load_weights('bestmodel.model' )<predict_on_test>
def inference(models, test_loader, device):
tk0 = tqdm(enumerate(test_loader), total=len(test_loader))
probs = []
for i,(images)in tk0:
images = images.to(device)
 avg_preds = []
for model in models:
with torch.no_grad() :
y_preds1 = model(images)
 y_preds2 = model(images.flip(-1))
y_preds =(y_preds1.sigmoid().to('cpu' ).numpy() + y_preds2.sigmoid().to('cpu' ).numpy())/ 2
avg_preds.append(y_preds)
 avg_preds = np.mean(avg_preds, axis=0)
 probs.append(avg_preds)
 probs = np.concatenate(probs)
 return probs
preds_dig=model2.predict(x_dig/255.)
preds_dig = np.argmax(preds_dig,axis=-1)
 print(metrics.accuracy_score(preds_dig, y_dig)) 
<save_to_csv>
MODEL_PATH = '.. /input/resnet200d-baseline-benchmark-public/resnet200d_fold4_cv954.pth'
MODEL_PATH957 = '.. /input/resnet200d-baseline-benchmark-public/resnet200d_fold3_cv957.pth'
results=model2.predict(x_test/255.0)
 predictions=np.argmax(results, axis=-1)
 submission = pd.read_csv('/kaggle/input/Kannada-MNIST/sample_submission.csv')
 submission['label'] = predictions
submission.to_csv("submission.csv",index=False)
 print('Done' )<filter>
model = ResNet200D()
model.load_state_dict(torch.load(MODEL_PATH,map_location=map_location),strict=False)
 model.eval()
models = [model.to(device)]
model957 = ResNet200D()
model957.load_state_dict(torch.load(MODEL_PATH957,map_location=map_location),strict=False)
 model957.eval()
models957 = [model957.to(device)]
misclassified = []
for i in range(len(preds_dig)) :
if preds_dig[i] != y_dig[i]:
misclassified.append(( preds_dig[i],y_dig[i]))<feature_engineering>
test = pd.read_csv('.. /input/ranzcr-clip-catheter-line-classification/sample_submission.csv')
 test_dataset = TestDataset(test, transform=get_transforms())
 test_loader = DataLoader(test_dataset, batch_size=BATCH_SIZE, shuffle=False,
num_workers=4 , pin_memory=True)
 predictions = inference(models, test_loader, device)
 predictions957 = inference(models957, test_loader, device)
<import_modules><EOS> 
target_cols = test.iloc[:, 1:12].columns.tolist()
test[target_cols] =(predictions + predictions957)/2
test[['StudyInstanceUID'] + target_cols].to_csv('submission.csv', index=False)
 test.head()