kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
14,938,817
checkpoint = ModelCheckpoint('vgg_model.h5', save_best_only=True, verbose=1) history = vgg_m.fit_generator(train_generator, steps_per_epoch=len(train_generator), epochs=6, validation_data = val_generator, validation_steps=len(val_generator), callbacks=[checkpoint]) <load_pretrained>
submission = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') submission.head()
Cassava Leaf Disease Classification
14,938,817
!ls batch_index = 0 files_list = os.listdir(".. /input/state-farm-distracted-driver-detection/test") def load_test_images(batch_size=32, src='.. /input/state-farm-distracted-driver-detection/test/'): global batch_index, files_list imgs_list = files_list[batch_index: batch_index+batch_size] batch_index += len(imgs_list...
def seed_everything(seed): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = True def get_img(path): im_bgr = cv2.imread(path) im_rgb = im_bgr[:, :, ::-1]...
Cassava Leaf Disease Classification
14,938,817
preds_list = np.array([]) batch_index=0 batch_size = 32 mm_raw = load_VGG16() mm_model = mm_raw.output mm_model = Dense(5000, activation='relu',kernel_regularizer=regularizers.l2(0.00001))(mm_model) mm_model = Dropout(0.1 )(mm_model) mm_model = Dense(500, activation='relu',kernel_regularizer=regularizers.l2(0.00001)...
class LeafDataset(Dataset): def __init__(self, df, img_dir, transforms=None, include_labels=True): super().__init__() self.df = df self.img_dir = img_dir self.transforms = transforms self.include_labels = include_labels if include_labels: self.labels = self.df['label'].values def __len__(self): return len(self.df) d...
Cassava Leaf Disease Classification
14,938,817
titles = "img,c0,c1,c2,c3,c4,c5,c6,c7,c8,c9".split(",") names = pd.DataFrame(files_list[:len(preds_list)]) names.columns=["img"] df = pd.DataFrame(preds_list) df.columns=titles[1:] df['img']=names['img'] df = df[titles] df.tail()<save_to_csv>
class LeafDiseaseClassifier(nn.Module): def __init__(self, model_arch, num_classes, pretrained=False): super().__init__() self.model = timm.create_model(model_arch, pretrained=pretrained) n_features = self.model.classifier.in_features self.model.classifier = nn.Linear(n_features, num_classes) def forward(self, x): ...
Cassava Leaf Disease Classification
14,938,817
df.to_csv('sub_VGG16.csv',index=False )<set_options>
if __name__ == '__main__': seed_everything(config['seed']) test = pd.DataFrame() test['image_id'] = list(os.listdir('.. /input/cassava-leaf-disease-classification/test_images/')) test_ds = LeafDataset(test, '.. /input/cassava-leaf-disease-classification/test_images/', transforms=get_infer_transforms() , include_labe...
Cassava Leaf Disease Classification
14,938,817
%matplotlib inline warnings.filterwarnings("ignore") test_dir = "/kaggle/input/deepfake-detection-challenge/test_videos/" test_videos = sorted([x for x in os.listdir(test_dir)if x[-4:] == ".mp4"]) frame_h = 5 frame_l = 5 len(test_videos) print("PyTorch version:", torch.__version__) print("CUDA version:", torch.vers...
test['label'] = np.argmax(preds, axis=1) test.head() test.to_csv('submission.csv', index=False )
Cassava Leaf Disease Classification
14,938,817
<install_modules><EOS>
del model torch.cuda.empty_cache()
Cassava Leaf Disease Classification
13,022,518
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<define_variables>
!pip install --quiet /kaggle/input/kerasapplications !pip install --quiet /kaggle/input/efficientnet-git
Cassava Leaf Disease Classification
13,022,518
test_dir = "/kaggle/input/deepfake-detection-challenge/test_videos/" test_videos = sorted([x for x in os.listdir(test_dir)if x[-4:] == ".mp4"]) len(test_videos )<load_pretrained>
def seed_everything(seed=0): random.seed(seed) np.random.seed(seed) tf.random.set_seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) os.environ['TF_DETERMINISTIC_OPS'] = '1' seed = 0 seed_everything(seed) warnings.filterwarnings('ignore' )
Cassava Leaf Disease Classification
13,022,518
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") sys.path.insert(0, "/kaggle/input/blazeface-pytorch") sys.path.insert(0, "/kaggle/input/deepfakes-inference-demo") facedet = BlazeFace().to(gpu) facedet.load_weights("/kaggle/input/blazeface-pytorch/blazeface.pth") facedet.load_anchors("/kaggle/i...
try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() print(f'Running on TPU {tpu.master() }') except ValueError: tpu = None if tpu: tf.config.experimental_connect_to_cluster(tpu) tf.tpu.experimental.initialize_tpu_system(tpu) strategy = tf.distribute.experimental.TPUStrategy(tpu) else: strategy = tf.distr...
Cassava Leaf Disease Classification
13,022,518
model = get_model("xception", pretrained=False) model = nn.Sequential(*list(model.children())[:-1]) class Pooling(nn.Module): def __init__(self): super(Pooling, self ).__init__() self.p1 = nn.AdaptiveAvgPool2d(( 1,1)) self.p2 = nn.AdaptiveMaxPool2d(( 1,1)) def forward(self, x): x1 = self.p1(x) x2 = self.p2(x) retur...
BATCH_SIZE = 16 * REPLICAS HEIGHT = 512 WIDTH = 512 CHANNELS = 3 N_CLASSES = 5 TTA_STEPS = 5
Cassava Leaf Disease Classification
13,022,518
def predict_on_video(video_path, batch_size): try: faces = face_extractor.process_video(video_path) face_extractor.keep_only_best_face(faces) if len(faces)> 0: x = np.zeros(( batch_size, input_size, input_size, 3), dtype=np.uint8) n = 0 for frame_data in faces: for face in frame_data["faces"]: resized_face = isotrop...
database_base_path = '/kaggle/input/cassava-leaf-disease-classification/' submission = pd.read_csv(f'{database_base_path}sample_submission.csv') display(submission.head()) TEST_FILENAMES = tf.io.gfile.glob(f'{database_base_path}test_tfrecords/ld_test*.tfrec') NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES) print...
Cassava Leaf Disease Classification
13,022,518
!nvidia-smi<save_to_csv>
model_path_list = glob.glob('/kaggle/input/cassava-leaf-disease-tpu-tensorflow-training/*.h5') model_path_list.sort() print('Models to predict:') print(*model_path_list, sep=' ' )
Cassava Leaf Disease Classification
13,022,518
submission_df_one = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df_one.to_csv("submission_xception.csv", index=False) fsub = 0.52*submission_df_resnext['label'] + 0.50*submission_df_one['label'] final = pd.DataFrame({'filename': test_videos, "label": fsub}) final.to_csv('submission.csv',...
model_path_list_2 = glob.glob('/kaggle/input/cassava-leaf-disease-training-with-tpu-v2-pods/*.h5') model_path_list_2.sort() print('Models to predict:') print(*model_path_list_2, sep=' ' )
Cassava Leaf Disease Classification
13,022,518
!pip install.. /input/pytorchcv/pytorchcv-0.0.55-py2.py3-none-any.whl --quiet<set_options>
def model_fn(input_shape, N_CLASSES): inputs = L.Input(shape=input_shape, name='inputs') base_model = efn.EfficientNetB3(input_tensor=inputs, include_top=False, weights=None, pooling='avg') model = tf.keras.Sequential([ base_model, L.Dropout (.25), L.Dense(N_CLASSES, activation='softmax', name='output') ]) return m...
Cassava Leaf Disease Classification
13,022,518
%matplotlib inline warnings.filterwarnings("ignore" )<define_variables>
files_path = f'{database_base_path}test_images/' test_preds = np.zeros(( len(os.listdir(files_path)) , N_CLASSES)) print('First model') for model_path in model_path_list: print(model_path) K.clear_session() model.load_weights(model_path) if TTA_STEPS > 0: test_ds = get_dataset(files_path, tta=True) for step in rang...
Cassava Leaf Disease Classification
13,022,518
<set_options><EOS>
submission = pd.DataFrame({'image_id': image_names, 'label': test_preds}) submission.to_csv('submission.csv', index=False) display(submission.head() )
Cassava Leaf Disease Classification
21,462,468
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<load_pretrained>
sys.path.append('.. /input/timm-pytorch-image-models/pytorch-image-models-master') TESTSAMPLEPATH = '.. /input/cassava-leaf-disease-classification/sample_submission.csv' CLASSESJSONPATH = '.. /input/cassava-leaf-disease-classification/label_num_to_disease_map.json' TESTDATAPATH = '.. /input/cassava-leaf-disease-classi...
Cassava Leaf Disease Classification
21,462,468
facedet = BlazeFace().to(gpu) facedet.load_weights("/kaggle/input/blazeface-pytorch/blazeface.pth") facedet.load_anchors("/kaggle/input/blazeface-pytorch/anchors.npy") _ = facedet.train(False )<load_pretrained>
class CLCdataset(Dataset): def __init__(self, df,isTrain = True): self.df = df self.isTrain = isTrain def __len__(self): return len(self.df) def __getitem__(self, idx): ID = self.df['image_id'].iloc[idx].split('.')[0] img = readImage(ID, TRAINDATAPATH if self.isTrain else TESTDATAPATH) if self.isTrain: img = train_tr...
Cassava Leaf Disease Classification
21,462,468
frames_per_video = 20 video_reader = VideoReader() video_read_fn = lambda x: video_reader.read_frames(x, num_frames=frames_per_video) face_extractor = FaceExtractor(video_read_fn, facedet )<define_variables>
test_transform = A.Compose([ A.Resize(cfg['image_size'], cfg['image_size'],p=1), A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0), ToTensorV2() ] )
Cassava Leaf Disease Classification
21,462,468
<normalization><EOS>
class CFCmodel(nn.Module): def __init__(self, out_dim): super(CFCmodel, self ).__init__() self.model = timm.create_model('efficientnet_b3', pretrained=False) self.model.classifier = nn.Linear(in_features=1536,out_features=out_dim, bias=True) self.model.eval() def forward(self, input): return self.model(input )
Cassava Leaf Disease Classification
14,321,589
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<choose_model_class>
!pip install --quiet /kaggle/input/kerasapplications !pip install --quiet /kaggle/input/efficientnet-git
Cassava Leaf Disease Classification
14,321,589
model = get_model("xception", pretrained=False) model = nn.Sequential(*list(model.children())[:-1]) model[0].final_block.pool = nn.Sequential(nn.AdaptiveAvgPool2d(1)) class Head(torch.nn.Module): def __init__(self, in_f, out_f): super(Head, self ).__init__() self.f = nn.Flatten() self.l = nn.Linear(in_f, 512) self.d...
def seed_everything(seed=0): random.seed(seed) np.random.seed(seed) tf.random.set_seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) os.environ['TF_DETERMINISTIC_OPS'] = '1' seed = 1234 seed_everything(seed) warnings.filterwarnings('ignore' )
Cassava Leaf Disease Classification
14,321,589
def predict_on_video(video_path, batch_size): try: faces = face_extractor.process_video(video_path) face_extractor.keep_only_best_face(faces) if len(faces)> 0: x = np.zeros(( batch_size, input_size, input_size, 3), dtype=np.uint8) n = 0 for frame_data in faces: for face in frame_data["faces"]: resized_face = isotrop...
BATCH_SIZE = 32 * REPLICAS HEIGHT = 512 WIDTH = 512 CHANNELS = 3 N_CLASSES = 5 TTA_STEPS = 10
Cassava Leaf Disease Classification
14,321,589
def predict_on_video_set(videos, num_workers): def process_file(i): filename = videos[i] y_pred = predict_on_video(os.path.join(test_dir, filename), batch_size=frames_per_video) return y_pred with ThreadPoolExecutor(max_workers=num_workers)as ex: predictions = ex.map(process_file, range(len(videos))) return list(pred...
def data_augment(image, label): p_spatial = tf.random.uniform([], 0, 1.0, dtype=tf.float32) p_rotate = tf.random.uniform([], 0, 1.0, dtype=tf.float32) p_pixel_1 = tf.random.uniform([], 0, 1.0, dtype=tf.float32) p_pixel_2 = tf.random.uniform([], 0, 1.0, dtype=tf.float32) p_pixel_3 = tf.random.uniform([], 0, 1.0, dty...
Cassava Leaf Disease Classification
14,321,589
speed_test = False<predict_on_test>
def get_name(file_path): parts = tf.strings.split(file_path, os.path.sep) name = parts[-1] return name def decode_image(image_data): image = tf.image.decode_jpeg(image_data, channels=3) image = tf.cast(image, tf.float32)/ 255.0 return image def center_crop(image): image = tf.reshape(image, [600, 800, CHANNELS]) h, w...
Cassava Leaf Disease Classification
14,321,589
if speed_test: start_time = time.time() speedtest_videos = test_videos[:5] predictions = predict_on_video_set(speedtest_videos, num_workers=4) elapsed = time.time() - start_time print("Elapsed %f sec.Average per video: %f sec." %(elapsed, elapsed / len(speedtest_videos)) )<predict_on_test>
model_path_list = glob.glob('/kaggle/input/cassava-leaf-disease-training-with-tpu-v2-pods/*.h5') model_path_list.sort() print('Models to predict:') print(*model_path_list, sep=' ' )
Cassava Leaf Disease Classification
14,321,589
%%time model.eval() predictions = predict_on_video_set(test_videos, num_workers=4 )<save_to_csv>
def model_fn(input_shape, N_CLASSES): inputs = L.Input(shape=input_shape, name='input_image') base_model = efn.EfficientNetB4(input_tensor=inputs, include_top=False, weights=None, pooling='avg') x = L.Dropout(0.4 )(base_model.output) output = L.Dense(N_CLASSES, activation='tanh', name='output' )(x) model = Model(in...
Cassava Leaf Disease Classification
14,321,589
submission_df = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df.to_csv("submission.csv", index=False )<import_modules>
files_path = f'{database_base_path}test_images/' test_size = len(os.listdir(files_path)) test_preds = np.zeros(( test_size, N_CLASSES)) for model_path in model_path_list: print(model_path) K.clear_session() model.load_weights(model_path) if TTA_STEPS > 0: test_ds = get_dataset(files_path, tta=True ).repeat() ct_steps...
Cassava Leaf Disease Classification
14,321,589
<define_variables><EOS>
submission = pd.DataFrame({'image_id': image_names, 'label': test_preds}) submission.to_csv('submission.csv', index=False) display(submission.head() )
Cassava Leaf Disease Classification
14,079,598
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<define_variables>
warnings.filterwarnings('ignore')
Cassava Leaf Disease Classification
14,079,598
Image('.. /input/deepfake-kernel-data/google_cloud_vm.png' )<define_variables>
training_folder = '.. /input/cassava-leaf-disease-classification/train_images/'
Cassava Leaf Disease Classification
14,079,598
Image('.. /input/deepfake-kernel-data/lr_15e-2_epochs_42_patience_5.png' )<define_variables>
img = Image.open(".. /input/cassava-leaf-disease-classification/train_images/1277648239.jpg") plt.imshow(img) plt.show()
Cassava Leaf Disease Classification
14,079,598
Image('.. /input/deepfake-kernel-data/lr_2e-3_epochs_10_patience_5.png' )<define_variables>
samples_df = pd.read_csv(".. /input/cassava-leaf-disease-classification/train.csv") samples_df = shuffle(samples_df, random_state=42) samples_df["filepath"] = training_folder+samples_df["image_id"] samples_df[:10]
Cassava Leaf Disease Classification
14,079,598
Image('.. /input/deepfake-kernel-data/lr_2e-3_epochs_20_patience_5.png' )<define_variables>
y=samples_df['label'].values y = to_categorical(y )
Cassava Leaf Disease Classification
14,079,598
Image('.. /input/deepfake-kernel-data/lr_4e-3_epochs_12_patience_2.png' )<define_variables>
batch_size = 8 image_size = 512 input_shape =(image_size, image_size, 3) dropout_rate = 0.4 classes_to_predict = sorted(samples_df.label.unique() )
Cassava Leaf Disease Classification
14,079,598
Image('.. /input/deepfake-kernel-data/lr_4e-3_epochs_30_patience_2.png' )<define_variables>
X_train, X_test, y_train, y_test = train_test_split(samples_df, y, random_state=42, test_size=0.2 )
Cassava Leaf Disease Classification
14,079,598
Image('.. /input/deepfake-kernel-data/google_cloud_vm_deepfake_training_screenshot.png' )<set_options>
training_data = tf.data.Dataset.from_tensor_slices(( X_train.filepath.values, y_train)) validation_data = tf.data.Dataset.from_tensor_slices(( X_test.filepath.values, y_test))
Cassava Leaf Disease Classification
14,079,598
%matplotlib inline warnings.filterwarnings("ignore" )<define_variables>
def load_image_and_label_from_path(image_path, label): img = tf.io.read_file(image_path) img = tf.image.decode_jpeg(img, channels=3) return img,label AUTOTUNE = tf.data.experimental.AUTOTUNE training_data = training_data.map(load_image_and_label_from_path, num_parallel_calls=AUTOTUNE) validation_data = validation_da...
Cassava Leaf Disease Classification
14,079,598
test_dir = "/kaggle/input/deepfake-detection-challenge/test_videos/" test_videos = sorted([x for x in os.listdir(test_dir)if x[-4:] == ".mp4"]) frame_h = 5 frame_l = 5 len(test_videos )<import_modules>
training_data_batches = training_data.shuffle(buffer_size=1000 ).batch(batch_size ).prefetch(buffer_size=AUTOTUNE) validation_data_batches = validation_data.shuffle(buffer_size=1000 ).batch(batch_size ).prefetch(buffer_size=AUTOTUNE )
Cassava Leaf Disease Classification
14,079,598
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )<set_options>
adapt_data = tf.data.Dataset.from_tensor_slices(X_train.filepath.values) def adapt_mode(image_path): img = tf.io.read_file(image_path) img = tf.image.decode_jpeg(img, channels=3) img = layers.experimental.preprocessing.Rescaling(1.0 / 255 )(img) return img adapt_data = adapt_data.map(adapt_mode, num_parallel_calls=...
Cassava Leaf Disease Classification
14,079,598
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu<load_pretrained>
data_augmentation_layers = tf.keras.Sequential( [ layers.experimental.preprocessing.RandomCrop(height=image_size, width=image_size), layers.experimental.preprocessing.RandomFlip("horizontal_and_vertical"), layers.experimental.preprocessing.RandomRotation(0.25), layers.experimental.preprocessing.RandomZoom(( -0.2, 0)) ...
Cassava Leaf Disease Classification
14,079,598
facedet = BlazeFace().to(gpu) facedet.load_weights("/kaggle/input/blazeface-pytorch/blazeface.pth") facedet.load_anchors("/kaggle/input/blazeface-pytorch/anchors.npy") _ = facedet.train(False )<load_pretrained>
image = Image.open(".. /input/cassava-leaf-disease-classification/train_images/1481899695.jpg") plt.imshow(image) plt.show()
Cassava Leaf Disease Classification
14,079,598
frames_per_video = 64 video_reader = VideoReader() video_read_fn = lambda x: video_reader.read_frames(x, num_frames=frames_per_video) face_extractor = FaceExtractor(video_read_fn, facedet )<define_variables>
image = tf.expand_dims(np.array(image), 0 )
Cassava Leaf Disease Classification
14,079,598
input_size = 224<normalization>
plt.figure(figsize=(12, 12)) for i in range(16): augmented_image = data_augmentation_layers(image) ax = plt.subplot(4, 4, i + 1) plt.imshow(augmented_image[0]) plt.axis("off" )
Cassava Leaf Disease Classification
14,079,598
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )<choose_model_class>
def create_model() : efficientnet= EfficientNetB4(weights=".. /input/tfkeras-efficientnet-weights/efficientnetb4_notop.h5", include_top=False, input_shape=input_shape, ) input_layer = Input(shape = input_shape) augmented = data_augmentation_layers(input_layer) efficientnet = efficientnet(augmented) pooling = layer...
Cassava Leaf Disease Classification
14,079,598
class MyResNeXt(models.resnet.ResNet): def __init__(self, training=True): super(MyResNeXt, self ).__init__(block=models.resnet.Bottleneck, layers=[3, 4, 6, 3], groups=32, width_per_group=4) self.fc = nn.Linear(2048, 1 )<load_pretrained>
%%time model.get_layer('efficientnetb4' ).get_layer('normalization' ).adapt(adapt_data_batches )
Cassava Leaf Disease Classification
14,079,598
checkpoint = torch.load("/kaggle/input/deepfakes-inference-demo/resnext.pth", map_location=gpu) model = MyResNeXt().to(gpu) model.load_state_dict(checkpoint) _ = model.eval() del checkpoint<predict_on_test>
def log_t(u, t): epsilon = 1e-7 if t == 1.0: return tf.math.log(u + epsilon) else: return(u**(1.0 - t)- 1.0)/(1.0 - t) def bi_tempered_logistic_loss(y_pred, y_true, t1, label_smoothing=0.0): y_pred = tf.cast(y_pred, tf.float32) y_true = tf.cast(y_true, tf.float32) if label_smoothing > 0.0: num_classes = tf.cast...
Cassava Leaf Disease Classification
14,079,598
def predict_on_video(video_path, batch_size): try: faces = face_extractor.process_video(video_path) face_extractor.keep_only_best_face(faces) if len(faces)> 0: x = np.zeros(( batch_size, input_size, input_size, 3), dtype=np.uint8) n = 0 for frame_data in faces: for face in frame_data["faces"]: resized_face = isotrop...
epochs = 8 decay_steps = int(round(len(X_train)/batch_size)) *epochs cosine_decay = CosineDecay(initial_learning_rate=1e-5, decay_steps=decay_steps, alpha=0.3) callbacks = [ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True)] loss = BiTemperedLogisticLoss() model.compile(loss=loss, optim...
Cassava Leaf Disease Classification
14,079,598
def predict_on_video_set(videos, num_workers): def process_file(i): filename = videos[i] y_pred = predict_on_video(os.path.join(test_dir, filename), batch_size=frames_per_video) return y_pred with ThreadPoolExecutor(max_workers=num_workers)as ex: predictions = ex.map(process_file, range(len(videos))) return list(pred...
history = model.fit(training_data_batches, epochs = epochs, validation_data = validation_data_batches, callbacks = callbacks )
Cassava Leaf Disease Classification
14,079,598
speed_test = False<predict_on_test>
model.load_weights("best_model.h5" )
Cassava Leaf Disease Classification
14,079,598
if speed_test: start_time = time.time() speedtest_videos = test_videos[:5] predictions = predict_on_video_set(speedtest_videos, num_workers=4) elapsed = time.time() - start_time print("Elapsed %f sec.Average per video: %f sec." %(elapsed, elapsed / len(speedtest_videos)) )<predict_on_test>
def run_predictions_over_image_list(image_list, folder): predictions = [] with tqdm(total=len(image_list)) as pbar: for image_filename in image_list: pbar.update(1) predictions.append(predict_and_vote(image_filename, folder)) return predictions
Cassava Leaf Disease Classification
14,079,598
predictions = predict_on_video_set(test_videos, num_workers=4 )<save_to_csv>
X_test["results"] = run_predictions_over_image_list(X_test["image_id"], training_folder )
Cassava Leaf Disease Classification
14,079,598
submission_df_resnext = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df_resnext.to_csv("submission_resnext.csv", index=False )<install_modules>
true_positives = 0 prediction_distribution_per_class = {"0":{"0": 0, "1": 0, "2":0, "3":0, "4":0}, "1":{"0": 0, "1": 0, "2":0, "3":0, "4":0}, "2":{"0": 0, "1": 0, "2":0, "3":0, "4":0}, "3":{"0": 0, "1": 0, "2":0, "3":0, "4":0}, "4":{"0": 0, "1": 0, "2":0, "3":0, "4":0}} number_of_images = len(X_test) for idx, pred in ...
Cassava Leaf Disease Classification
14,079,598
!pip install.. /input/deepfake-xception-trained-model/pytorchcv-0.0.55-py2.py3-none-any.whl --quiet<define_variables>
test_folder = '.. /input/cassava-leaf-disease-classification/test_images/' submission_df = pd.DataFrame(columns={"image_id","label"}) submission_df["image_id"] = os.listdir(test_folder) submission_df["label"] = 0
Cassava Leaf Disease Classification
14,079,598
test_dir = "/kaggle/input/deepfake-detection-challenge/test_videos/" test_videos = sorted([x for x in os.listdir(test_dir)if x[-4:] == ".mp4"]) len(test_videos )<set_options>
submission_df["label"] = run_predictions_over_image_list(submission_df["image_id"], test_folder )
Cassava Leaf Disease Classification
14,079,598
<load_pretrained><EOS>
submission_df.to_csv("submission.csv", index=False )
Cassava Leaf Disease Classification
14,887,844
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<load_pretrained>
package_path = '.. /input/pytorch-image-models/pytorch-image-models-master'
Cassava Leaf Disease Classification
14,887,844
frames_per_video = 64 video_reader = VideoReader() video_read_fn = lambda x: video_reader.read_frames(x, num_frames=frames_per_video) face_extractor = FaceExtractor(video_read_fn, facedet )<define_variables>
from datetime import datetime from glob import glob from scipy.ndimage.interpolation import zoom from scipy.special import softmax from skimage import io from sklearn import metrics from sklearn.metrics import log_loss from sklearn.metrics import roc_auc_score, log_loss from sklearn.model_selection import GroupKFold, S...
Cassava Leaf Disease Classification
14,887,844
input_size = 150<normalization>
CFG = { 'fold_num': 7, 'seed': 719, 'model_arch': 'tf_efficientnet_b3_ns', 'img_size': 512, 'epochs': 32, 'train_bs': 32, 'valid_bs': 32, 'lr': 1e-4, 'num_workers': 4, 'accum_iter': 1, 'verbose_step': 1, 'device': 'cuda:0', 'tta': 8 }
Cassava Leaf Disease Classification
14,887,844
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )<choose_model_class>
train = pd.read_csv('.. /input/cassava-leaf-disease-classification/train.csv') train.head()
Cassava Leaf Disease Classification
14,887,844
model = get_model("xception", pretrained=False) model = nn.Sequential(*list(model.children())[:-1]) class Pooling(nn.Module): def __init__(self): super(Pooling, self ).__init__() self.p1 = nn.AdaptiveAvgPool2d(( 1,1)) self.p2 = nn.AdaptiveMaxPool2d(( 1,1)) def forward(self, x): x1 = self.p1(x) x2 = self.p2(x) retur...
train.label.value_counts()
Cassava Leaf Disease Classification
14,887,844
def predict_on_video(video_path, batch_size): try: faces = face_extractor.process_video(video_path) face_extractor.keep_only_best_face(faces) if len(faces)> 0: x = np.zeros(( batch_size, input_size, input_size, 3), dtype=np.uint8) n = 0 for frame_data in faces: for face in frame_data["faces"]: resized_face = isotrop...
submission = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') submission.head()
Cassava Leaf Disease Classification
14,887,844
def predict_on_video_set(videos, num_workers): def process_file(i): filename = videos[i] y_pred = predict_on_video(os.path.join(test_dir, filename), batch_size=frames_per_video) return y_pred with ThreadPoolExecutor(max_workers=num_workers)as ex: predictions = ex.map(process_file, range(len(videos))) return list(pred...
def seed_everything(seed): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = True def get_img(path): im_bgr = cv2.imread(path) im_rgb = im_bgr[:, :, ::-1] r...
Cassava Leaf Disease Classification
14,887,844
speed_test = False<predict_on_test>
class CassavaDataset(Dataset): def __init__( self, df, data_root, transforms=None, output_label=True ): super().__init__() self.df = df.reset_index(drop=True ).copy() self.transforms = transforms self.data_root = data_root self.output_label = output_label def __len__(self): return self.df.shape[0] def __getitem__(sel...
Cassava Leaf Disease Classification
14,887,844
if speed_test: start_time = time.time() speedtest_videos = test_videos[:5] predictions = predict_on_video_set(speedtest_videos, num_workers=4) elapsed = time.time() - start_time print("Elapsed %f sec.Average per video: %f sec." %(elapsed, elapsed / len(speedtest_videos)) )<predict_on_test>
HorizontalFlip, VerticalFlip, IAAPerspective, ShiftScaleRotate, CLAHE, RandomRotate90, Transpose, ShiftScaleRotate, Blur, OpticalDistortion, GridDistortion, HueSaturationValue, IAAAdditiveGaussianNoise, GaussNoise, MotionBlur, MedianBlur, IAAPiecewiseAffine, RandomResizedCrop, IAASharpen, IAAEmboss, RandomBrightnessCon...
Cassava Leaf Disease Classification
14,887,844
%%time model.eval() predictions = predict_on_video_set(test_videos, num_workers=4 )<save_to_csv>
class CassvaImgClassifier(nn.Module): def __init__(self, model_arch, n_class, pretrained=False): super().__init__() self.model = timm.create_model(model_arch, pretrained=pretrained) n_features = self.model.classifier.in_features self.model.classifier = nn.Linear(n_features, n_class) def forward(self, x): x = self.mod...
Cassava Leaf Disease Classification
14,887,844
submission_df_xception = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df_xception.to_csv("submission_xception.csv", index=False )<create_dataframe>
model_path = [ ".. /input/cassava-10-fold-label-smoothing-02/cassava_model_10_fold_labelsmoothing_0.2_small/tf_efficientnet_b3_ns_fold_0_5", ".. /input/cassava-10-fold-label-smoothing-02/cassava_model_10_fold_labelsmoothing_0.2_small/tf_efficientnet_b3_ns_fold_1_9", ".. /input/cassava-10-fold-label-smoothing-02/cassava...
Cassava Leaf Disease Classification
14,887,844
submission_df = pd.DataFrame({"filename": test_videos}) submission_df["label"] = 0.51*submission_df_resnext["label"] + 0.5*submission_df_xception["label"]<save_to_csv>
if __name__ == '__main__': seed_everything(CFG['seed']) tst_preds_all_folds = [] for fold in range(CFG['fold_num']): test = pd.DataFrame() test['image_id'] = sorted(list( os.listdir('.. /input/cassava-leaf-disease-classification/test_images/') )) test_ds = CassavaDataset( test, '.. /input/cassava-leaf-disease-classi...
Cassava Leaf Disease Classification
14,887,844
submission_df.to_csv("submission.csv", index=False )<set_options>
variable_list = %who_ls for _ in variable_list: if _ is not "tst_preds_all_folds": del globals() [_] %who_ls
Cassava Leaf Disease Classification
14,887,844
%matplotlib inline warnings.filterwarnings("ignore" )<define_variables>
sys.path.append('.. /input/pytorch-image-models/pytorch-image-models-master') warnings.filterwarnings('ignore') device = torch.device('cuda' if torch.cuda.is_available() else 'cpu' )
Cassava Leaf Disease Classification
14,887,844
test_dir = "/kaggle/input/deepfake-detection-challenge/test_videos/" test_videos = sorted([x for x in os.listdir(test_dir)if x[-4:] == ".mp4"]) frame_h = 5 frame_l = 5 len(test_videos )<import_modules>
OUTPUT_DIR = './' MODEL_DIR = '.. /input/cassava-resnext/' if not os.path.exists(OUTPUT_DIR): os.makedirs(OUTPUT_DIR) TEST_PATH = '.. /input/cassava-leaf-disease-classification/test_images'
Cassava Leaf Disease Classification
14,887,844
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )<set_options>
class CFG: debug=False num_workers=8 model_name='resnext50_32x4d' size=512 batch_size=32 seed=2020 target_size=5 target_col='label' n_fold=5 trn_fold=[0, 1, 2, 3, 4] inference=True tta=8
Cassava Leaf Disease Classification
14,887,844
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu<load_pretrained>
test = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') test['filepath'] = test.image_id.apply(lambda x: os.path.join('.. /input/cassava-leaf-disease-classification/test_images', f'{x}'))
Cassava Leaf Disease Classification
14,887,844
facedet = BlazeFace().to(gpu) facedet.load_weights("/kaggle/input/blazeface-pytorch/blazeface.pth") facedet.load_anchors("/kaggle/input/blazeface-pytorch/anchors.npy") _ = facedet.train(False )<load_pretrained>
def get_transforms(*, data): if data == 'valid': return A.Compose([ A.Resize(CFG.size, CFG.size), A.Transpose(p=0.5), A.HorizontalFlip(p=0.5), A.VerticalFlip(p=0.5), A.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], ), ToTensorV2() ] )
Cassava Leaf Disease Classification
14,887,844
frames_per_video = 64 video_reader = VideoReader() video_read_fn = lambda x: video_reader.read_frames(x, num_frames=frames_per_video) face_extractor = FaceExtractor(video_read_fn, facedet )<define_variables>
class CustomResNext(nn.Module): def __init__(self, model_name='resnext50_32x4d', pretrained=False): super().__init__() self.model = timm.create_model(model_name, pretrained=pretrained) n_features = self.model.fc.in_features self.model.fc = nn.Linear(n_features, CFG.target_size) def forward(self, x): x = self.model(x)...
Cassava Leaf Disease Classification
14,887,844
input_size = 224<normalization>
def load_state(model_path): model = CustomResNext(CFG.model_name, pretrained=False) try: model.load_state_dict(torch.load(model_path)['model'], strict=True) state_dict = torch.load(model_path)['model'] except: state_dict = torch.load(model_path)['model'] state_dict = {k[7:] if k.startswith('module.')else k: state_dic...
Cassava Leaf Disease Classification
14,887,844
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )<choose_model_class>
model = CustomResNext(CFG.model_name, pretrained=False) states = [load_state(MODEL_DIR+f'{CFG.model_name}_fold{fold}.pth')for fold in CFG.trn_fold] test_dataset = TestDataset(test, transform=get_transforms(data='valid')) test_loader = DataLoader(test_dataset, batch_size=CFG.batch_size, shuffle=False, num_workers=CFG.n...
Cassava Leaf Disease Classification
14,887,844
class MyResNeXt(models.resnet.ResNet): def __init__(self, training=True): super(MyResNeXt, self ).__init__(block=models.resnet.Bottleneck, layers=[3, 4, 6, 3], groups=32, width_per_group=4) self.fc = nn.Linear(2048, 1 )<load_pretrained>
submission = test[["image_id"]] submission["label"] =( np.mean(tst_preds_all_folds, axis=0)* 0.7 + predictions * 0.3 ).argmax(1 )
Cassava Leaf Disease Classification
14,887,844
checkpoint = torch.load("/kaggle/input/deepfakes-inference-demo/resnext.pth", map_location=gpu) model = MyResNeXt().to(gpu) model.load_state_dict(checkpoint) _ = model.eval() del checkpoint<predict_on_test>
submission.to_csv("submission.csv", index=False )
Cassava Leaf Disease Classification
14,887,844
def predict_on_video(video_path, batch_size): try: faces = face_extractor.process_video(video_path) face_extractor.keep_only_best_face(faces) if len(faces)> 0: x = np.zeros(( batch_size, input_size, input_size, 3), dtype=np.uint8) n = 0 for frame_data in faces: for face in frame_data["faces"]: resized_face = isotrop...
submission.to_csv("submission.csv", index=False )
Cassava Leaf Disease Classification
15,066,262
def predict_on_video_set(videos, num_workers): def process_file(i): filename = videos[i] y_pred = predict_on_video(os.path.join(test_dir, filename), batch_size=frames_per_video) return y_pred with ThreadPoolExecutor(max_workers=num_workers)as ex: predictions = ex.map(process_file, range(len(videos))) return list(pred...
class CFG: img_size = 512 num_classes = 5 num_workers = 4 batch_size = 64 epochs = 1 OUTPUT_DIR = './' ROOT_DIR = '.. /input/cassava-leaf-disease-classification/' TRAIN_PATH = '.. /input/cassava-leaf-disease-classification/train_images' TEST_PATH = '.. /input/cassava-leaf-disease-classification/test_images' MODEL_DIR =...
Cassava Leaf Disease Classification
15,066,262
speed_test = False<predict_on_test>
def get_augmentation(data): if data=='test': return A.Compose([ A.Resize(CFG.img_size, CFG.img_size), A.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0), ToTensorV2() ]) test_aug = A.Compose([ A.Resize(CFG.img_size, CFG.img_size), A.Transpose(p=0.5), A.HorizontalFlip(p=0...
Cassava Leaf Disease Classification
15,066,262
if speed_test: start_time = time.time() speedtest_videos = test_videos[:5] predictions = predict_on_video_set(speedtest_videos, num_workers=4) elapsed = time.time() - start_time print("Elapsed %f sec.Average per video: %f sec." %(elapsed, elapsed / len(speedtest_videos)) )<predict_on_test>
class TestDataset(Dataset): def __init__(self, df, transform=None): self.df = df self.file_names = df['image_id'].values self.transform = transform def __len__(self): return len(self.df) def __getitem__(self, idx): file_name = self.file_names[idx] file_path = f'{TEST_PATH}/{file_name}' image = Image.open(file_path ).c...
Cassava Leaf Disease Classification
15,066,262
predictions = predict_on_video_set(test_videos, num_workers=4 )<save_to_csv>
class CustomResNext(nn.Module): def __init__(self, pretrained=False): super().__init__() self.model = timm.create_model('resnext50_32x4d', pretrained=pretrained) n_features = self.model.fc.in_features self.model.fc = nn.Linear(n_features, CFG.num_classes) def forward(self, x): x = self.model(x) return x class LeafMo...
Cassava Leaf Disease Classification
15,066,262
submission_df_resnext = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df_resnext.to_csv("submission_resnext.csv", index=False )<install_modules>
def get_leaf_model(PATH): model = LeafModel() checkpoint = torch.load(PATH) model.load_state_dict(checkpoint['model_state_dict']) model.eval() return model.to(device) def get_resnext_model(PATH): model = CustomResNext() model.load_state_dict(torch.load(PATH)) model.eval() return model.to(device) def get_efficient_b...
Cassava Leaf Disease Classification
15,066,262
!pip install.. /input/deepfake-xception-trained-model/pytorchcv-0.0.55-py2.py3-none-any.whl --quiet<define_variables>
class EnsembledModel() : def __init__(self, model_paths): super().__init__() self.num_models = len(model_paths) self.leafmodel1 = get_leaf_model(model_paths[0]) self.leafmodel2 = get_leaf_model(model_paths[1]) self.effb4_model1 = get_efficient_b4_model(model_paths[2]) self.effb4_model2 = get_efficient_b4_model(mode...
Cassava Leaf Disease Classification
15,066,262
test_dir = "/kaggle/input/deepfake-detection-challenge/test_videos/" test_videos = sorted([x for x in os.listdir(test_dir)if x[-4:] == ".mp4"]) len(test_videos )<set_options>
model_paths = [ '.. /input/cassava-trained-models/with_torch_crossentropy_LeafDiseasesModel Eff-4_fold-1.pt', '.. /input/cassava-trained-models/with_torch_crossentropy_LeafDiseasesModel Eff-4_fold-5.pt', '.. /input/cassava-trained-models/LeafDiseasesModel Eff-4_fold-1.pt', '.. /input/cassava-trained-models/LeafDiseases...
Cassava Leaf Disease Classification
15,066,262
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" )<load_pretrained>
def inference(model, data_loader): epoch_preds = 0 for epoch in range(CFG.epochs): preds = [] for images in tqdm(data_loader): images = images.to(device) logits = model.predict(images) preds += [logits.softmax(1 ).detach().cpu().numpy() ] all_img_preds = np.concatenate(preds, axis=0) epoch_preds += all_img_preds epo...
Cassava Leaf Disease Classification
15,066,262
facedet = BlazeFace().to(gpu) facedet.load_weights("/kaggle/input/blazeface-pytorch/blazeface.pth") facedet.load_anchors("/kaggle/input/blazeface-pytorch/anchors.npy") _ = facedet.train(False )<load_pretrained>
test = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') test_data = TestDataset(test, transform=get_augmentation(data='test')) test_loader = DataLoader(test_data, batch_size=CFG.batch_size, num_workers=CFG.num_workers )
Cassava Leaf Disease Classification
15,066,262
frames_per_video = 64 video_reader = VideoReader() video_read_fn = lambda x: video_reader.read_frames(x, num_frames=frames_per_video) face_extractor = FaceExtractor(video_read_fn, facedet )<define_variables>
predictions = inference(model, test_loader )
Cassava Leaf Disease Classification
15,066,262
<normalization><EOS>
test['label'] = predictions.argmax(1) test[['image_id', 'label']].to_csv(OUTPUT_DIR + 'submission.csv', index=False )
Cassava Leaf Disease Classification
14,949,467
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<choose_model_class>
BATCH_SIZE = 1 image_size = 512 enet_type = ['tf_efficientnet_b4_ns'] * 5 model_path = ['.. /input/moa-b4-baseline/baseline_cld_fold0_epoch8_tf_efficientnet_b4_ns_512.pth', '.. /input/moa-b4-baseline/baseline_cld_fold1_epoch9_tf_efficientnet_b4_ns_512.pth', '.. /input/moa-b4-baseline/baseline_cld_fold2_epoch9_tf_effici...
Cassava Leaf Disease Classification
14,949,467
model = get_model("xception", pretrained=False) model = nn.Sequential(*list(model.children())[:-1]) class Pooling(nn.Module): def __init__(self): super(Pooling, self ).__init__() self.p1 = nn.AdaptiveAvgPool2d(( 1,1)) self.p2 = nn.AdaptiveMaxPool2d(( 1,1)) def forward(self, x): x1 = self.p1(x) x2 = self.p2(x) retur...
transforms_valid = albumentations.Compose([ albumentations.CenterCrop(image_size, image_size, p=1), albumentations.Resize(image_size, image_size), albumentations.Normalize() ] )
Cassava Leaf Disease Classification
14,949,467
def predict_on_video(video_path, batch_size): try: faces = face_extractor.process_video(video_path) face_extractor.keep_only_best_face(faces) if len(faces)> 0: x = np.zeros(( batch_size, input_size, input_size, 3), dtype=np.uint8) n = 0 for frame_data in faces: for face in frame_data["faces"]: resized_face = isotrop...
OUTPUT_DIR = './' MODEL_DIR = '.. /input/cassava-resnext50-32x4d-weights/' if not os.path.exists(OUTPUT_DIR): os.makedirs(OUTPUT_DIR) TRAIN_PATH = '.. /input/cassava-leaf-disease-classification/train_images' TEST_PATH = '.. /input/cassava-leaf-disease-classification/test_images'
Cassava Leaf Disease Classification
14,949,467
def predict_on_video_set(videos, num_workers): def process_file(i): filename = videos[i] y_pred = predict_on_video(os.path.join(test_dir, filename), batch_size=frames_per_video) return y_pred with ThreadPoolExecutor(max_workers=num_workers)as ex: predictions = ex.map(process_file, range(len(videos))) return list(pred...
class CFG: debug=False num_workers=8 model_name='resnext50_32x4d' size=512 batch_size=32 seed=2020 target_size=5 target_col='label' n_fold=5 trn_fold=[0, 1, 2, 3, 4] inference=True
Cassava Leaf Disease Classification
14,949,467
speed_test = False<predict_on_test>
test = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') test['filepath'] = test.image_id.apply(lambda x: os.path.join('.. /input/cassava-leaf-disease-classification/test_images', f'{x}'))
Cassava Leaf Disease Classification
14,949,467
if speed_test: start_time = time.time() speedtest_videos = test_videos[:5] predictions = predict_on_video_set(speedtest_videos, num_workers=4) elapsed = time.time() - start_time print("Elapsed %f sec.Average per video: %f sec." %(elapsed, elapsed / len(speedtest_videos)) )<predict_on_test>
test_dataset_efficient = CLDDataset(test, 'test', transform=transforms_valid) test_loader_efficient = torch.utils.data.DataLoader(test_dataset_efficient, batch_size=BATCH_SIZE, shuffle=False, num_workers=4 )
Cassava Leaf Disease Classification
14,949,467
%%time model.eval() predictions = predict_on_video_set(test_videos, num_workers=4 )<save_to_csv>
def get_transforms(*, data): if data == 'valid': return A.Compose([ A.Resize(CFG.size, CFG.size), A.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], ), ToTensorV2() , ] )
Cassava Leaf Disease Classification
14,949,467
submission_df_xception = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df_xception.to_csv("submission_xception.csv", index=False )<create_dataframe>
class CustomResNext(nn.Module): def __init__(self, model_name='resnext50_32x4d', pretrained=False): super().__init__() self.model = timm.create_model(model_name, pretrained=pretrained) n_features = self.model.fc.in_features self.model.fc = nn.Linear(n_features, CFG.target_size) def forward(self, x): x = self.model(x)...
Cassava Leaf Disease Classification