kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
15,203,842
optimizer = RMSprop(lr=0.001,rho=0.9,epsilon=1e-08,decay=0.0 )<choose_model_class>
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,203,842
model.compile(optimizer=optimizer,loss='categorical_crossentropy',metrics=['accuracy'] )<choose_model_class>
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=64) test_preds_arr = np.zeros(( N_FOLD, len(smpl_sub), N_CLASSES)) for fold_id in FOLD...
RANZCR CLiP - Catheter and Line Position Challenge
15,203,842
learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc',patience=3,verbose=1,factor=0.5,min_lir=0.00001 )<define_variables>
sub = smpl_sub.copy() sub[CLASSES] = test_preds_arr.mean(axis=0 )
RANZCR CLiP - Catheter and Line Position Challenge
15,203,842
epochs=30 batch_size=86<choose_model_class>
Final_Submission = smpl_sub.copy() Final_Submission[CLASSES] =.50 * sub[CLASSES] +.50 * submission[CLASSES]
RANZCR CLiP - Catheter and Line Position Challenge
15,203,842
<train_model><EOS>
Final_Submission.to_csv("submission.csv", index=False )
RANZCR CLiP - Catheter and Line Position Challenge
14,767,736
<SOS> metric: MCAUC Kaggle data source: ranzcr-clip-catheter-and-line-position-challenge<train_model>
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,767,736
history = model.fit_generator(datagen.flow(X_train,Y_train,batch_size=batch_size), epochs=epochs, validation_data=(X_test,Y_test), verbose=2, steps_per_epoch=X_train.shape[0]//batch_size, callbacks=[learning_rate_reduction] )<load_from_csv>
IMAGE_SIZE = 640 BATCH_SIZE = 128 TEST_PATH = '.. /input/ranzcr-clip-catheter-line-classification/test' MODEL_PATH = '.. /input/resnet200d-public/resnet200d_320_CV9632.pth'
RANZCR CLiP - Catheter and Line Position Challenge
14,767,736
test = pd.read_csv('.. /input/Kannada-MNIST/test.csv' )<define_variables>
test = pd.read_csv('.. /input/ranzcr-clip-catheter-line-classification/sample_submission.csv' )
RANZCR CLiP - Catheter and Line Position Challenge
14,767,736
test_ids = test['id']<drop_column>
def get_transforms() : return Compose([ Resize(IMAGE_SIZE, IMAGE_SIZE), Normalize( ), ToTensorV2() , ] )
RANZCR CLiP - Catheter and Line Position Challenge
14,767,736
test = test.drop(['id'],axis=1 )<feature_engineering>
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....
RANZCR CLiP - Catheter and Line Position Challenge
14,767,736
test = test/255.0<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'...
RANZCR CLiP - Catheter and Line Position Challenge
14,767,736
y_pre = model.predict(test )<prepare_output>
model = ResNet200D() model.load_state_dict(torch.load(MODEL_PATH)['model']) model.eval() models = [model.to(device)]
RANZCR CLiP - Catheter and Line Position Challenge
14,767,736
y_pre = np.argmax(y_pre,axis=1 )<create_dataframe>
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,767,736
<prepare_output><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
15,074,438
<SOS> metric: MCAUC Kaggle data source: ranzcr-clip-catheter-and-line-position-challenge<concatenate>
batch_size = 1 image_size = 512 tta = True submit = True enet_type = ['resnet200d'] * 5 model_path = ['.. /input/resnet200d-baseline-benchmark-public/resnet200d_fold0_cv953.pth', '.. /input/resnet200d-baseline-benchmark-public/resnet200d_fold1_cv955.pth', '.. /input/resnet200d-baseline-benchmark-public/resnet200d_fold2...
RANZCR CLiP - Catheter and Line Position Challenge
15,074,438
sub1 = pd.concat([test_ids,sub1],axis=1 )<rename_columns>
sys.path.append('.. /input/pytorch-image-models/pytorch-image-models-master') sys.path.append('.. /input/timm-pytorch-image-models/pytorch-image-models-master') DEBUG = False %matplotlib inline device = torch.device('cuda')if not DEBUG else torch.device('cpu' )
RANZCR CLiP - Catheter and Line Position Challenge
15,074,438
sub1 = sub1.rename(columns={0:'label'} )<save_to_csv>
class RANZCRResNet200D(nn.Module): def __init__(self, model_name='resnet200d', out_dim=11, pretrained=False): 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.Ada...
RANZCR CLiP - Catheter and Line Position Challenge
15,074,438
sub1.to_csv('submission.csv',index=False )<set_options>
transforms_test = albumentations.Compose([ Resize(image_size, image_size), Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], ), ToTensorV2() ] )
RANZCR CLiP - Catheter and Line Position Challenge
15,074,438
plt.style.use('ggplot') %matplotlib inline<load_from_csv>
test = pd.read_csv('.. /input/ranzcr-clip-catheter-line-classification/sample_submission.csv') test['file_path'] = test.StudyInstanceUID.apply(lambda x: os.path.join('.. /input/ranzcr-clip-catheter-line-classification/test', f'{x}.jpg')) target_cols = test.iloc[:, 1:12].columns.tolist() test_dataset = RANZCRDataset(te...
RANZCR CLiP - Catheter and Line Position Challenge
15,074,438
test = pd.read_csv('.. /input/Kannada-MNIST/test.csv') train = pd.read_csv('.. /input/Kannada-MNIST/train.csv') dig_df = pd.read_csv('.. /input/Kannada-MNIST/Dig-MNIST.csv') sample_df = pd.read_csv('.. /input/Kannada-MNIST/sample_submission.csv' )<split>
if submit: test_preds = [] for i in range(len(enet_type)) : if enet_type[i] == 'resnet200d': print('resnet200d loaded') model = RANZCRResNet200D(enet_type[i], out_dim=len(target_cols)) model = model.to(device) model.load_state_dict(torch.load(model_path[i], map_location='cuda:0')) if tta: test_preds += [tta_inference...
RANZCR CLiP - Catheter and Line Position Challenge
15,074,438
<choose_model_class><EOS>
if fast_sub: pd.read_csv('.. /input/ranzcr-clip-catheter-line-classification/sample_submission.csv',usecols=[0],index_col=0 ).join(pd.read_csv(fast_sub_path ).set_index('StudyInstanceUID')).fillna(0 ).to_csv('submission.csv' )
RANZCR CLiP - Catheter and Line Position Challenge
14,456,355
<SOS> metric: MCAUC Kaggle data source: ranzcr-clip-catheter-and-line-position-challenge<choose_model_class>
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,456,355
learning_rate_reduction = ReduceLROnPlateau(monitor='val_accuracy', patience=7, verbose=1, factor=0.1, min_lr=1e-8 )<choose_model_class>
IMAGE_SIZE = 640 BATCH_SIZE = 128 TEST_PATH = '.. /input/ranzcr-clip-catheter-line-classification/test' MODEL_PATH = '.. /input/seresnet152d-cv9615/seresnet152d_320_CV96.15.pth'
RANZCR CLiP - Catheter and Line Position Challenge
14,456,355
def build_norm_model() : inputs = layers.Input(shape=(28, 28, 1)) x = layers.Conv2D(filters=64, kernel_size=(5, 5), strides=(1, 1), padding='same', input_shape=(28, 28, 1))(inputs) x = layers.LeakyReLU(alpha=0.3 )(x) x = layers.BatchNormalization()(x) x = layers.Conv2D(filters=128, kernel_size=(3, 3), strides=(1, 1)...
test = pd.read_csv('.. /input/ranzcr-clip-catheter-line-classification/sample_submission.csv' )
RANZCR CLiP - Catheter and Line Position Challenge
14,456,355
def make_prediction(model, x): y_pred = model.predict(x) return np.argmax(y_pred, axis=1 )<categorify>
def get_transforms() : return Compose([ Resize(IMAGE_SIZE, IMAGE_SIZE), Normalize( ), ToTensorV2() , ] )
RANZCR CLiP - Catheter and Line Position Challenge
14,456,355
<train_model>
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 =...
RANZCR CLiP - Catheter and Line Position Challenge
14,456,355
final_model = build_norm_model() final_model.compile(optimizer=optimizers.RMSprop(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy']) history_final = final_model.fit_generator(train_datagen.flow(X_train, y_train, batch_size=1024), steps_per_epoch=100, epochs=120, validation_data=(X_valid, y_valid), callb...
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,456,355
y_result = make_prediction(final_model, X_test) sample_df['label'] = y_result sample_df.to_csv('submission.csv',index=False )<set_options>
model = SeResNet152D() model.load_state_dict(torch.load(MODEL_PATH)['model']) model.eval() models = [model.to(device)]
RANZCR CLiP - Catheter and Line Position Challenge
14,456,355
plt.style.use('ggplot') %matplotlib inline np.random.RandomState(42) <load_from_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 )
RANZCR CLiP - Catheter and Line Position Challenge
14,456,355
<choose_model_class><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,814,599
<SOS> metric: MCAUC Kaggle data source: ranzcr-clip-catheter-and-line-position-challenge<set_options>
warnings.filterwarnings("ignore")
RANZCR CLiP - Catheter and Line Position Challenge
14,814,599
optimizers = { 'sgd': opt.SGD() , 'sgd+momentum': opt.SGD(nesterov=True), 'rmsprop': opt.RMSprop() , 'adam': opt.Adam() , } <choose_model_class>
RANZCR CLiP - Catheter and Line Position Challenge
14,814,599
batch_size = 1024 epochs = 5 datagen_train = ImageDataGenerator( rotation_range = 10, width_shift_range = 0.25, height_shift_range = 0.25, shear_range = 0.1, zoom_range = 0.4, horizontal_flip = False ) datagen_val = ImageDataGenerator() learning_rate_reduction = ReduceLROnPlateau( monitor='loss', factor=0.25, patie...
RANZCR CLiP - Catheter and Line Position Challenge
14,814,599
%matplotlib inline<load_from_csv>
RANZCR CLiP - Catheter and Line Position Challenge
14,814,599
train = pd.read_csv('/kaggle/input/Kannada-MNIST/train.csv') test = pd.read_csv('/kaggle/input/Kannada-MNIST/test.csv' )<prepare_x_and_y>
RANZCR CLiP - Catheter and Line Position Challenge
14,814,599
X = train.drop(['label'],axis=1) y = train['label'] display(X.head() ,y.head() )<filter>
RANZCR CLiP - Catheter and Line Position Challenge
14,814,599
<init_hyperparams><EOS>
img_size = 600 def auto_select_accelerator() : try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() tf.config.experimental_connect_to_cluster(tpu) tf.tpu.experimental.initialize_tpu_system(tpu) strategy = tf.distribute.experimental.TPUStrategy(tpu) print("Running on TPU:", tpu.master()) except ValueError:...
RANZCR CLiP - Catheter and Line Position Challenge
13,702,907
<SOS> metric: MCAUC Kaggle data source: ranzcr-clip-catheter-and-line-position-challenge<train_model>
!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,702,907
def train_mnist() : Reached 99.9% accuracy so cancelling training!") callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10) X_train, X_val, y_train, y_val = train_test_split(X,y,random_state=0,test_size=0.2,shuffle=True) X_val, X_test, y_val, y_test = train_test_split(X_val,y_val,random_state=0...
import os import efficientnet.tfkeras as efn import numpy as np import pandas as pd import tensorflow as tf
RANZCR CLiP - Catheter and Line Position Challenge
13,702,907
<prepare_x_and_y>
def auto_select_accelerator() : try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() tf.config.experimental_connect_to_cluster(tpu) tf.tpu.experimental.initialize_tpu_system(tpu) strategy = tf.distribute.experimental.TPUStrategy(tpu) print("Running on TPU:", tpu.master()) except ValueError: strategy = tf....
RANZCR CLiP - Catheter and Line Position Challenge
13,702,907
history, model, X_test, y_test = train_mnist()<prepare_x_and_y>
COMPETITION_NAME = "ranzcr-clip-catheter-line-classification" strategy = auto_select_accelerator() BATCH_SIZE = strategy.num_replicas_in_sync * 16
RANZCR CLiP - Catheter and Line Position Challenge
13,702,907
X_test =(X_test / 255.0 ).reshape(len(X_test),28,28,1) test =(test / 255.0 ).reshape(len(test),28,28,1 )<compute_test_metric>
IMSIZE =(224, 240, 260, 300, 380, 456, 528, 600, 512) load_dir = f"/kaggle/input/{COMPETITION_NAME}/" sub_df = pd.read_csv(load_dir + 'sample_submission.csv') test_paths = load_dir + "test/" + sub_df['StudyInstanceUID'] + '.jpg' label_cols = sub_df.columns[1:] test_decoder = build_decoder(with_labels=False, target_si...
RANZCR CLiP - Catheter and Line Position Challenge
13,702,907
loss, acc = model.evaluate(X_test,y_test) print(f"Accuracy: {acc}") print(f"Loss: {loss}" )<predict_on_test>
def create_model(w, input_shape=[IMSIZE[-2], IMSIZE[-2],3], classes=11): base_model = efn.EfficientNetB7(include_top=False, weights=None, input_shape=input_shape) inputs = tf.keras.Input(shape=input_shape) x = base_model(inputs) x = tf.keras.layers.GlobalAveragePooling2D()(x) x = tf.keras.layers.Dense(classes )(x) ...
RANZCR CLiP - Catheter and Line Position Challenge
13,702,907
<create_dataframe><EOS>
sub_df[label_cols] = model.predict(dtest, verbose=1) sub_df.to_csv('submission.csv', index=False) sub_df.head()
RANZCR CLiP - Catheter and Line Position Challenge
13,676,994
<SOS> metric: MCAUC Kaggle data source: ranzcr-clip-catheter-and-line-position-challenge<save_to_csv>
import tensorflow as tf from tensorflow.keras import layers import os import re import math import numpy as np import matplotlib.pyplot as plt import pandas as pd
RANZCR CLiP - Catheter and Line Position Challenge
13,676,994
df.to_csv('submission.csv', index=False )<load_from_csv>
GCS_DS_PATH = ".. /input/ranzcr-clip-catheter-line-classification"
RANZCR CLiP - Catheter and Line Position Challenge
13,676,994
base_path = '/kaggle/input/Kannada-MNIST/' train = pd.read_csv(base_path + 'train.csv') test = pd.read_csv(base_path + 'test.csv') dig_mnist = pd.read_csv(base_path + 'Dig-MNIST.csv') train_label = train['label'] train_data_raw = train.drop('label', axis=1, inplace=False) train_data = [] train_data_raw = np.array(t...
train_df = pd.read_csv(GCS_DS_PATH+"/train.csv") train_df.index = train_df["StudyInstanceUID"] del train_df["StudyInstanceUID"] train_annot_df = pd.read_csv(GCS_DS_PATH+"/train_annotations.csv") train_annot_df.index = train_annot_df["StudyInstanceUID"] del train_annot_df["StudyInstanceUID"]
RANZCR CLiP - Catheter and Line Position Challenge
13,676,994
train_data = np.array(train_data)/255.0 test_data = np.array(test_data)/255.0 train_label = np.array(train_label ).reshape(60000,-1 )<choose_model_class>
classes = list(train_df.columns[:-1]) classes_normal= [name for name in classes[:-1] if name.split(" - ")[1] == "Normal"] classes_abnormal= [name for name in classes[:-1] if name.split(" - ")[1] == "Abnormal"] classes_borderline = [name for name in classes[:-1] if name.split(" - ")[1] == "Borderline"] classes_count = ...
RANZCR CLiP - Catheter and Line Position Challenge
13,676,994
es = EarlyStopping(monitor='accuracy', mode='min', verbose=1, patience=5,baseline=0.99) def define_model() : model2 = keras.models.Sequential([ keras.layers.Conv2D(16,(3,3), input_shape=(28,28,1), activation='relu'), keras.layers.BatchNormalization() , keras.layers.Conv2D(16,(5,5), activation='relu', padding='same'), ...
class_weights = {} ls = list(classes_count.values) tot_samples = sum(ls) for i in range(num_classes): class_weights[i] = tot_samples/(num_classes*ls[i]) class_weights
RANZCR CLiP - Catheter and Line Position Challenge
13,676,994
def define_model_ResNet50() : model = keras.models.Sequential() input_layer = keras.layers.Input(shape=(224, 224, 3), name='image_input') model.add(DenseNet121(weights=None, include_top=False, input_tensor=input_layer)) model.add(keras.layers.Flatten()) model.add(keras.layers.Dense(128)) model.add(keras.layers.BatchN...
patient_ids = train_df["PatientID"].unique() patientwise_count = train_df['PatientID'].value_counts() num_patients = len(patientwise_count) print("Number of patients: ",num_patients) patientwise_count
RANZCR CLiP - Catheter and Line Position Challenge
13,676,994
EPOCHS =100 X_train ,X_test,Y_train,Y_test= train_test_split(train_data,train_label,test_size=0.1) print(np.array(Y_train ).shape) es = keras.callbacks.EarlyStopping(monitor='accuracy', mode='min', patience=3, baseline=0.99) checkpoint = ModelCheckpoint('best_weights.h5', monitor='val_loss', sava_best_only=True, mod...
IMAGE_SIZE = [600,600] AUTO = tf.data.experimental.AUTOTUNE TEST_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + '/test_tfrecords/*.tfrec' )
RANZCR CLiP - Catheter and Line Position Challenge
13,676,994
<prepare_x_and_y>
def decode_image(image_data): image = tf.image.decode_jpeg(image_data, channels=3) image = tf.cast(image, tf.float32)/ 255.0 image = tf.image.resize(image, [*IMAGE_SIZE]) return image def read_labeled_tfrecord(example): LABELED_TFREC_FORMAT = { "StudyInstanceUID" : tf.io.FixedLenFeature([], tf.string), "image" : tf.i...
RANZCR CLiP - Catheter and Line Position Challenge
13,676,994
<load_from_csv>
def data_augment(image, label): image = tf.image.random_flip_left_right(image) return image,label def get_test_dataset(ordered=False): dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered) dataset = dataset.map(data_augment, num_parallel_calls=AUTO) dataset = dataset.batch(BATCH_SIZE) dataset = dat...
RANZCR CLiP - Catheter and Line Position Challenge
13,676,994
<prepare_x_and_y>
BATCH_SIZE = 16 * strategy.num_replicas_in_sync test_ds = get_test_dataset() print("Test:", test_ds )
RANZCR CLiP - Catheter and Line Position Challenge
13,676,994
print(np.array(X_train ).shape) print(np.array(Y_train ).shape) datagen = ImageDataGenerator(featurewise_center=False, samplewise_center=False, featurewise_std_normalization=False, samplewise_std_normalization=False, zca_whitening=False, rotation_range=20, zoom_range = 0.2, width_shift_range=0.20, height_shift_range=...
!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,676,994
model_prediction = define_model() model_prediction.load_weights('best_weights.h5' )<data_type_conversions>
model = tf.keras.models.load_model(".. /input/ranzcr-clip-tpu/model.h5" )
RANZCR CLiP - Catheter and Line Position Challenge
13,676,994
<save_to_csv><EOS>
test_ids=[] test_pred = [] j=0 for batch in test_ds: images,ids_batch = batch pred_batch = model.predict(images) for i,ids in enumerate(ids_batch): j+=1 if j%500 == 0: print(str(j),"Test Images Done") test_ids.append(ids) test_pred.append(pred_batch[i]) test_ids = [np.array(i ).astype("str" ).tolist() for i in test...
RANZCR CLiP - Catheter and Line Position Challenge
13,542,132
<SOS> metric: MCAUC Kaggle data source: ranzcr-clip-catheter-and-line-position-challenge<install_modules>
warnings.simplefilter("ignore")
RANZCR CLiP - Catheter and Line Position Challenge
13,542,132
!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<init_hyperparams>
print('Train images: %d' %len(os.listdir(os.path.join(WORK_DIR, "train"))))
RANZCR CLiP - Catheter and Line Position Challenge
13,542,132
%%time def detect(save_img=False): weights, imgsz = opt.weights,opt.img_size source = '.. /input/global-wheat-detection/test/' device = torch_utils.select_device(opt.device) half = False models = [] for w in weights: models.append(torch.load(w, map_location=device)['model'].to(device ).float().eval()) dataset = LoadI...
train = pd.read_csv(os.path.join(WORK_DIR, "train.csv")) train_images = WORK_DIR + "/train/" + train['StudyInstanceUID'] + '.jpg' ss = pd.read_csv(os.path.join(WORK_DIR, 'sample_submission.csv')) test_images = WORK_DIR + "/test/" + ss['StudyInstanceUID'] + '.jpg' label_cols = ss.columns[1:] labels = train[label_cols].v...
RANZCR CLiP - Catheter and Line Position Challenge
13,542,132
def run_wbf_yolo(boxes,scores, image_size=1024, iou_thr=0.4, skip_box_thr=0.34, weights=None): labels0 = [np.ones(len(scores[idx])) for idx in range(len(scores)) ] boxes, scores, labels = weighted_boxes_fusion(boxes, scores, labels0, weights=None, iou_thr=iou_thr, skip_box_thr=skip_box_thr) return boxes, scores, label...
BATCH_SIZE = 8 * 1 STEPS_PER_EPOCH = len(train)* 0.85 / BATCH_SIZE VALIDATION_STEPS = len(train)* 0.15 / BATCH_SIZE EPOCHS = 30 TARGET_SIZE = 750
RANZCR CLiP - Catheter and Line Position Challenge
13,542,132
all_path,all_score,all_bboxex = res yolov5preds = {} for row in range(len(all_path)) : preds = {} image_id = all_path[row].split("/")[-1].split(".")[0] boxes = all_bboxex[row] scores = all_score[row] boxes, scores, labels = run_wbf_yolo(boxes,scores) yolov5preds[image_id] = [boxes,scores,labels]<choose_model_class>
def build_decoder(with_labels = True, target_size =(TARGET_SIZE, TARGET_SIZE), 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 ValueErr...
RANZCR CLiP - Catheter and Line Position Challenge
13,542,132
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...
test_df = build_dataset( test_images, bsize = BATCH_SIZE, repeat = False, shuffle = False, augment = False, cache = False) test_df
RANZCR CLiP - Catheter and Line Position Challenge
13,542,132
best_iou_thr = 0.432 best_skip_box_thr = 0.397<load_pretrained>
RANZCR CLiP - Catheter and Line Position Challenge
13,542,132
models = [ load_net('.. /input/kernel5c5dc38533/effdet5-cutmix-augmix-bboxaug-0/last-checkpoint.bin'), load_net('.. /input/fold-1-global-wheat/effdet5-cutmix-augmix-bboxaug-1/last-checkpoint.bin'), load_net('.. /input/fold-2-global-wheat/effdet5-cutmix-augmix-bboxaug-2/last-checkpoint.bin'), load_net('.. /input/fold-3-...
print('Our Xception CNN has %d layers' %len(model.layers))
RANZCR CLiP - Catheter and Line Position Challenge
13,542,132
DATA_ROOT_PATH = '.. /input/global-wheat-detection/test' class TestDatasetRetriever(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_PAT...
img_tensor = build_dataset( pd.Series(test_images[0]), bsize = 1,repeat = False, shuffle = False, augment = False, cache = False )
RANZCR CLiP - Catheter and Line Position Challenge
13,542,132
<define_variables><EOS>
ss[label_cols] = model.predict(test_df, verbose = 1) ss.to_csv('submission.csv', index = False )
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
<SOS> metric: MCAUC Kaggle data source: ranzcr-clip-catheter-and-line-position-challenge<create_dataframe>
class CFG: device = 'GPU' cpu_workers = 2 debug = True seed = 13353 batch_size = 50 num_tta = 2 num_folds = 3 fold_idx = False fold_blend = 'pmean' model_blend = 'pmean' power = 1/11 w_public = 0.25 lgb_folds = 5 label_features = False sort_targets = True pred_as_feature = True lgb_stop_rounds = 200 lgb_params = {'obje...
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
y = effdetpreds.copy() x = yolov5preds.copy()<statistical_test>
CFG = dict(vars(CFG)) for key in ['__dict__', '__doc__', '__module__', '__weakref__']: del CFG[key]
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
def run_last_wbf(yolo,eff,weights=[2,1],iou_thr=0.5,skip_box_thr=0.397): box1,scores1,labels1 = yolo box2,scores2,labels2 = eff box1 = box1/1023 box2 = box2/1023 boxes, scores, labels = weighted_boxes_fusion([box1,box2], [scores1,scores2], [labels1,labels2],weights=[2,1], iou_thr=iou_thr, skip_box_thr=skip_box_thr) re...
CFGs = [] for model in CFG['models']: model_cfg = pickle.load(open(model + 'configuration.pkl', 'rb')) CFGs.append(model_cfg) print('Numer of models:', len(CFGs))
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
iou_thr = 0.5 skip_box_thr = 0.0001 results = [] for row in range(len(all_path)) : image_id = all_path[row].split("/")[-1].split(".")[0] boxes,scores = run_last_wbf(yolov5preds[image_id],effdetpreds[image_id]) boxes =(boxes*1023 ).astype(np.int32 ).clip(min=0, max=1023) boxes[:, 2] = boxes[:, 2] - boxes[:, 0] boxes[:...
pd.set_option('display.max_columns', 100) ImageFile.LOAD_TRUNCATED_IMAGES = True %matplotlib inline warnings.filterwarnings('ignore') sys.path.append('.. /input/timm-pytorch-image-models/pytorch-image-models-master')
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
test_df.to_csv('submission.csv', index=False) test_df.head()<install_modules>
if CFG['device'] == 'GPU': print('Training on GPU...') device = torch.device('cuda:0') if CFG['device'] == 'CPU': print('Training on CPU...') device = torch.device('cpu' )
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
! pip install.. /input/mmdetectionv260/addict-2.4.0-py3-none-any.whl ! pip install.. /input/mmdetectionv260/mmcv_full-latesttorch1.6.0cu102-cp37-cp37m-manylinux1_x86_64.whl ! pip install.. /input/mmdetectionv260/mmpycocotools-12.0.3-cp37-cp37m-linux_x86_64.whl ! pip install.. /input/mmdetection-package/mmdet-2.7.0-py3-...
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 compute_blend(df, preds, blend, CFG, weights = None): if weights is None: weights = np.ones(len(preds)) / len(preds...
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
! pip install.. /input/mmdetection-package/torch-1.6.0-cp37-cp37m-linux_x86_64.whl<install_modules>
df = pd.read_csv(CFG['data_path'] + 'sample_submission.csv') CFG['targets'] = ['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'] CFG['num_classes'] ...
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
<install_modules>
for m in CFG['models']: tmp_train_preds = pd.read_csv(m + '/oof.csv') tmp_train_preds.columns = ['StudyInstanceUID'] + CFG['targets'] + ['PatientID', 'fold'] + [m + ' ' + c for c in CFG['targets']] if m == CFG['models'][0]: train_preds = tmp_train_preds else: train_preds = train_preds.merge(tmp_train_preds[['StudyInst...
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
! cp -r.. /input/mmdetection-wheat-models/attention_stage1/faster_rcnn_r50_fpn_attention_0010_dcn_albu_1x4_1x_bWheat_kaggle.py./config.py ! cp -r.. /input/mmdetection-wheat-models/attention_stage1/epoch_12.pth./model.pth<define_variables>
for c in CFG['targets']: class_preds = train_preds.filter(like = 'kaggle' ).filter(like = c ).columns for blend in ['amean', 'median', 'gmean', 'pmean', 'rmean']: train_preds[blend + ' ' + c] = compute_blend(train_preds, class_preds, blend, CFG) for blend in ['amean', 'median', 'gmean', 'pmean', 'rmean']: train_preds[...
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
CONFIG_FILE = './config.py' CHECKPOINT_PATH = './model.pth' TEST_IMG_DIR = '.. /input/global-wheat-detection/test'<import_modules>
def get_dataset(CFG): class ImageData(Dataset): def __init__(self, df, path, transform = None, labeled = False, indexed = False): self.df = df self.path = path self.transform = transform self.labeled = labeled self.indexed = indexed def __len__(self): return len(self.df) def __getitem__(self, idx): path = os.path.join...
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
import os import json import pandas as pd import numpy as np import cv2 from tqdm import tqdm import torch import mmcv from mmdet.apis import init_detector, inference_detector<define_variables>
def get_model(CFG, device, num_classes): if CFG['weights'] != 'public': model = timm.create_model(model_name = CFG['backbone'], pretrained = False, in_chans = CFG['channels']) if 'efficient' in CFG['backbone']: model.classifier = nn.Linear(model.classifier.in_features, num_classes) else: model.fc = nn.Linear(model.fc...
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
TEST_ANN_FILE = './annotation_test.json' anns = [] for img_name in tqdm(os.listdir(TEST_IMG_DIR)) : if not img_name.endswith('.jpg'): continue anns.append(dict(filename=img_name, boxes=[]))<load_pretrained>
cv_start = time.time() gc.collect() all_counter = 0 fold_counter = 0 if not CFG['fold_idx'] else CFG['fold_idx'] all_cnn_preds = None for model_idx in range(len(CFG['models'])) : ImageData = get_dataset(CFGs[model_idx]) test_dataset = ImageData(df = df, path = CFG['data_path'] + 'test/', transform = get_augs(CFGs[mode...
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
with open('./result.bbox.json', 'r')as f1, open(TEST_ANN_FILE, 'r')as f2: result_info = json.load(f1) annotations_info = json.load(f2) for i, ann in tqdm(enumerate(result_info)) : if ann['score'] < 0.5: continue annotation = ann annotation['id'] = i annotation['area'] = ann['bbox'][2] * ann['bbox'][3] annotation['isc...
print('Blending fold predictions with: ' + CFG['fold_blend']) for m in CFG['models']: for c in CFG['targets']: class_preds = all_cnn_preds.filter(like = m ).filter(like = c ).columns all_cnn_preds[m + c] = compute_blend(all_cnn_preds, class_preds, CFG['fold_blend'], CFG) all_cnn_preds.drop(class_preds, axis = 1, inpl...
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
train_config = './train_config.py' cfg = mmcv.Config.fromfile(CONFIG_FILE) cfg.data.samples_per_gpu = 8 cfg.data.workers_per_gpu = 4 cfg.data.train.ann_file = './annotation_new.json' cfg.data.train.img_prefix = TEST_IMG_DIR cfg.data.train.pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_b...
for m in CFG['models']: tmp_train_preds = pd.read_csv(m + '/oof.csv') tmp_train_preds.columns = ['StudyInstanceUID'] + CFG['targets'] + ['PatientID', 'fold'] + [m + '' + c for c in CFG['targets']] if m == CFG['models'][0]: train_preds = tmp_train_preds else: train_preds = train_preds.merge(tmp_train_preds[['StudyInsta...
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
! python./mmdetection/tools/train.py {train_config} --no-validate --work-dir./pseudo<define_variables>
test_preds = all_cnn_preds.copy() test_preds = pd.concat([df['StudyInstanceUID'], test_preds], axis = 1) test_preds.head()
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
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 )<set_options>
X = train_preds.copy() X_test = test_preds.copy() drop_features = ['StudyInstanceUID', 'PatientID', 'fold'] + CFG['targets'] features = [f for f in X.columns if f not in drop_features] print(len(features), 'features') display(features )
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
device = 'cuda:0' if torch.cuda.is_available() else 'cpu'<load_pretrained>
folds = pd.read_csv('/kaggle/input/how-to-properly-split-folds/train_folds.csv') del X['fold'] X = X.merge(folds[['StudyInstanceUID', 'fold']], how = 'left', on = 'StudyInstanceUID' )
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
config = mmcv.Config.fromfile(CONFIG_FILE) config.model.pretrained = None config.data.test.pipeline[1]['img_scale'] = [(1280, 1280),(1408, 1408)] model = init_detector(config, './pseudo/epoch_1.pth', device=device) model.eval()<predict_on_test>
if CFG['sort_targets']: sorted_targets = ['Swan Ganz Catheter Present', 'ETT - Normal', 'ETT - Abnormal', 'ETT - Borderline', 'NGT - Abnormal', 'NGT - Normal', 'NGT - Incompletely Imaged', 'NGT - Borderline', 'CVC - Abnormal', 'CVC - Normal', 'CVC - Borderline']
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
results = [] score_threshold = 0.3 with torch.no_grad() : for img_name in tqdm(os.listdir(TEST_IMG_DIR)) : img_pth = os.path.join(TEST_IMG_DIR, img_name) image = mmcv.imread(img_pth) result = inference_detector(model, image) boxes = result[0][:, :4] scores = result[0][:, 4] if len(boxes)> 0: boxes[:, 2] = boxes[:, 2...
cnn_oof = np.zeros(( len(X), CFG['num_classes'])) lgb_oof = np.zeros(( len(X), CFG['num_classes'])) lgb_tst = np.zeros(( len(X_test), CFG['lgb_folds'], CFG['num_classes'])) all_lgb_preds = None cv_start = time.time() print('-' * 45) print('{:<28}{:<7}{:>5}'.format('Label', 'Model', 'AUC')) print('-' * 45) for label i...
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv', index=False) test_df.head()<install_modules>
print('Blending fold predictions with: ' + CFG['fold_blend']) for c in CFG['targets']: class_preds = all_lgb_preds.filter(like = c ).columns all_lgb_preds[c] = compute_blend(all_lgb_preds, class_preds, CFG['fold_blend'], CFG) all_lgb_preds.drop(class_preds, axis = 1, inplace = True) all_lgb_preds.head()
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
!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>
if CFG['w_public'] > 0: gc.collect() BATCH_SIZE = 96 IMAGE_SIZE = 640 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' class TestDat...
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
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>
if CFG['w_public'] == 0: df_pub = all_lgb_preds.copy() else: for c in CFG['targets']: class_preds = df_pub.filter(like = c ).columns df_pub[c] = compute_blend(df_pub, class_preds, CFG['model_blend'], CFG, weights = np.array([2/3, 1/3])) df_pub.drop(class_preds, axis = 1, inplace = True) df_pub.head()
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
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}/{...
all_preds = all_lgb_preds.copy() all_preds.columns = ['my/' + c for c in all_preds.columns] df_pub.columns = ['public/' + c for c in df_pub.columns] preds = pd.concat([all_preds, df_pub], axis = 1) for c in CFG['targets']: class_preds = preds.filter(like = c ).columns preds[c] = compute_blend(preds, class_preds, CFG['...
RANZCR CLiP - Catheter and Line Position Challenge
15,587,798
<choose_model_class><EOS>
if all_counter == len(CFG['models'] * CFG['num_folds']): for c in CFG['targets']: df[c] = preds[c].rank(pct = True) df.to_csv('submission.csv', index = False) display(df.head() )
RANZCR CLiP - Catheter and Line Position Challenge
15,559,926
<SOS> metric: MCAUC Kaggle data source: ranzcr-clip-catheter-and-line-position-challenge<categorify>
!pip install /kaggle/input/kerasapplications -q !pip install /kaggle/input/efficientnet-keras-source-code/ -q --no-deps
RANZCR CLiP - Catheter and Line Position Challenge
15,559,926
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...
import os, gc import efficientnet.tfkeras as efn import numpy as np import pandas as pd import tensorflow as tf
RANZCR CLiP - Catheter and Line Position Challenge
15,559,926
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...
def auto_select_accelerator() : try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() tf.config.experimental_connect_to_cluster(tpu) tf.tpu.experimental.initialize_tpu_system(tpu) strategy = tf.distribute.experimental.TPUStrategy(tpu) print("Running on TPU:", tpu.master()) except ValueError: strategy = tf....
RANZCR CLiP - Catheter and Line Position Challenge
15,559,926
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>
COMPETITION_NAME = "ranzcr-clip-catheter-line-classification" strategy = auto_select_accelerator() BATCH_SIZE = strategy.num_replicas_in_sync * 16
RANZCR CLiP - Catheter and Line Position Challenge
15,559,926
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...
model_paths = [ '.. /input/ranzcr-last-models/0.952_model_640_47.h5', '.. /input/ranzcr-last-models/0.953_model_616_51.h5', '.. /input/ranzcr-last-models/0.953_model_640_43.h5', '.. /input/ranzcr-last-models/0.954_model_640_42.h5', '.. /input/ranzcr-last-models/0.954_model_632_48.h5', ] subs = [] for model_path in mode...
RANZCR CLiP - Catheter and Line Position Challenge
15,559,926
<categorify><EOS>
submission = pd.concat(subs) submission = submission.groupby('StudyInstanceUID' ).mean() submission.to_csv('submission.csv') submission
RANZCR CLiP - Catheter and Line Position Challenge
15,517,725
<SOS> metric: MCAUC Kaggle data source: ranzcr-clip-catheter-and-line-position-challenge<save_to_csv>
!pip install.. /input/timm-repo/pytorch-image-models-master/ > /dev/null
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>
!pip install.. /input/pretrainedmodels-pytorch/pretrained-models.pytorch-master/ > /dev/null
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>
!pip install.. /input/efficientnet-pyotrch/EfficientNet-PyTorch-master/ > /dev/null
RANZCR CLiP - Catheter and Line Position Challenge