Kaggle competition: RANZCR CLiP - Catheter and Line Position Challenge
<SOS> metric: MCAUC Kaggle data source: ranzcr-clip-catheter-and-line-position-challenge<init_hyperparams>
!pip install timm
<choose_model_class><EOS> 
sys.path.append('.. /input/pytorch-images-seresnet')
 warnings.filterwarnings('ignore')
 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
 IMAGE_SIZE = 640
BATCH_SIZE = 128
TEST_PATH = '.. /input/ranzcr-clip-catheter-line-classification/test'
MODEL_PATH_resnet200d = '.. /input/resnet200d-public/resnet200d_320_CV9632.pth'
MODEL_PATH_seresnet152d = '.. /input/seresnet152d-cv9615/seresnet152d_320_CV96.15.pth'
test = pd.read_csv('.. /input/ranzcr-clip-catheter-line-classification/sample_submission.csv')
 class TestDataset(Dataset):
def __init__(self, df, transform=None):
self.df = df
self.file_names = df['StudyInstanceUID'].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}.jpg'
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
def get_transforms() :
return Compose([
Resize(IMAGE_SIZE, IMAGE_SIZE),
Normalize(
),
ToTensorV2() ,
])
 class ResNet200D(nn.Module):
def __init__(self, model_name='resnet200d_320'):
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
class SeResNet152D(nn.Module):
def __init__(self, model_name='seresnet152d_320'):
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
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
models200D = []
model = ResNet200D()
model.load_state_dict(torch.load(MODEL_PATH_resnet200d)['model'])
 model.eval()
model.to(device)
 models200D.append(model)
 models152D = []
model = SeResNet152D()
model.load_state_dict(torch.load(MODEL_PATH_seresnet152d)['model'])
 model.eval()
model.to(device)
 models152D.append(model)
 test_dataset = TestDataset(test, transform=get_transforms())
 test_loader = DataLoader(test_dataset, batch_size=BATCH_SIZE, shuffle=False,
num_workers=4 , pin_memory=True)
 predictions200d = inference(models200D, test_loader, device)
 predictions152d = inference(models152D, test_loader, device)
 predictions =(2 * predictions200d + predictions152d)/ 3.0
target_cols = test.iloc[:, 1:12].columns.tolist()
test[target_cols] = predictions
test[['StudyInstanceUID'] + target_cols].to_csv('submission.csv', index=False)
 test.head()