kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
15,517,725
def get_valid_transforms() : return A.Compose([ A.Resize(height=512, width=512, p=1.0), ToTensorV2(p=1.0), ], p=1.0 )<data_type_conversions>
!pip install.. /input/segmentation-models-pytorch/segmentation_models.pytorch-master/ > /dev/null
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
DATA_ROOT_PATH = '.. /input/global-wheat-detection/test' class DatasetRetriever(Dataset): def __init__(self, image_ids, transforms=None): super().__init__() self.image_ids = image_ids self.transforms = transforms def __getitem__(self, index: int): image_id = self.image_ids[index] image = cv2.imread(f'{DATA_ROOT_PATH}/{...
class RANZCRDataset(torch.utils.data.Dataset): def __init__( self, df, root, ext, path_col, use_timm_aug=False, transforms=None, augmentations=None, ): super().__init__() df = df.reset_index(drop=True ).copy() self.transforms = transforms self.augmentations = augmentations self.root = root self.use_timm_aug = use_tim...
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
dataset = DatasetRetriever( image_ids=np.array([path.split('/')[-1][:-4] for path in glob(f'{DATA_ROOT_PATH}/*.jpg')]), transforms=get_valid_transforms() ) def collate_fn(batch): return tuple(zip(*batch)) data_loader = DataLoader( dataset, batch_size=2, shuffle=False, num_workers=4, drop_last=False, collate_fn=coll...
EFFNETB6_EMB_DIM = 2304 EFFNETB5_EMB_DIM = 2048 EFFNETB4_EMB_DIM = 1792 EFFNETB3_EMB_DIM = 1536 EFFNETB1_EMB_DIM = 1280 RESNET50_EMB_DIM = 2048 REXNET200_EMB_DIM = 2560 VIT_EMB_DIM = 768 NF_RESNET50_EMB_DIM = 2048 EPS = 1e-6 class TaylorSoftmax(nn.Module): def __init__(self, dim=1, n=2): super(TaylorSoftmax, self ).__i...
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
def load_net(checkpoint_path): config = get_efficientdet_config('tf_efficientdet_d5') net = EfficientDet(config, pretrained_backbone=False) config.num_classes = 1 config.image_size=512 net.class_net = HeadNet(config, num_outputs=config.num_classes, norm_kwargs=dict(eps=.001, momentum=.01)) checkpoint = torch.load(che...
def get_validation_models( model_initilizer: Callable, model_config: Mapping[str, Any], model_ckp_dicts: List[OrderedDict], device: str, ): t_models = [] for mcd in model_ckp_dicts: t_model = model_initilizer(**model_config, device=device) t_model.load_state_dict(mcd) t_model = t_model.to(device) t_model.eval() t_...
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
def make_predictions(images, score_threshold=0.22): images = torch.stack(images ).cuda().float() predictions = [] with torch.no_grad() : det = net(images, torch.tensor([1]*images.shape[0] ).float().cuda()) for i in range(images.shape[0]): boxes = det[i].detach().cpu().numpy() [:,:4] scores = det[i].detach().cpu().nump...
%matplotlib inline
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
def format_prediction_string(boxes, scores): pred_strings = [] for j in zip(scores, boxes): pred_strings.append("{0:.4f} {1} {2} {3} {4}".format(j[0], j[1][0], j[1][1], j[1][2], j[1][3])) return " ".join(pred_strings )<predict_on_test>
SKIP_VAL = True
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
results = [] for images, image_ids in data_loader: predictions = make_predictions(images) for i, image in enumerate(images): boxes, scores, labels = run_wbf(predictions, image_index=i) boxes =(boxes*2 ).astype(np.int32 ).clip(min=0, max=1023) image_id = image_ids[i] boxes[:, 2] = boxes[:, 2] - boxes[:, 0] boxes[:, 3...
def public_notebook() : device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') BATCH_SIZE = 64 TEST_PATH = '.. /input/ranzcr-clip-catheter-line-classification/test' test = pd.read_csv('.. /input/ranzcr-clip-catheter-line-classification/sample_submission.csv') class TestDataset(Dataset): def __init__(se...
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv', index=False) test_df.head()<install_modules>
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
!pip install --no-deps '.. /input/timm-package/timm-0.1.26-py3-none-any.whl' > /dev/null !pip install --no-deps '.. /input/pycocotools/pycocotools-2.0-cp37-cp37m-linux_x86_64.whl' > /dev/null<categorify>
RESIZE_SIZE = 640
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
def get_valid_transforms() : return A.Compose([ A.Resize(height=512, width=512, p=1.0), ToTensorV2(p=1.0), ], p=1.0 )<data_type_conversions>
PATH2DIR = '.. /input/ranzcr-clip-catheter-line-classification/' os.listdir(PATH2DIR) train = pd.read_csv(pjoin(PATH2DIR, 'train.csv')) sample_sub = pd.read_csv(pjoin(PATH2DIR, 'sample_submission.csv')) split = np.load('.. /input/ranzcr-models/naive_cv_split.npy', allow_pickle=True )
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
DATA_ROOT_PATH = '.. /input/global-wheat-detection/test' class DatasetRetriever(Dataset): def __init__(self, image_ids, transforms=None): super().__init__() self.image_ids = image_ids self.transforms = transforms def __getitem__(self, index: int): image_id = self.image_ids[index] image = cv2.imread(f'{DATA_ROOT_PATH}/{...
DEVICE = 'cuda'
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
dataset = DatasetRetriever( image_ids=np.array([path.split('/')[-1][:-4] for path in glob(f'{DATA_ROOT_PATH}/*.jpg')]), transforms=get_valid_transforms() ) def collate_fn(batch): return tuple(zip(*batch)) data_loader = DataLoader( dataset, batch_size=4, shuffle=False, num_workers=2, drop_last=False, collate_fn=coll...
models_512 = [] ckp_names = glob('.. /input/ranzcr-models/timm_efficientnet_b5_unet_32bs_640res_lesslaugs_ls005_shedchanged_startpoint_difflrs_segbranch_125coefs_1e4noseg_bigholes_firstpseudo_swa_roc_auc_score/timm_efficientnet_b5_unet_32bs_640res_lesslaugs_ls005_shedchanged_startpoint_difflrs_segbranch_125coefs_1e4nos...
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
def load_net(checkpoint_path): config = get_efficientdet_config('tf_efficientdet_d5') net = EfficientDet(config, pretrained_backbone=False) config.num_classes = 1 config.image_size=512 net.class_net = HeadNet(config, num_outputs=config.num_classes, norm_kwargs=dict(eps=.001, momentum=.01)) checkpoint = torch.load(che...
if not SKIP_VAL: val_dfs = [ train.iloc[split[i][1]] for i in range(5) ] val_loaders = create_val_loaders( loader_initilizer=RANZCRDataset, loader_config={ "root":'train_images_512_512', "path_col": "StudyInstanceUID", "ext": ".jpeg", "transforms":T.ToTensor() }, dfs=val_dfs, batch_size=32 ) train_logits = predict_...
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
class BaseWheatTTA: image_size = 512 def augment(self, image): raise NotImplementedError def batch_augment(self, images): raise NotImplementedError def deaugment_boxes(self, boxes): raise NotImplementedError class TTAHorizontalFlip(BaseWheatTTA): def augment(self, image): return image.flip(1) def batch_augment(sel...
def predict_test_with_multiple_models( my_models: List[List[torch.nn.Module]], my_loaders: List[torch.utils.data.DataLoader], predict_func: Callable, device: str, ): logits = [] for my_loader in my_loaders: temp_logits = [] for batch in tqdm(my_loader): temp_logits_inner = [] for exp_models in my_models: logit = np.s...
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
def process_det(index, det, score_threshold=0.25): boxes = det[index].detach().cpu().numpy() [:,:4] scores = det[index].detach().cpu().numpy() [:,4] boxes[:, 2] = boxes[:, 2] + boxes[:, 0] boxes[:, 3] = boxes[:, 3] + boxes[:, 1] boxes =(boxes ).clip(min=0, max=511 ).astype(int) indexes = np.where(scores>score_threshol...
INF_BS = 32
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
tta_transforms = [] for tta_combination in product([TTAHorizontalFlip() , None], [TTAVerticalFlip() , None], [TTARotate90() , None]): tta_transforms.append(TTACompose([tta_transform for tta_transform in tta_combination if tta_transform]))<categorify>
all_test_loaders_512 = [] test_original = RANZCRDataset(**{ "df":sample_sub, "root":'test_images_512_512', "path_col": "StudyInstanceUID", "ext": ".jpeg", "transforms":T.ToTensor() }) all_test_loaders_512.append(torch.utils.data.DataLoader( test_original, batch_size=INF_BS, drop_last=False, shuffle=False, num_workers...
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
def make_tta_predictions(images, score_threshold=0.25): with torch.no_grad() : images = torch.stack(images ).float().cuda() predictions = [] for tta_transform in tta_transforms: result = [] det = net(tta_transform.batch_augment(images.clone()), torch.tensor([1]*images.shape[0] ).float().cuda()) for i in range(images.s...
test_logits_512 = predict_test_with_multiple_models( models_512, all_test_loaders_512, cnn_model_predict, DEVICE )
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
def format_prediction_string(boxes, scores): pred_strings = [] for j in zip(scores, boxes): pred_strings.append("{0:.4f} {1} {2} {3} {4}".format(j[0], j[1][0], j[1][1], j[1][2], j[1][3])) return " ".join(pred_strings )<categorify>
from scipy.special import expit
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
results = [] for images, image_ids in data_loader: predictions = make_tta_predictions(images) for i, image in enumerate(images): boxes, scores, labels = run_wbf(predictions, image_index=i) boxes =(boxes*2 ).round().astype(np.int32 ).clip(min=0, max=1023) image_id = image_ids[i] boxes[:, 2] = boxes[:, 2] - boxes[:, 0...
test_logits = expit(test_logits_512 ).mean(0 ).mean(1 )
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv', index=False) test_df.head()<load_from_csv>
my_exp_1 = test_logits[0] my_exp_2 = test_logits[1] my_exp_3 = test_logits[2] my_exp_4 = test_logits[3]
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
def load_dataset(root): csv = pd.read_csv(os.path.join(root, "train.csv")) data = {} for i in csv.index: key = csv["image_id"][i] bbox = json.loads(csv["bbox"][i]) bbox = [bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3], 0.0] if key in data: data[key].append(bbox) else: data[key] = [bbox] return sorted( [(k, ...
blend =( my_exp_1**0.5 + my_exp_2**0.5 + my_exp_3**0.5 + my_exp_3**0.5 )
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
def load_model(path, ctx=mx.cpu()): net = gcv.model_zoo.yolo3_darknet53_custom(["wheat"], pretrained_base=False) net.set_nms(post_nms=150) net.load_parameters(path, ctx=ctx) return net <normalization>
sample_sub.iloc[:,1:] = blend sample_sub
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
def inference(path): raw = load_image(path) rh, rw, _ = raw.shape classes_list = [] scores_list = [] bboxes_list = [] for _ in range(5): img, flips = gcv.data.transforms.image.random_flip(raw, px=0.5, py=0.5) x, _ = gcv.data.transforms.presets.yolo.transform_test(img, short=img_s) _, _, xh, xw = x.shape rot = random...
sample_sub.nunique(axis=0 )
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
import numpy as np import pandas as pd import os from tqdm.auto import tqdm import shutil as sh<install_modules>
!rm -rf test_images_512_512 sample_sub.to_csv('submission.csv', index=False) os.listdir('./' )
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
!cp -r.. /input/yolov5train/* .<load_from_csv>
ROOT = Path.cwd().parent INPUT = ROOT / "input" OUTPUT = ROOT / "output" DATA = INPUT / "ranzcr-clip-catheter-line-classification" TRAIN = DATA / "train" TEST = DATA / "test" TRAINED_MODEL = INPUT/ 'ranzer-models' TMP = ROOT / "tmp" TMP.mkdir(exist_ok=True) RANDAM_SEED = 1086 N_CLASSES = 11 FOLDS = [0, 1, 2, 3, 4] N_F...
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
with open(".. /input/valdata/val4.txt")as f: content = f.readlines() ` at the end of each line content = [x.strip().split('/')[-1].split('.')[0] for x in content] content<install_modules>
for p in DATA.iterdir() : print(p.name) train = pd.read_csv(DATA / "train.csv") smpl_sub = pd.read_csv(DATA / "sample_submission.csv" )
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
!pip install --no-deps '.. /input/weightedboxesfusion/' > /dev/null<feature_engineering>
if FAST_COMMIT and len(smpl_sub)== 3582: smpl_sub = smpl_sub.iloc[:64 * 2].reset_index(drop=True )
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
def convertTrainLabel() : df = pd.read_csv('.. /input/global-wheat-detection/train.csv') bboxs = np.stack(df['bbox'].apply(lambda x: np.fromstring(x[1:-1], sep=','))) for i, column in enumerate(['x', 'y', 'w', 'h']): df[column] = bboxs[:,i] df.drop(columns=['bbox'], inplace=True) df['x_center'] = df['x'] + df['w']/2...
def multi_label_stratified_group_k_fold(label_arr: np.array, gid_arr: np.array, n_fold: int, seed: int=42): np.random.seed(seed) random.seed(seed) start_time = time.time() n_train, n_class = label_arr.shape gid_unique = sorted(set(gid_arr)) n_group = len(gid_unique) gid2aid = dict(zip(gid_unique, range(n_group))) ...
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
def run_wbf(boxes, scores, image_size=1023, iou_thr=0.5, skip_box_thr=0.7, weights=None): labels = [np.zeros(score.shape[0])for score in scores] boxes = [box/(image_size)for box in boxes] boxes, scores, labels = weighted_boxes_fusion(boxes, scores, labels, weights=None, iou_thr=iou_thr, skip_box_thr=skip_box_thr) boxe...
label_arr = train[CLASSES].values group_id = train.PatientID.values train_val_indexs = list( multi_label_stratified_group_k_fold(label_arr, group_id, N_FOLD, RANDAM_SEED))
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
def makePseudolabel() : source = '.. /input/global-wheat-detection/test/' weights = '.. /input/ckpts41/best_fold4.pt' imgsz = 1024 conf_thres = 0.5 iou_thres = 0.6 is_TTA = True imagenames = os.listdir(source) device = torch.device('cuda')if torch.cuda.is_available() else torch.device('cpu') model = torch.load(weight...
train["fold"] = -1 for fold_id,(trn_idx, val_idx)in enumerate(train_val_indexs): train.loc[val_idx, "fold"] = fold_id train.groupby("fold")[CLASSES].sum()
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
!cp 'weights/best.pt' 'best_psuedolblf4.pt'<define_variables>
def resize_images(img_id, input_dir, output_dir, resize_to=(640, 640), ext="png"): img_path = input_dir / f"{img_id}.jpg" save_path = output_dir / f"{img_id}.{ext}" img = cv2.imread(str(img_path), cv2.IMREAD_GRAYSCALE) img = cv2.resize(img, resize_to) cv2.imwrite(str(save_path), img,) TEST_RESIZED = TMP / "test_{0}x...
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
def format_prediction_string(boxes, scores): pred_strings = [] for j in zip(scores, boxes): pred_strings.append("{0:.4f} {1} {2} {3} {4}".format(j[0], j[1][0], j[1][1], j[1][2], j[1][3])) return " ".join(pred_strings )<load_pretrained>
def get_activation(activ_name: str="relu"): act_dict = { "relu": nn.ReLU(inplace=True), "tanh": nn.Tanh() , "sigmoid": nn.Sigmoid() , "identity": nn.Identity() } if activ_name in act_dict: return act_dict[activ_name] else: raise NotImplementedError class Conv2dBNActiv(nn.Module): def __init__( self, in_channels: i...
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
def detect() : source = '.. /input/global-wheat-detection/test/' weights = 'weights/best.pt' if not os.path.exists(weights): weights = '.. /input/ckpts41/best_fold4.pt' imgsz = 1024 conf_thres = 0.5 iou_thres = 0.6 is_TTA = True imagenames = os.listdir(source) device = torch.device('cuda')if torch.cuda.is_available() ...
class MultiHeadResNet200D(nn.Module): def __init__( self, out_dims_head: tp.List[int]=[3, 4, 3, 1], pretrained=False ): self.base_name = "resnet200d_320" self.n_heads = len(out_dims_head) super(MultiHeadResNet200D, self ).__init__() base_model = timm.create_model( self.base_name, num_classes=sum(out_dims_head), p...
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
results = detect() test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv', index=False) test_df.head()<install_modules>
class LabeledImageDataset(data.Dataset): def __init__( self, file_list: tp.List[ tp.Tuple[tp.Union[str, Path], tp.Union[int, float, np.ndarray]]], transform_list: tp.List[tp.Dict], ): self.file_list = file_list self.transform = ImageTransformForCls(transform_list) def __len__(self): return len(self.file_list) ...
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
!pip install --no-deps '.. /input/timm-package/timm-0.1.26-py3-none-any.whl' > /dev/null !pip install --no-deps '.. /input/pycocotools/pycocotools-2.0-cp37-cp37m-linux_x86_64.whl' > /dev/null<define_variables>
def get_dataloaders_for_inference( file_list: tp.List[tp.List], batch_size=64, ): dataset = LabeledImageDataset( file_list, transform_list=[ ["Normalize", { "always_apply": True, "max_pixel_value": 255.0, "mean": ["0.4887381077884414"], "std": ["0.23064819430546407"]}], ["ToTensorV2", {"always_apply": True}], ]) ...
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
img_sz = 640 device = 'cuda' if torch.cuda.is_available() else 'cpu' device<normalization>
class ImageTransformBase: def __init__(self, data_augmentations: tp.List[tp.Tuple[str, tp.Dict]]): augmentations_list = [ self._get_augmentation(aug_name )(**params) for aug_name, params in data_augmentations] self.data_aug = albumentations.Compose(augmentations_list) def __call__(self, pair: tp.Tuple[np.ndarray]...
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
def get_valid_transforms() : return A.Compose([A.Resize(height=img_sz, width=img_sz, p=1.0), ToTensorV2(p=1.0)], p=1.0 )<data_type_conversions>
def load_setting_file(path: str): with open(path)as f: settings = yaml.safe_load(f) return settings def set_random_seed(seed: int = 42, deterministic: bool = False): random.seed(seed) np.random.seed(seed) os.environ["PYTHONHASHSEED"] = str(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backe...
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
DATA_ROOT_PATH = '.. /input/global-wheat-detection/test' class DatasetRetriever(Dataset): def __init__(self, image_ids, transforms=None): super().__init__() self.image_ids = image_ids self.transforms = transforms def __getitem__(self, index: int): image_id = self.image_ids[index] image = cv2.imread(f'{DATA_ROOT_PATH}/{...
if not torch.cuda.is_available() : device = torch.device("cpu") else: device = torch.device("cuda") print(device )
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
dataset = DatasetRetriever(image_ids=np.array([path.split('/')[-1][:-4] for path in glob(f'{DATA_ROOT_PATH}/*.jpg')]), transforms=get_valid_transforms()) def collate_fn(batch): return tuple(zip(*batch)) data_loader = DataLoader(dataset, batch_size=2, shuffle=False, num_workers=4, drop_last=False, collate_fn=collate_fn...
model_dir = TRAINED_MODEL test_dir = TEST_RESIZED test_file_list = [ (test_dir / f"{img_id}.png", [-1] * 11) for img_id in smpl_sub["StudyInstanceUID"].values] test_loader = get_dataloaders_for_inference(test_file_list, batch_size=32) test_preds_arr = np.zeros(( N_FOLD , len(smpl_sub), N_CLASSES)) for fold_id in [0,...
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
def load_net(checkpoint_path): config = get_efficientdet_config('tf_efficientdet_d5') net = EfficientDet(config, pretrained_backbone=False) config.num_classes = 1 config.image_size=img_sz net.class_net = HeadNet(config, num_outputs=config.num_classes, norm_kwargs=dict(eps=.001, momentum=.01)) checkpoint = torch.load(...
if CONVERT_TO_RANK: test_preds_arr = test_preds_arr.argsort(axis=1 ).argsort(axis=1) sub = smpl_sub.copy() sub[CLASSES] = test_preds_arr.mean(axis=0) sub.to_csv("submission.csv", index=False )
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
class BaseWheatTTA: image_size = img_sz def augment(self, image): raise NotImplementedError def batch_augment(self, images): raise NotImplementedError def deaugment_boxes(self, boxes): raise NotImplementedError class TTAHorizontalFlip(BaseWheatTTA): def augment(self, image): return image.flip(1) def batch_augment(self...
model_dir = TRAINED_MODEL test_dir = TEST_RESIZED test_file_list = [ (test_dir / f"{img_id}.png", [-1] * 11) for img_id in smpl_sub["StudyInstanceUID"].values] test_loader = get_dataloaders_for_inference(test_file_list, batch_size=4) N_FOLD = len([1024]) test_preds_arr = np.zeros(( N_FOLD , len(smpl_sub), N_CLASSES...
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
tta_transforms = [] for tta_combination in product([TTAHorizontalFlip() , None], [TTAVerticalFlip() , None], [TTARotate90() , None]): tta_transforms.append(TTACompose([tta_transform for tta_transform in tta_combination if tta_transform]))<predict_on_test>
sub_2 = smpl_sub.copy() sub_2[CLASSES] = test_preds_arr.mean(axis=0 )
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
def make_predictions(net, images, score_threshold=0.22): images = torch.stack(images ).cuda().float() predictions = [] with torch.no_grad() : det = net(images, torch.tensor([1]*images.shape[0] ).float().cuda()) for i in range(images.shape[0]): boxes = det[i].detach().cpu().numpy() [:,:4] scores = det[i].detach().cpu()...
sub[CLASSES] = 0.6 * sub[CLASSES] + 0.4 * sub_2[CLASSES]
RANZCR CLiP - Catheter and Line Position Challenge
15,372,370
<categorify><EOS>
sub.to_csv("submission.csv", index=False )
RANZCR CLiP - Catheter and Line Position Challenge
13,557,724
<SOS> metric: MCAUC Kaggle data source: ranzcr-clip-catheter-and-line-position-challenge<save_to_csv>
!pip install /kaggle/input/kerasapplications -q !pip install /kaggle/input/efficientnet-keras-source-code/ -q --no-deps
RANZCR CLiP - Catheter and Line Position Challenge
13,557,724
test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv', index=False) test_df.head()<import_modules>
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' warnings.simplefilter('ignore' )
RANZCR CLiP - Catheter and Line Position Challenge
13,557,724
import logging import os import re import gc import json from tqdm.auto import tqdm import numpy as np import pandas as pd import cv2 import matplotlib.pyplot as plt<install_modules>
MIXED_PRECISION = True XLA_ACCELERATE = False GPUS = tf.config.experimental.list_physical_devices('GPU') if GPUS: try: for GPU in GPUS: tf.config.experimental.set_memory_growth(GPU, True) logical_gpus = tf.config.experimental.list_logical_devices('GPU') print(len(GPUS), "Physical GPUs,", len(logical_gpus), "Logical ...
RANZCR CLiP - Catheter and Line Position Challenge
13,557,724
!pip install.. /input/pytorch-16/torch-1.6.0cu101-cp37-cp37m-linux_x86_64.whl<install_modules>
class BaseConfig(object): SEED = 101 TRAIN_DF = '.. /input/ranzcr-clip-catheter-line-classification/train.csv' TRAIN_IMG_PATH = '.. /input/ranzcr224/RANZCR_224/' TEST_IMG_PATH = '.. /input/ranzcr-clip-catheter-line-classification/test/' CLASS_MAP = '.. /input/ranzcr-clip-catheter-line-classification/train_annotations.c...
RANZCR CLiP - Catheter and Line Position Challenge
13,557,724
!pip install.. /input/pytorch-16/torchvision-0.7.0cu101-cp37-cp37m-linux_x86_64.whl<install_modules>
df = pd.read_csv(BaseConfig.TRAIN_DF) submit = pd.read_csv(BaseConfig.SUBMIT) target_cols = submit.columns[1:] df.head()
RANZCR CLiP - Catheter and Line Position Challenge
13,557,724
!pip install.. /input/pretrainedmodels/pretrainedmodels-0.7.4/pretrainedmodels-0.7.4/ > /dev/null<install_modules>
target_cols = ['ETT - Abnormal', 'ETT - Borderline', 'ETT - Normal', 'NGT - Abnormal', 'NGT - Borderline', 'NGT - Incompletely Imaged', 'NGT - Normal', 'CVC - Abnormal', 'CVC - Borderline', 'CVC - Normal', 'Swan Ganz Catheter Present']
RANZCR CLiP - Catheter and Line Position Challenge
13,557,724
!pip install.. /input/wheat-pkgs/EfficientNet-PyTorch-master/EfficientNet-PyTorch-master/ > /dev/null<install_modules>
def build_decoder(with_labels=True, target_size=(300, 300), ext='jpg'): def decode(path): file_bytes = tf.io.read_file(path) if ext == 'png': img = tf.image.decode_png(file_bytes, channels=3) elif ext in ['jpg', 'jpeg']: img = tf.image.decode_jpeg(file_bytes, channels=3) else: raise ValueError("Image extension not s...
RANZCR CLiP - Catheter and Line Position Challenge
13,557,724
!pip install.. /input/wheat-pkgs/timm-0.1.20-py3-none-any.whl > /dev/null<install_modules>
class TrainConfig(BaseConfig): EPOCH = 3 FOLDS = 5 TTA = 5 VERBOSITY = 0 WORKERS = 2 LABEL_SMOOTH = 0.0 MULTIPROCESS = False LR_RATE = { '0' : 1e-3, '1' : 1e-3, '2' : 1e-4, '3' : 1e-4, '4' : 1e-4 } BATCH_SIZE = { '0' : 32, '1' : 128, '2' : 86, '3' : 128, '4' : 128 } IMG_SIZE = { '0': 850, '1': 240, '2': 260, '3': 224, ...
RANZCR CLiP - Catheter and Line Position Challenge
13,557,724
!pip install.. /input/wheat-pkgs/segmentation_models.pytorch-master/segmentation_models.pytorch-master > /dev/null<import_modules>
class SpatialAttentionModule(tf.keras.layers.Layer): def __init__(self, kernel_size=3): super(SpatialAttentionModule, self ).__init__() self.conv1 = tf.keras.layers.Conv2D(64, kernel_size=kernel_size, use_bias=False, kernel_initializer='he_normal', strides=1, padding='same', activation=tf.nn.relu6) self.conv2 = tf.k...
RANZCR CLiP - Catheter and Line Position Challenge
13,557,724
set_seed, create_logging, WheatDataset, FastDataLoader, collate, ModleWithLoss, CtdetLoss, ModelEMA, get_cosine_schedule_with_warmup, train_one_epoch, get_train_transforms )<define_variables>
class AttentionWeightedAverage2D(tf.keras.layers.Layer): def __init__(self, **kwargs): self.init = tf.keras.initializers.get('uniform') super(AttentionWeightedAverage2D, self ).__init__(** kwargs) def build(self, input_shape): self.input_spec = [tf.keras.layers.InputSpec(ndim=4)] assert len(input_shape)== 4 self.W = ...
RANZCR CLiP - Catheter and Line Position Challenge
13,557,724
bifpn_path_0 = '.. /input/wheat-weights/model_centernet_effnetb5_bifpn_00099.pth' bifpn_path_1 = '.. /input/wheat-weights/model_centernet_effnetb5_bifpn_fold1_00099.pth' bifpn_path_3 = '.. /input/wheat-weights/model_centernet_effnetb5_bifpn_fold3_lb_ema_00099.pth'<init_hyperparams>
class RANZCRClassifier(tf.keras.Model): def __init__(self, dim): super(RANZCRClassifier, self ).__init__() self.Base = efn.EfficientNetB5( input_shape=(TrainConfig.IMG_SIZE['0'], TrainConfig.IMG_SIZE['0'], 3), weights=None, include_top=False) self.GAP1 = tf.keras.layers.GlobalAveragePooling2D() self.GAP2 = tf.keras.l...
RANZCR CLiP - Catheter and Line Position Challenge
13,557,724
class Config: arch = 'timm-efficientnet-b5' heads = {'hm': 1, 'wh': 2, 'reg': 2} head_conv = 64 reg_offset = True cat_spec_wh = False img_size = 1024 in_scale = 1024 / img_size down_ratio = 4 mean = [0.315290, 0.317253, 0.214556], std = [0.245211, 0.238036, 0.193879] num_classes = 1 pad = 63 batch_size = 8 K = 128 max_...
model = RANZCRClassifier(( TrainConfig.IMG_SIZE['0'],TrainConfig.IMG_SIZE['0'], 3)) model.build(( None, *(TrainConfig.IMG_SIZE['0'],TrainConfig.IMG_SIZE['0'], 3))) model.load_weights('.. /input/multiattentioncheckwg/model.h5' )
RANZCR CLiP - Catheter and Line Position Challenge
13,557,724
def change_key(d): for _ in range(len(d)) : k, v = d.popitem(False) d['.'.join(k.split('.')[1:])] = v<load_from_csv>
test_paths = BaseConfig.TEST_IMG_PATH + submit['StudyInstanceUID'] + '.jpg' test_decoder = build_decoder(with_labels=False, target_size=(TrainConfig.IMG_SIZE['0'], TrainConfig.IMG_SIZE['0'])) dtest = build_dataset( test_paths, bsize=TrainConfig.BATCH_SIZE['0'], repeat=False, shuffle=False, augment=False, cache=False, ...
RANZCR CLiP - Catheter and Line Position Challenge
13,557,724
DIR_INPUT = '.. /input/global-wheat-detection' DIR_TRAIN = f'{DIR_INPUT}/train' DIR_TEST = f'{DIR_INPUT}/test' train_df = pd.read_csv(f'{DIR_INPUT}/train.csv') train_df.shape<data_type_conversions>
submit[target_cols] = model.predict(dtest, verbose=1) submit.to_csv('submission.csv', index=False) submit.head()
RANZCR CLiP - Catheter and Line Position Challenge
14,570,708
train_df['x'] = -1 train_df['y'] = -1 train_df['w'] = -1 train_df['h'] = -1 def expand_bbox(x): r = np.array(re.findall("([0-9]+[.]?[0-9]*)", x)) if len(r)== 0: r = [-1, -1, -1, -1] return r train_df[['x', 'y', 'w', 'h']] = np.stack(train_df['bbox'].apply(lambda x: expand_bbox(x))) train_df.drop(columns=['bbox'], inpl...
class PAM_Module(nn.Module): def __init__(self, in_dim): super(PAM_Module, self ).__init__() self.chanel_in = in_dim self.query_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim//8, kernel_size=1) self.key_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim//8, kernel_size=1) self.value_conv = nn.Conv2d...
RANZCR CLiP - Catheter and Line Position Challenge
14,570,708
class WheatDatasetTest(torch.utils.data.Dataset): def __init__(self, opt, image_dir, transforms=None, mean=[0.315290, 0.317253, 0.214556], std=[0.245211, 0.238036, 0.193879]): self.opt = opt self.image_dir = image_dir self.img_id = os.listdir(self.image_dir) self.transforms = transforms self.mean = np.array(mean, dtyp...
class EffNetWLF(nn.Module): def __init__(self, model_name, target_size=11): super().__init__() self.backbone = EfficientNet.from_name(model_name) self.backbone._dropout = nn.Dropout(0.1) n_features = self.backbone._fc.in_features self.backbone._fc = nn.Linear(n_features, target_size) self.local_fe = CBAM(n_features)...
RANZCR CLiP - Catheter and Line Position Challenge
14,570,708
def flip_lr(img): return np.ascontiguousarray(img[:, ::-1, :]) def deaug_lr(img, boxes): h, w = img.shape[:2] boxes[:,(0, 2)] = w - boxes[:,(2, 0)] return boxes def flip_ud(img): return np.ascontiguousarray(img[::-1, :, :]) def deaug_ud(img, boxes): h, w = img.shape[:2] boxes[:,(1, 3)] = w - boxes[:,(3, 1)] return bo...
work_dir = ".. /input/ranzcr-clip-catheter-line-classification/" df = pd.read_csv(os.path.join(work_dir, "sample_submission.csv")) test_img_paths = glob.glob(os.path.join(work_dir, "test/*.jpg")) print(len(test_img_paths)) model_weights = glob.glob(".. /input/effb2wlf/*.pth") print(model_weights )
RANZCR CLiP - Catheter and Line Position Challenge
14,570,708
testdataset = WheatDatasetTest(opt, DIR_TEST) print('Total number of images in test set: {}'.format(len(testdataset))) testdataset_lr = WheatDatasetTest(opt, DIR_TEST, transforms=flip_lr) testdataset_ud = WheatDatasetTest(opt, DIR_TEST, transforms=flip_ud )<find_best_model_class>
normalize = a_transform.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], p=1.0, max_pixel_value=255.0) test_transform = a_transform.Compose([a_transform.Resize(512, 512), normalize, ToTensorV2() ], p=1.0) test_ds = TestDataset(test_img_paths, test_transform) dataloader = DataLoader(test_ds, batch_siz...
RANZCR CLiP - Catheter and Line Position Challenge
14,570,708
<load_pretrained><EOS>
final_pred = np.empty(( len(model_weights),len(test_ds), 11), dtype=np.float32) for model_idx, each_w in enumerate(model_weights): print(f"running idx {model_idx}") model = EffNetWLF("efficientnet-b2") model = model.to(device) checkpoint = torch.load(f"{each_w}") model.load_state_dict(checkpoint["model"]) uids = ...
RANZCR CLiP - Catheter and Line Position Challenge
14,476,794
<SOS> metric: MCAUC Kaggle data source: ranzcr-clip-catheter-and-line-position-challenge<predict_on_test>
sys.path.append('.. /input/pytorch-images-seresnet') warnings.filterwarnings('ignore') device = torch.device('cuda' if torch.cuda.is_available() else 'cpu' )
RANZCR CLiP - Catheter and Line Position Challenge
14,476,794
opt.pad = 63 opt.test_scales = [1.1, ] threshold = 0.30 bifpn0_pred_boxes_0 , bifpn0_pred_scores_0, h0_list, w0_list, img_ids = do_predict(opt, bifpn_model, threshold=threshold, flip_type=0, return_ids=True, return_shapes=True) bifpn0_pred_boxes_0_lr, bifpn0_pred_scores_0_lr = do_predict(opt, bifpn_model, threshold=th...
IMAGE_SIZE = 640 BATCH_SIZE = 64 TEST_PATH = '.. /input/ranzcr-clip-catheter-line-classification/test' MODEL_PATH = '.. /input/efficientnetb5cv9621/tf_efficientnet_b5_ns_CV96.21.pth'
RANZCR CLiP - Catheter and Line Position Challenge
14,476,794
del bifpn_model gc.collect() torch.cuda.empty_cache()<load_pretrained>
test = pd.read_csv('.. /input/ranzcr-clip-catheter-line-classification/sample_submission.csv' )
RANZCR CLiP - Catheter and Line Position Challenge
14,476,794
bifpn_model = PoseBiFPNNet(opt.arch, opt.heads, opt.head_conv) checkpoint = torch.load(bifpn_path_1, map_location=device) change_key(checkpoint['model']) bifpn_model.load_state_dict(checkpoint['model']) bifpn_model.to(device) del checkpoint gc.collect()<predict_on_test>
def get_transforms() : return Compose([ Resize(IMAGE_SIZE, IMAGE_SIZE), Normalize( ), ToTensorV2() , ] )
RANZCR CLiP - Catheter and Line Position Challenge
14,476,794
opt.pad = 63 opt.test_scales = [1.1, ] threshold = 0.30 bifpn1_pred_boxes_0 , bifpn1_pred_scores_0 = do_predict(opt, bifpn_model, threshold=threshold, flip_type=0, return_ids=False, return_shapes=False) bifpn1_pred_boxes_0_lr, bifpn1_pred_scores_0_lr = do_predict(opt, bifpn_model, threshold=threshold, flip_type=1, ret...
class EfficientNetB5(nn.Module): def __init__(self, model_name='tf_efficientnet_b5_ns'): super().__init__() self.model = timm.create_model(model_name, pretrained=False) n_features = self.model.classifier.in_features self.model.global_pool = nn.Identity() self.model.classifier = nn.Identity() self.pooling = nn.Adaptive...
RANZCR CLiP - Catheter and Line Position Challenge
14,476,794
del bifpn_model gc.collect() torch.cuda.empty_cache()<load_pretrained>
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'...
RANZCR CLiP - Catheter and Line Position Challenge
14,476,794
bifpn_model = PoseBiFPNNet(opt.arch, opt.heads, opt.head_conv) checkpoint = torch.load(bifpn_path_3, map_location=device) change_key(checkpoint['model']) bifpn_model.load_state_dict(checkpoint['model']) bifpn_model.to(device) del checkpoint gc.collect()<predict_on_test>
model = EfficientNetB5() model.load_state_dict(torch.load(MODEL_PATH)['model']) model.eval() models = [model.to(device)]
RANZCR CLiP - Catheter and Line Position Challenge
14,476,794
opt.pad = 63 opt.test_scales = [1.1, ] threshold = 0.30 bifpn3_pred_boxes_0 , bifpn3_pred_scores_0 = do_predict(opt, bifpn_model, threshold=threshold, flip_type=0, return_ids=False, return_shapes=False) bifpn3_pred_boxes_0_lr, bifpn3_pred_scores_0_lr = do_predict(opt, bifpn_model, threshold=threshold, flip_type=1, ret...
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 )
RANZCR CLiP - Catheter and Line Position Challenge
14,476,794
<categorify><EOS>
target_cols = test.iloc[:, 1:12].columns.tolist() test[target_cols] = predictions test[['StudyInstanceUID'] + target_cols].to_csv('submission.csv', index=False) test.head()
RANZCR CLiP - Catheter and Line Position Challenge
14,298,658
<SOS> metric: MCAUC Kaggle data source: ranzcr-clip-catheter-and-line-position-challenge<define_variables>
effnet_path = '.. /input/efficientnet-pytorch/' iterstrat_path = '.. /input/iterative-stratification/iterative-stratification-master' sys.path.append(effnet_path) sys.path.append(iterstrat_path )
RANZCR CLiP - Catheter and Line Position Challenge
14,298,658
sys.path.insert(0, ".. /input/weightedboxesfusion") iou_thr = 0.44 skip_box_thr = 0.00001 pred_boxes_ensemble = [] pred_scores_ensemble = [] for(b00, b01, b02, b03, b04, b05, b06, b07, b08, b10, b11, b12, b13, b14, b15, b16, b17, b18, b20, b21, b22, b23, b24, b25, b26, b27, b28, s00, s01, s02, s03, s04, s05, s06, s07,...
warnings.filterwarnings("ignore")
RANZCR CLiP - Catheter and Line Position Challenge
14,298,658
pred_boxes_ensemble = [denormalize_clip_boxes(a, h0, w0)for a, h0, w0 in zip(pred_boxes_ensemble, h0_list, w0_list)] pred_scores_ensemble = [a for a in pred_scores_ensemble]<categorify>
IMAGE_SIZE =(512, 512) PIL.ImageFile.LOAD_TRUNCATED_IMAGES = True IMAGE_BACKEND = 'cv2' FOLD = 0 def set_seed(seed=0): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.deterministic = True set_seed()
RANZCR CLiP - Catheter and Line Position Challenge
14,298,658
def format_prediction_string(boxes, scores): pred_strings = [] for s, b in zip(scores, boxes.astype(int)) : pred_strings.append(f'{s:.4f} {b[0]} {b[1]} {b[2]} {b[3]}') return " ".join(pred_strings )<compute_test_metric>
data_dir = ".. /input/ranzcr-clip-catheter-line-classification/" path_checkpoints_dir = "./checkpoints" path_submissions_dir = "./" path_trained_models = ".. /input/000-010-sgdr-ensemble-4" path_test_dir= os.path.join(data_dir, 'test') path_sample_submission_file= os.path.join(data_dir, 'sample_submission.csv') submi...
RANZCR CLiP - Catheter and Line Position Challenge
14,298,658
pred_strs = [] for bboxes, scores in zip(pred_boxes_ensemble, pred_scores_ensemble): if len(bboxes)> 0: bboxes[:, 2] -= bboxes[:, 0] bboxes[:, 3] -= bboxes[:, 1] bboxes = bboxes.round() pred_strs.append(format_prediction_string(bboxes, scores)) else: pred_strs.append('' )<create_dataframe>
def resize_one_image(input_path, output_path, image_size): image = cv2.imread(input_path) image = cv2.resize(image, image_size) cv2.imwrite(output_path, image) def resize_image_batch(input_dir, output_dir, image_size): if not os.path.isdir(output_dir): os.mkdir(output_dir) input_paths = [os.path.join(input_dir, i...
RANZCR CLiP - Catheter and Line Position Challenge
14,298,658
test_df = pd.DataFrame({'image_id': img_ids, 'PredictionString':pred_strs}) test_df<save_to_csv>
path_resized_test_image_dir = os.path.join('./', "test_resized") print(path_resized_test_image_dir )
RANZCR CLiP - Catheter and Line Position Challenge
14,298,658
test_df.to_csv('submission.csv', index=False )<set_options>
submission_file = pd.read_csv(path_sample_submission_file) path_test_images = [os.path.join(path_resized_test_image_dir, i + ".jpg")for i in submission_file.StudyInstanceUID.values]
RANZCR CLiP - Catheter and Line Position Challenge
14,298,658
sns.set(context="notebook", style="darkgrid", palette="deep", font="sans-serif", font_scale=1, color_codes=True) <load_from_csv>
path_test_dir = ".. /input/ranzcr-clip-catheter-line-classification/test" resize_image_batch(path_test_dir, path_resized_test_image_dir, IMAGE_SIZE )
RANZCR CLiP - Catheter and Line Position Challenge
14,298,658
data= pd.read_csv(".. /input/covid19-global-forecasting-week-1/train.csv") data["Date"] = data["Date"].apply(lambda x: x.replace("-","")) data["Date"] = data["Date"].astype(int) <count_missing_values>
class ImageDataset: def __init__( self, image_paths, targets=None, augmentations=None, backend="cv2", channel_first=True, grayscale=False, grayscale_as_rgb=False, ): if grayscale is False and grayscale_as_rgb is True: raise Exception("Invalid combination of " "arguments 'grayscale=False' and 'grayscale_as_rgb=True'...
RANZCR CLiP - Catheter and Line Position Challenge
14,298,658
data = data.drop(['Province/State'],axis=1) data = data.dropna() data.isnull().sum() <load_from_csv>
test_dataset = ImageDataset( path_test_images, None, augmentations=test_augmentation, backend=IMAGE_BACKEND, channel_first=True, grayscale=True, grayscale_as_rgb=True, )
RANZCR CLiP - Catheter and Line Position Challenge
14,298,658
test = pd.read_csv(".. /input/covid19-global-forecasting-week-1/test.csv") test["Date"] = test["Date"].apply(lambda x: x.replace("-","")) test["Date"] = test["Date"].astype(int) test["Lat"] = test["Lat"].fillna(12.5211) test["Long"] = test["Long"].fillna(69.9683) test.isnull().sum() <prepare_x_and_y>
class DataModule(object): def __init__(self, train_dataset, valid_dataset, test_dataset): self.train_dataset = train_dataset self.valid_dataset = valid_dataset self.test_dataset = test_dataset def get_train_dataloader(self, **kwargs): return torch.utils.data.DataLoader(self.train_dataset, **kwargs) def get_valid_datal...
RANZCR CLiP - Catheter and Line Position Challenge
14,298,658
x =data[['Lat', 'Long', 'Date']] y1 = data[['ConfirmedCases']] y2 = data[['Fatalities']] x_test = test[['Lat', 'Long', 'Date']] <choose_model_class>
class EfficientNetModel(torch.nn.Module): def __init__(self, num_labels=11, pretrained=True): super().__init__() self.num_labels = num_labels if pretrained: self.backbone = EfficientNet.from_pretrained("efficientnet-b5",) else: self.backbone = EfficientNet.from_name("efficientnet-b5",) self.dropout = torch.nn.Dropout...
RANZCR CLiP - Catheter and Line Position Challenge
14,298,658
model = RandomForestClassifier(n_estimators=200 )<predict_on_test>
class Trainer: def __init__(self, model, data_module, experiment_id, optimizer=None, scheduler=None, device='cuda'): self.model = model self.data_module = data_module self.optimizer = optimizer self.scheduler = scheduler self.device = device self.fp16 = False self.step_scheduler_after = None self.n_epochs = None self.m...
RANZCR CLiP - Catheter and Line Position Challenge
14,298,658
model.fit(x,y1) pred1 = model.predict(x_test) pred1 = pd.DataFrame(pred1) pred1.columns = ["ConfirmedCases_prediction"]<choose_model_class>
def ensemble_models(model_paths, output_file, **kwargs): model = EfficientNetModel(pretrained=False) data_module = DataModule(None, None, test_dataset) preds_list = [] num_models = len(model_paths) print(f"number of models to ensemble={num_models}") for mpath in model_paths: print(mpath) trainer = Trainer(model,...
RANZCR CLiP - Catheter and Line Position Challenge
14,298,658
<predict_on_test><EOS>
model_paths = os.listdir(path_trained_models,) model_paths = [os.path.join(path_trained_models, mpath)for mpath in model_paths] ensemble_models(model_paths, "submission", test_batch_size=16) print("done" )
RANZCR CLiP - Catheter and Line Position Challenge
13,898,599
<SOS> metric: MCAUC Kaggle data source: ranzcr-clip-catheter-and-line-position-challenge<load_from_csv>
OUTPUT_DIR = './' if not os.path.exists(OUTPUT_DIR): os.makedirs(OUTPUT_DIR) TEST_PATH = '.. /input/ranzcr-clip-catheter-line-classification/test'
RANZCR CLiP - Catheter and Line Position Challenge
13,898,599
Sub = pd.read_csv(".. /input/covid19-global-forecasting-week-1/submission.csv") Sub.columns sub_new = Sub[["ForecastId"]]<concatenate>
class CFG: debug=False num_workers=4 model_name='resnet200d_320' size=512 batch_size=128 seed=416 target_size=11 target_cols=['ETT - Abnormal', 'ETT - Borderline', 'ETT - Normal', 'NGT - Abnormal', 'NGT - Borderline', 'NGT - Incompletely Imaged', 'NGT - Normal', 'CVC - Abnormal', 'CVC - Borderline', 'CVC - Normal', 'Sw...
RANZCR CLiP - Catheter and Line Position Challenge
13,898,599
OP = pd.concat([pred1,pred2,sub_new],axis=1) OP.head() OP.columns = ['ConfirmedCases', 'Fatalities', 'ForecastId'] OP = OP[['ForecastId','ConfirmedCases', 'Fatalities']] <data_type_conversions>
def get_score(y_true, y_pred): scores = [] for i in range(y_true.shape[1]): score = roc_auc_score(y_true[:,i], y_pred[:,i]) scores.append(score) avg_score = np.mean(scores) return avg_score, scores def get_result(result_df): preds = result_df[[f'pred_{c}' for c in CFG.target_cols]].values labels = result_df[CFG.targ...
RANZCR CLiP - Catheter and Line Position Challenge
13,898,599
OP["ConfirmedCases"] = OP["ConfirmedCases"].astype(int) OP["Fatalities"] = OP["Fatalities"].astype(int) <save_to_csv>
oof_df = pd.read_csv('.. /input/ranzcr-exp12-step3-fold0/oof_df.csv') for fold in CFG.trn_fold: fold_oof_df = oof_df[oof_df['fold']==fold].reset_index(drop=True) LOGGER.info(f"========== fold: {fold} result ==========") get_result(fold_oof_df )
RANZCR CLiP - Catheter and Line Position Challenge
13,898,599
OP.to_csv("submission.csv",index=False )<import_modules>
if CFG.debug: test = pd.read_csv('.. /input/ranzcr-clip-catheter-line-classification/sample_submission.csv', nrows=10) else: test = pd.read_csv('.. /input/ranzcr-clip-catheter-line-classification/sample_submission.csv') print(test.shape) test.head()
RANZCR CLiP - Catheter and Line Position Challenge
13,898,599
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import plotly.express as px import plotly.graph_objects as go import datetime as dt import folium<load_pretrained>
train_dataset = TestDataset(test, transform=get_transforms(data='valid')) for i in range(1): image = train_dataset[i] plt.imshow(image[0]) plt.show() plt.imshow(image[0].flip(-1)) plt.show()
RANZCR CLiP - Catheter and Line Position Challenge
13,898,599
!kaggle kaggle competitions download -c covid19-global-forecasting-week-1<install_modules>
class CustomResNet200D(nn.Module): def __init__(self, model_name='resnet200d_320', pretrained=False): super().__init__() self.model = timm.create_model(model_name, pretrained=False) if pretrained: pretrained_path = '.. /input/resnet200d-pretrained-weight/resnet200d_ra2-bdba9bf9.pth' self.model.load_state_dict(torch.lo...
RANZCR CLiP - Catheter and Line Position Challenge
13,898,599
!pip install kaggle<set_options>
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'...
RANZCR CLiP - Catheter and Line Position Challenge
13,898,599
!mkdir.kaggle<load_pretrained>
%%time model = CustomResNet200D(CFG.model_name, pretrained=False) model_path = '.. /input/ranzcr-exp12-step3-fold0/resnet200d_320_fold0_best_loss.pth' model.load_state_dict(torch.load(model_path)['model']) model.eval() models = [model.to(device)]
RANZCR CLiP - Catheter and Line Position Challenge
13,898,599
token = {"username":'nitingrover425','key':'c22685e02df7d46edd199e441980c448'} with open('/content/.kaggle/kaggle.json', 'w')as file: json.dump(token, file )<install_modules>
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(models, test_loader, device )
RANZCR CLiP - Catheter and Line Position Challenge
13,898,599
<load_pretrained><EOS>
test[CFG.target_cols] = predictions test[['StudyInstanceUID'] + CFG.target_cols].to_csv(OUTPUT_DIR+'submission.csv', index=False) test.head()
RANZCR CLiP - Catheter and Line Position Challenge
13,871,913
<SOS> metric: MCAUC Kaggle data source: ranzcr-clip-catheter-and-line-position-challenge<load_from_csv>
import os import random import numpy as np import pandas as pd import cv2 import matplotlib.pyplot as plt import torch import torchvision from torchvision import transforms import tensorflow as tf import albumentations as A
RANZCR CLiP - Catheter and Line Position Challenge
13,871,913
train_data = pd.read_csv(".. /input/covid19-global-forecasting-week-1/train.csv" )<count_missing_values>
DIR = ".. /input/ranzcr-clip-catheter-line-classification/"
RANZCR CLiP - Catheter and Line Position Challenge