kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
14,949,467
submission_df = pd.DataFrame({"filename": test_videos} )<feature_engineering>
class enet_v2(nn.Module): def __init__(self, backbone, out_dim, pretrained=False): super(enet_v2, self ).__init__() self.enet = timm.create_model(backbone, pretrained=pretrained) in_ch = self.enet.classifier.in_features self.myfc = nn.Linear(in_ch, out_dim) self.enet.classifier = nn.Identity() def forward(self, x): x...
Cassava Leaf Disease Classification
14,949,467
r1 = 0.46441 r2 = 0.52189 total = r1 + r2 r11 = r1/total r22 = r2/total<feature_engineering>
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,949,467
<save_to_csv><EOS>
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,264,662
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<set_options>
OUTPUT_DIR = "./" MODEL_DIR = ".. /input/cassava-model/" 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,264,662
%matplotlib inline <create_dataframe>
class CFG: debug = False num_workers = 4 models = [ "tf_efficientnet_b4_ns", "vit_base_patch16_384", "seresnext50_32x4d", ] size = { "tf_efficientnet_b3_ns": 512, "tf_efficientnet_b4_ns": 512, "vit_base_patch16_384": 384, "deit_base_patch16_384": 384, "seresnext50_32x4d": 512, } batch_size = 64 seed = 7097 target_size ...
Cassava Leaf Disease Classification
14,264,662
frames_per_vid = [17, 25, 30, 32, 35, 36, 40] public_LB = [0.46788, 0.46776, 0.46611, 0.46542, 0.46643, 0.46484, 0.46635] df_viz = pd.DataFrame({'frames_per_vid': frames_per_vid, 'public_LB':public_LB} )<define_variables>
tta_weight_sum = CFG.no_tta_weight +(CFG.tta - 1) weight_sum = sum([CFG.weight[model] for model in CFG.models])* tta_weight_sum
Cassava Leaf Disease Classification
14,264,662
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>
test = pd.read_csv(".. /input/cassava-leaf-disease-classification/sample_submission.csv") test.head()
Cassava Leaf Disease Classification
14,264,662
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )<set_options>
class CassvaImgClassifier(nn.Module): def __init__(self, model_name="resnext50_32x4d", pretrained=False): super().__init__() if model_name == "deit_base_patch16_384": self.model = torch.hub.load(".. /input/fair-deit", model_name, pretrained=pretrained, source="local") n_features = self.model.head.in_features self.mode...
Cassava Leaf Disease Classification
14,264,662
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu<load_pretrained>
def inference(model, states, test_loader, device, data_parallel): model.to(device) if device == torch.device("cuda")and data_parallel: model = torch.nn.DataParallel(model) tk0 = tqdm(enumerate(test_loader), total=len(test_loader)) probs = [] for i,(images)in tk0: images = images.to(device) avg_preds = [] for state i...
Cassava Leaf Disease Classification
14,264,662
<load_pretrained><EOS>
predictions = None for model_name in CFG.models: for i in range(CFG.tta): model = CassvaImgClassifier(model_name, pretrained=False) states = [] for saved_model in ["best", "final"]: if CFG.trn_fold[model_name][saved_model] != []: LOGGER.info( f"========== Model: {model_name}, TTA: {i}, Saved: {saved_model}, Fold: {CF...
Cassava Leaf Disease Classification
15,007,591
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<define_variables>
!pip install -U /kaggle/input/kerasapplications
Cassava Leaf Disease Classification
15,007,591
input_size = 224<normalization>
!pip install -U /kaggle/input/efficientnet/efficientnet-master
Cassava Leaf Disease Classification
15,007,591
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )<choose_model_class>
!pip install -U /kaggle/input/tensorflowresnets/TensorFlow-ResNets
Cassava Leaf Disease Classification
15,007,591
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>
def is_interactive() : return 'runtime' in get_ipython().config.IPKernelApp.connection_file IS_INTERACTIVE = is_interactive() print(IS_INTERACTIVE )
Cassava Leaf Disease Classification
15,007,591
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>
import pandas as pd, numpy as np from kaggle_datasets import KaggleDatasets import tensorflow as tf, re, math import tensorflow.keras.backend as K import efficientnet.tfkeras as efn from sklearn.model_selection import KFold from sklearn.metrics import roc_auc_score import matplotlib.pyplot as plt from tqdm import tqdm ...
Cassava Leaf Disease Classification
15,007,591
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...
def _bytes_feature(value): if isinstance(value, type(tf.constant(0))): value = value.numpy() return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def _float_feature(value): return tf.train.Feature(float_list=tf.train.FloatList(value=[value])) def _int64_feature(value): return tf.train.Feature(int...
Cassava Leaf Disease Classification
15,007,591
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...
RESNEXT_ID = 10 N_TFRECORDS = 20 IMAGE_HEIGHT = 600 IMAGE_WIDTH = 800 os.mkdir('test_tfrecords_600') test_df = pd.DataFrame(os.listdir('.. /input/cassava-leaf-disease-classification/test_images/'), columns=['image_name']) test_df['tfr_group'] = test_df.index%N_TFRECORDS
Cassava Leaf Disease Classification
15,007,591
speed_test = False<predict_on_test>
for tfr_group in range(N_TFRECORDS): df = test_df[test_df.tfr_group==tfr_group] if df.shape[0]>0: tfr_filename = 'test_tfrecords_600/cassava_test{}-{}.tfrec'.format(tfr_group,df.shape[0]) print("Writing",tfr_filename) with tf.io.TFRecordWriter(tfr_filename)as writer: for index,row in tqdm(df.iterrows()): image_name =...
Cassava Leaf Disease Classification
15,007,591
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>
N_TFRECORDS = 20 IMAGE_HEIGHT = 666 IMAGE_WIDTH = 500 os.mkdir('test_tfrecords_500') test_df = pd.DataFrame(os.listdir('.. /input/cassava-leaf-disease-classification/test_images/'), columns=['image_name']) test_df['tfr_group'] = test_df.index%N_TFRECORDS
Cassava Leaf Disease Classification
15,007,591
predictions = predict_on_video_set(test_videos, num_workers=4 )<save_to_csv>
for tfr_group in range(N_TFRECORDS): df = test_df[test_df.tfr_group==tfr_group] if df.shape[0]>0: tfr_filename = 'test_tfrecords_500/cassava_test{}-{}.tfrec'.format(tfr_group,df.shape[0]) print("Writing",tfr_filename) with tf.io.TFRecordWriter(tfr_filename)as writer: for index,row in tqdm(df.iterrows()): image_name =...
Cassava Leaf Disease Classification
15,007,591
submission_df = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df.to_csv("submission.csv", index=False )<set_options>
DEVICE = "GPU" FOLDS = 5 FOLD_TO_RUN = [0,1,2,3,4] BATCH_SIZE = 128 EPOCHS = 15 N_WORKERS = 4
Cassava Leaf Disease Classification
15,007,591
%matplotlib inline <create_dataframe>
if DEVICE == "TPU": print("connecting to TPU...") try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() print('Running on TPU ', tpu.master()) except ValueError: print("Could not connect to TPU") tpu = None if tpu: try: print("initializing TPU...") tf.config.experimental_connect_to_cluster(tpu) tf.tpu.exp...
Cassava Leaf Disease Classification
15,007,591
frames_per_vid = [17, 25, 30, 32, 35, 36, 38, 39, 40, 49, 56, 64, 72, 80, 81, 82, 100] public_LB = [0.46788, 0.46776, 0.46611, 0.46542, 0.46643, 0.46484, 0.46444, 0.46603, 0.46635, 0.46620, 0.46481, 0.46441, 0.46559, 0.46518, 0.46453, 0.46482, 0.46495] df_viz = pd.DataFrame({'frames_per_vid': frames_per_vid, 'public_LB...
GCS_PATH = '.' files_test_600 = np.sort(np.array(tf.io.gfile.glob(GCS_PATH + '/test_tfrecords_600/*.tfrec'))) files_test_500 = np.sort(np.array(tf.io.gfile.glob(GCS_PATH + '/test_tfrecords_500/*.tfrec'))) print(files_test_600) print(files_test_500 )
Cassava Leaf Disease Classification
15,007,591
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>
ROT_ = 180.0 SHR_ = 2.0 HZOOM_ = 8.0 WZOOM_ = 8.0 HSHIFT_ = 8.0 WSHIFT_ = 8.0
Cassava Leaf Disease Classification
15,007,591
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )<set_options>
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift): rotation = math.pi * rotation / 180. shear = math.pi * shear / 180. def get_3x3_mat(lst): return tf.reshape(tf.concat([lst],axis=0), [3,3]) c1 = tf.math.cos(rotation) s1 = tf.math.sin(rotation) one = tf.constant([1],dtype='float32') ...
Cassava Leaf Disease Classification
15,007,591
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu<load_pretrained>
def read_unlabeled_tfrecord(example): tfrec_format = { 'image' : tf.io.FixedLenFeature([], tf.string), "image_name": tf.io.FixedLenFeature([], tf.string) } example = tf.io.parse_single_example(example, tfrec_format) return example['image'], example['image_name'] def prepare_image(img, augment=True, tta=None, dim=256)...
Cassava Leaf Disease Classification
15,007,591
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_dataset(files, augment = False, tta=None, shuffle = False, repeat = False, batch_size=16, dim=512): ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO) if repeat: ds = ds.repeat() if shuffle: ds = ds.shuffle(1024*8) opt = tf.data.Options() opt.experimental_deterministic = False ds = ds.with_options(o...
Cassava Leaf Disease Classification
15,007,591
frames_per_video = 65 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>
EFNS = [efn.EfficientNetB0, efn.EfficientNetB1, efn.EfficientNetB2, efn.EfficientNetB3, efn.EfficientNetB4, efn.EfficientNetB5, efn.EfficientNetB6, efn.EfficientNetB7] def build_model(dim=128, ef=0): inp = tf.keras.layers.Input(shape=(dim,dim,3)) if ef == RESNEXT_ID: base = models.ResNeXt50(input_shape=(dim,dim,3),weig...
Cassava Leaf Disease Classification
15,007,591
input_size = 224<normalization>
def get_lr_callback(batch_size=8): lr_start = 0.000005 lr_max = 0.00000125 * REPLICAS * batch_size lr_min = 0.000001 lr_ramp_ep = 5 lr_sus_ep = 0 lr_decay = 0.8 def lrfn(epoch): if epoch < lr_ramp_ep: lr =(lr_max - lr_start)/ lr_ramp_ep * epoch + lr_start elif epoch < lr_ramp_ep + lr_sus_ep: lr = lr_max else: lr =(lr_m...
Cassava Leaf Disease Classification
15,007,591
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )<choose_model_class>
print('Getting test_ids') IMG_SIZE = 500 NUM_TEST_IMAGES = count_data_items(files_test_500) ds_test = get_dataset(files_test_500,augment=False,repeat=False,shuffle=False, dim=IMG_SIZE,batch_size=BATCH_SIZE*4) test_ids_ds = ds_test.map(lambda image, idnum: idnum ).unbatch() test_ids = next(iter(test_ids_ds.batch(NUM_...
Cassava Leaf Disease Classification
15,007,591
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>
tta_counter = 0
Cassava Leaf Disease Classification
15,007,591
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>
VERBOSE = IS_INTERACTIVE def generate_submission(EFF_NET,category,TTA): if EFF_NET == RESNEXT_ID: model_root = f'.. /input/cassava-category-{category}/ResNext50/ResNext50/' else: model_root = f'.. /input/cassava-category-{category}/B{EFF_NET}/B{EFF_NET}/' if category%2==0: IMG_SIZE = 600 files_test = files_test_600 eli...
Cassava Leaf Disease Classification
15,007,591
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...
CASSAVA_WEIGHTS = {(1, 'B0'): 0.0, (1, 'B1'): 0.0, (3, 'ResNext50'): 0.2144082584031884, (4, 'B0'): 0.04051596743735366, (4, 'B1'): 0.0059384033956569274, (4, 'B2'): 0.0, (4, 'B3'): 0.2772041683999385, (4, 'B4'): 1.0, (4, 'B5'): 1.0, (4, 'ResNext50'): 1.0, (5, 'B3'): 0.47634532056167095, (5, 'B4'): 0.0, (1,...
Cassava Leaf Disease Classification
15,007,591
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...
submission = pd.DataFrame(test_ids,columns=['image_id']) for x in range(5): submission[x] = 0 submission = submission.set_index('image_id') submission = submission.sort_index() submission
Cassava Leaf Disease Classification
15,007,591
speed_test = False<predict_on_test>
import random
Cassava Leaf Disease Classification
15,007,591
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>
submission.to_csv('predictions.csv') submission
Cassava Leaf Disease Classification
15,007,591
predictions = predict_on_video_set(test_videos, num_workers=4 )<save_to_csv>
K.clear_session()
Cassava Leaf Disease Classification
15,007,591
submission_df = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df.to_csv("submission.csv", index=False )<set_options>
device = cuda.get_current_device() device.reset()
Cassava Leaf Disease Classification
15,007,591
%reload_ext autoreload %autoreload 2 %matplotlib inline <define_variables>
package_paths = [ '.. /input/pytorch-image-models/pytorch-image-models-master', '.. /input/image-fmix/FMix-master' ] for pth in package_paths: sys.path.append(pth)
Cassava Leaf Disease Classification
15,007,591
path = Path('data/MarchMadness') dest = path dest.mkdir(parents=True, exist_ok=True) input_path = '.. /input/mens-machine-learning-competition-2019' data_path = '.. /input/ncaa-19-dataprep/data/MarchMadness'<load_from_csv>
from glob import glob from sklearn.model_selection import GroupKFold, StratifiedKFold import cv2 from skimage import io import torch from torch import nn import os from datetime import datetime import time import random import cv2 import torchvision from torchvision import transforms import pandas as pd import numpy as...
Cassava Leaf Disease Classification
15,007,591
df_test = pd.read_csv(f'{data_path}/df_test.csv', low_memory=False) df_msr = pd.read_csv(f'{data_path}/df_msr.csv', low_memory=False) df = pd.read_csv(f'{data_path}/df.csv', low_memory=False) sub = pd.read_csv(f'{input_path}/SampleSubmissionStage2.csv', low_memory=False) seeds = pd.read_csv(f'{input_path}/datafiles...
import os import pandas as pd import albumentations as albu import matplotlib.pyplot as plt import json import seaborn as sns import cv2 import albumentations as albu import numpy as np
Cassava Leaf Disease Classification
15,007,591
def random_seed(seed_value, use_cuda): np.random.seed(seed_value) torch.manual_seed(seed_value) random.seed(seed_value) if use_cuda: torch.cuda.manual_seed(seed_value) torch.cuda.manual_seed_all(seed_value) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False <merge>
import torch import torch.nn as nn import torchvision.models as models import torch.optim as optim from torch.utils.data import Dataset, DataLoader from torch.optim.lr_scheduler import ReduceLROnPlateau from sklearn.metrics import accuracy_score from sklearn.model_selection import StratifiedKFold, GroupKFold, KFold, tr...
Cassava Leaf Disease Classification
15,007,591
def join_df(left, right, left_on, right_on=None, on=None, how='left', suffix='_y'): if right_on is None: right_on = left_on return left.merge(right, left_on=left_on, right_on=right_on, on=on, how=how, suffixes=("", suffix))<drop_column>
CFG = { 'fold_num': 10, 'seed': 719, 'model_arch': 'tf_efficientnet_b3_ns', 'img_size': 384, 'epochs': 32, 'train_bs': 32, 'valid_bs': 32, 'lr': 1e-4, 'num_workers': 4, 'accum_iter': 1, 'verbose_step': 1, 'device': 'cuda:0', 'tta': 4, 'used_epochs': [8], 'weights': [1,1,1,1,1] }
Cassava Leaf Disease Classification
15,007,591
base_cols = ['Score'] drop_cols = ['Loc', 'PointDiff_1', 'RankDiff_1', 'Seed_1', 'Seed_2'] for c in base_cols: drop_cols.append(c+'_1') drop_cols.append(c+'_Opp_1') drop_cols.append(c+'_2') drop_cols.append(c+'_Opp_2') df.drop(drop_cols, axis=1, inplace=True) df_test.drop(drop_cols, axis=1, inplace=True) <drop_col...
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
15,007,591
dep_var = 'result' cat_vars = ['Season', 'TeamId_1', 'TeamId_2', 'Coach_1', 'Coach_2', 'Top5_1', 'Top5_2', 'Top25_1', 'Top25_2', 'Top50_1', 'Top50_2', 'ConfAbbrev_1', 'ConfAbbrev_2', 'Is_ConfGm', 'isMajor_1', 'isMajor_2'] cont_vars = [c for c in df.columns if c not in cat_vars] cont_vars.remove('result') test = Tabula...
class CassavaDataset(Dataset): def __init__(self,df:pd.DataFrame,imfolder:str,train:bool = True, transforms=None): self.df=df self.imfolder=imfolder self.train=train self.transforms=transforms def __getitem__(self,index): im_path=os.path.join(self.imfolder,self.df.iloc[index]['image_id']) x=cv2.imread(im_path,cv2.IMRE...
Cassava Leaf Disease Classification
15,007,591
learn = tabular_learner(data, layers=[200,100], emb_drop=0.2, metrics=[accuracy]) learn.model<train_model>
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class CustomDeiT(nn.Module): def __init__(self, model_name='model_name', pretrained=False): super().__init__() self.model = torch.hub.load('facebookresearch/deit:main', model_name, pretrained=0) n_features = self.model.head.in_features self.model.h...
Cassava Leaf Disease Classification
15,007,591
learn.fit_one_cycle(2, wd=0.05 )<save_model>
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
15,007,591
learn.save('m_stage2_1') <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
15,007,591
preds, _ = learn.get_preds(DatasetType.Test) eps = 1e-5 df_test['Pred'] = np.clip(preds[:,1], eps, 1-eps) df_test = df_test[['Season', 'TeamId_1', 'TeamId_2', 'Pred']] df_msr = df_msr[['Season', 'TeamId_1', 'TeamId_2', 'result']] df_msr.reset_index(inplace=True, drop=True) df_m = join_df(df_msr, df_test, ['Season', ...
tst_preds = np.mean(tst_preds, axis=0)
Cassava Leaf Disease Classification
15,007,591
import math import numpy as np import pandas as pd from sklearn.metrics import log_loss from sklearn.preprocessing import StandardScaler<merge>
test_pred = pd.DataFrame(tst_preds) test_pred['image_id'] = test.image_id
Cassava Leaf Disease Classification
15,007,591
def Aggregate(teamcompactresults1, teamcompactresults2, merged_results, regularseasoncompactresults): winningteam1compactresults = pd.merge(how='left', left=teamcompactresults1, right=regularseasoncompactresults, left_on=['year', 'team1'], right_on=['Season', 'WTeamID']) winningteam1compactresults.drop(['Season', 'Day...
test_pred = test_pred.set_index('image_id' )
Cassava Leaf Disease Classification
15,007,591
def GrabData() : tourneyresults = pd.read_csv('.. /input/stage2datafiles/NCAATourneyCompactResults.csv') tourneyseeds = pd.read_csv('.. /input/stage2datafiles/NCAATourneySeeds.csv') regularseasoncompactresults = \ pd.read_csv('.. /input/stage2datafiles/RegularSeasonCompactResults.csv') sample = pd.read_csv('.. /inpu...
test_pred.to_csv('vit_predictions.csv' )
Cassava Leaf Disease Classification
15,007,591
train, test = GrabData() trainlabels = train.result.values train.drop('result', inplace=True, axis=1) train.fillna(-1, inplace=True) testids = test.ID.values test.drop(['ID', 'Pred'], inplace=True, axis=1) test.fillna(-1, inplace=True )<normalization>
Cassava Leaf Disease Classification
15,007,591
ss = StandardScaler() train[train.columns[3:]] = np.round(ss.fit_transform(train[train.columns[3:]]), 6) train['target'] = trainlabels <save_to_csv>
Cassava Leaf Disease Classification
15,007,591
train[train.columns[3:]].to_csv('mensdata.csv',index=False )<compute_test_metric>
Cassava Leaf Disease Classification
15,007,591
def Outputs(data): return 1./(1.+np.exp(-data)) def GPIndividual1(data): predictions =(1.0*np.tanh(((((((((((( data["team2Seed"])+(data["team1Lmin"])) /2.0)) +(data["team2Seed"])) /2.0)) +(data["team2Seed"])) /2.0)) -(data["team1Seed"])))+ 1.0*np.tanh(((((((((( data["team1Lmin"])/ 2.0)) +(data["team2Seed"])) /2.0)) *((...
Cassava Leaf Disease Classification
15,007,591
print(log_loss(train.target,GPIndividual1(train))) print(log_loss(train.target,GPIndividual2(train))) print(log_loss(train.target,GPIndividual3(train))) print(log_loss(train.target,GP(train)) )<save_to_csv>
pred1 = pd.read_csv('./predictions.csv',index_col=0 ).sort_index() pred3 = pd.read_csv('./vit_predictions.csv',index_col=0 ).sort_index() pred1 = pred1.div(pred1.sum(axis=1),axis=0) pred3 = pred3.div(pred3.sum(axis=1),axis=0 )
Cassava Leaf Disease Classification
15,007,591
test[test.columns[3:]] = np.round(ss.transform(test[test.columns[3:]]), 6) predictions = GP(test) submission = pd.DataFrame({'ID': testids, 'Pred': np.clip(predictions.values,.01,.99)}) submission.to_csv('submission.csv', index=False )<load_from_csv>
submission = 0.8*pred1 + 0.2*pred3
Cassava Leaf Disease Classification
15,007,591
data_dir = '.. /input/' df_seeds = pd.read_csv(data_dir + 'stage2datafiles/NCAATourneySeeds.csv') df_tour = pd.read_csv(data_dir + 'stage2datafiles/NCAATourneyCompactResults.csv') df_massey = pd.read_csv(data_dir + 'masseyordinals/MasseyOrdinals.csv' )<data_type_conversions>
submission['label'] = submission.idxmax(axis=1) submission = submission.reset_index() submission
Cassava Leaf Disease Classification
15,007,591
<groupby><EOS>
submission[['image_id','label']].to_csv('submission.csv',index=False )
Cassava Leaf Disease Classification
14,644,890
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<drop_column>
Cassava Leaf Disease Classification
14,644,890
df_tour.drop(['DayNum', 'WScore', 'LScore', 'WLoc', 'NumOT'], inplace=True, axis=1) df_tour.tail() df_subs_tour = df_tour[df_tour['Season'] >= min(massey_seasons)]<feature_engineering>
import os import glob import random import shutil import warnings import json import itertools import numpy as np import pandas as pd from collections import Counter import plotly.express as px import matplotlib.pyplot as plt import seaborn as sns import keras from keras.preprocessing.image import ImageDataGenerator im...
Cassava Leaf Disease Classification
14,644,890
WMassey = [0]*len(df_subs_tour) LMassey = [0]*len(df_subs_tour) for ind, row in df_subs_tour.iterrows() : season = row['Season'] wid = row['WTeamID'] lid = row['LTeamID'] WMassey[ind] = df_SeasonTeamID[df_SeasonTeamID['Season']==season][wid].values[0] LMassey[ind] = df_SeasonTeamID[df_SeasonTeamID['Season']==season][...
work_dir = '.. /input/cassava-leaf-disease-classification/' train_path = '/kaggle/input/cassava-leaf-disease-classification/train_images'
Cassava Leaf Disease Classification
14,644,890
df_subs_tour['WMassey'] = WMassey df_subs_tour['LMassey'] = LMassey df_subs_tour.head(10 )<merge>
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 = 123 seed_everything(seed) warnings.filterwarnings('ignore' )
Cassava Leaf Disease Classification
14,644,890
df_winseeds = df_seeds.rename(columns={'TeamID':'WTeamID', 'int_seed':'WSeed'}) df_loseseeds = df_seeds.rename(columns={'TeamID':'LTeamID', 'int_seed':'LSeed'}) df_d = pd.merge(left=df_subs_tour, right=df_winseeds, how='left', on=['Season', 'WTeamID']) df_concat = pd.merge(left=df_d, right=df_loseseeds, on=['Season'...
data = pd.read_csv(work_dir + 'train.csv') print(data['label'].value_counts() )
Cassava Leaf Disease Classification
14,644,890
df_wins = pd.DataFrame() df_wins['SeedDiff'] = df_concat['SeedDiff'] df_wins['MasseyDiff'] = df_concat['MasseyDiff'] df_wins['Result'] = 1 df_losses = pd.DataFrame() df_losses['SeedDiff'] = -df_concat['SeedDiff'] df_losses['MasseyDiff'] = -df_concat['MasseyDiff'] df_losses['Result'] = 0 df_predictions = pd.concat(( df_...
with open(work_dir + 'label_num_to_disease_map.json')as f: real_labels = json.load(f) real_labels = {int(k):v for k,v in real_labels.items() } data['class_name'] = data['label'].map(real_labels) real_labels
Cassava Leaf Disease Classification
14,644,890
X_train = df_predictions[['SeedDiff', 'MasseyDiff']].values y_train = df_predictions['Result'].values X_train, y_train = shuffle(X_train, y_train )<import_modules>
train, test = train_test_split(data, test_size = 0.05, random_state = 123, stratify = data['class_name'] )
Cassava Leaf Disease Classification
14,644,890
from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV<train_on_grid>
IMG_SIZE = 300 size =(IMG_SIZE,IMG_SIZE) n_CLASS = 5 BATCH_SIZE = 15
Cassava Leaf Disease Classification
14,644,890
rf = RandomForestClassifier() rf_params = {'n_estimators': [100, 200, 300, 400, 500, 1000]} rf_grid = GridSearchCV(rf, rf_params, scoring='neg_log_loss', refit=True) rf_grid.fit(X_train, y_train) print('Best log_loss: {:.4}, with best C: {}'.format(rf_grid.best_score_, rf_grid.best_params_['n_estimators']))<train_on_...
datagen_train = ImageDataGenerator( preprocessing_function = tf.keras.applications.efficientnet.preprocess_input, rotation_range = 40, width_shift_range = 0.2, height_shift_range = 0.2, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True, vertical_flip = True, fill_mode = 'nearest', ) datagen_val = ImageData...
Cassava Leaf Disease Classification
14,644,890
logreg = LogisticRegression(solver='lbfgs') params = {'C': [0.001,0.01, 1, 10, 100]} log_grid = GridSearchCV(logreg, params, scoring='neg_log_loss', refit=True) log_grid.fit(X_train, y_train) print('Best log_loss: {:.4}, with best C: {}'.format(log_grid.best_score_, log_grid.best_params_['C']))<load_from_csv>
train_set = datagen_train.flow_from_dataframe( train, directory=train_path, seed=123, x_col='image_id', y_col='class_name', target_size = size, class_mode='categorical', interpolation='nearest', shuffle = True, batch_size = BATCH_SIZE, ) test_set = datagen_val.flow_from_dataframe( test, directory=train_path, seed=1...
Cassava Leaf Disease Classification
14,644,890
df_sub = pd.read_csv('.. /input/SampleSubmissionStage2.csv') df_massey_2019 = pd.read_csv('.. /input/prelim2019_masseyordinals/Prelim2019_MasseyOrdinals.csv') len_sub = len(df_sub )<groupby>
def create_model() : model = Sequential() model.add( EfficientNetB5( input_shape =(IMG_SIZE, IMG_SIZE, 3), include_top = False, weights='imagenet', drop_connect_rate=0.6, ) ) model.add(GlobalAveragePooling2D()) model.add(Flatten()) model.add(Dense( 256, activation='relu', bias_regularizer=tf.keras.regularizers.L...
Cassava Leaf Disease Classification
14,644,890
df_massey_2019 = df_massey_2019[df_massey_2019['Season']==2019] df_m = df_massey_2019.groupby('TeamID' ).mean() df_m.reset_index(drop=False, inplace=True) df_m.head()<string_transform>
EPOCHS = 50 STEP_SIZE_TRAIN = train_set.n // train_set.batch_size STEP_SIZE_TEST = test_set.n // test_set.batch_size
Cassava Leaf Disease Classification
14,644,890
def getYearTeams(ID): return(int(x)for x in ID.split('_'))<prepare_x_and_y>
def model_fit() : leaf_model = create_model() loss = tf.keras.losses.CategoricalCrossentropy( from_logits = False, label_smoothing=0.0001, name='categorical_crossentropy' ) leaf_model.compile( optimizer = Adam(learning_rate = 1e-3), loss = loss, metrics = ['categorical_accuracy'] ) es = EarlyStopping( monitor='v...
Cassava Leaf Disease Classification
14,644,890
X_test = np.zeros(shape=(len_sub, 2)) for ii, row in df_sub.iterrows() : year, t1, t2 = getYearTeams(row['ID']) t1_seed = df_seeds[(df_seeds['TeamID'] == t1)&(df_seeds['Season'] == year)]['int_seed'].values[0] t2_seed = df_seeds[(df_seeds['TeamID'] == t2)&(df_seeds['Season'] == year)]['int_seed'].values[0] t1_mass = d...
sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True)) K.set_session(sess )
Cassava Leaf Disease Classification
14,644,890
<save_to_csv><EOS>
try: final_model = keras.models.load_model('Cassava_best_model.h5') except Exception as e: with tf.device('/GPU:0'): results = model_fit() print('Train Categorical Accuracy: ', max(results.history['categorical_accuracy'])) print('Test Categorical Accuracy: ', max(results.history['val_categorical_accuracy']))
Cassava Leaf Disease Classification
14,398,182
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<set_options>
debug = True MODEL_DIR = '.. /input/20t-efficientnet-b3-cutmix-tta'
Cassava Leaf Disease Classification
14,398,182
%matplotlib inline <install_modules>
OUTPUT_DIR = './' 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' assert len(glob.glob(f'{MODEL_DIR}/*.yml')) ==1 config_path = glob.glob(f'{MODEL_DIR}/*.yml')[0]
Cassava Leaf Disease Classification
14,398,182
!git clone https://github.com/radekosmulski/whale <import_modules>
with open(config_path)as f: config = yaml.load(f) INFO = config['info'] TAG = config['tag'] CFG = config['cfg'] CFG['train'] = False CFG['inference'] = True inference_batch_size = 8
Cassava Leaf Disease Classification
14,398,182
from whale.utils import map5<set_options>
def get_result(result_df): preds = result_df['preds'].values labels = result_df['label'].values score = get_score(labels, preds) LOGGER.info(f'Score: {score:<.5f}') return score def get_aug_name(compose): aug_list = [] for aug in compose: aug_list.append(aug.__class__.__name__) return aug_list def get_aug_score(aug_...
Cassava Leaf Disease Classification
14,398,182
fastprogress.fastprogress.NO_BAR = True master_bar, progress_bar = force_console_behavior() fastai.basic_train.master_bar, fastai.basic_train.progress_bar = master_bar, progress_bar<import_modules>
test = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') test.head()
Cassava Leaf Disease Classification
14,398,182
from fastai import * from fastai.vision import *<define_variables>
class TrainDataset(Dataset): def __init__(self, df, transform=None): self.df = df self.file_names = df['image_id'].values self.labels = df['label'].values self.transform = transform def __len__(self): return len(self.df) def __getitem__(self, idx): file_name = self.file_names[idx] file_path = f'{TRAIN_PATH}/{file_name...
Cassava Leaf Disease Classification
14,398,182
path = Path('.. /input/humpback-whale-identification/') path_test = Path('.. /input/humpback-whale-identification/test') path_train = Path('.. /input/humpback-whale-identification/train' )<load_from_csv>
def _get_augmentations(aug_list): process = [] for aug in aug_list: if aug == 'Resize': process.append(Resize(CFG['size'], CFG['size'])) elif aug == 'RandomResizedCrop': process.append(RandomResizedCrop(CFG['size'], CFG['size'])) elif aug == 'CenterCrop': process.append(CenterCrop(CFG['size'], CFG['size'])) elif aug ==...
Cassava Leaf Disease Classification
14,398,182
df = pd.read_csv(path/'train.csv') df.head() val_fns = {'69823499d.jpg'}<define_variables>
def get_transforms(*, aug_list): return Compose( _get_augmentations(aug_list) )
Cassava Leaf Disease Classification
14,398,182
fn2label = {row[1].Image: row[1].Id for row in df.iterrows() } path2fn = lambda path: re.search('\w*\.jpg$', path ).group(0 )<define_variables>
class CustomModel(nn.Module): def __init__(self, model_name, pretrained=False): super().__init__() self.model = timm.create_model(model_name, pretrained=pretrained) if hasattr(self.model, 'classifier'): n_features = self.model.classifier.in_features self.model.classifier = nn.Linear(n_features, CFG['target_size']) el...
Cassava Leaf Disease Classification
14,398,182
name = f'res50-full-train'<define_variables>
model = CustomModel(TAG['model_name'], pretrained=False) model_paths = glob.glob(f'{MODEL_DIR}/*.pth') model_paths.sort() states = [torch.load(path)for path in model_paths] test_dataset = TTADataset(test, TEST_PATH, ttas=ttas) test_loader = DataLoader(test_dataset, batch_size=inference_batch_size, shuffle=False, num...
Cassava Leaf Disease Classification
14,398,182
SZ = 224 BS = 64 NUM_WORKERS = 0 SEED=0<define_variables>
def valid_inference(model, state, test_loader, device): model.to(device) tk0 = tqdm(enumerate(test_loader), total=len(test_loader)) probs = [] for i,(images, labels)in tk0: images = images.to(device) labels = labels.to(device) batch_size, n_crops, c, h, w = images.size() images = images.view(-1, c, h, w) model.load...
Cassava Leaf Disease Classification
14,398,182
MODEL_PATH = "/kaggle/working/"<train_on_grid>
if debug: train = pd.read_csv('.. /input/cassava-leaf-disease-classification/train.csv') folds = train.copy() Fold = StratifiedKFold(n_splits=CFG['n_fold'], shuffle=True, random_state=CFG['seed']) for n,(train_index, val_index)in enumerate(Fold.split(folds, folds[CFG['target_col']])) : folds.loc[val_index, 'fold'] = ...
Cassava Leaf Disease Classification
14,398,182
<define_variables><EOS>
if debug: LOGGER.info(f"========== augmentation result ==========") get_aug_score(oof_aug_preds, oof_df['label'], ttas) get_aug_csv(oof_aug_preds, oof_df, ttas )
Cassava Leaf Disease Classification
13,694,227
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<load_from_csv>
!pip install.. /input/keras-efficientnet-whl/Keras_Applications-1.0.8-py3-none-any.whl !pip install.. /input/keras-efficientnet-whl/efficientnet-1.1.1-py3-none-any.whl
Cassava Leaf Disease Classification
13,694,227
df = pd.read_csv('.. /input/radek-whale-oversample/oversampled_train_and_val.csv' )<choose_model_class>
%matplotlib inline print("Tensorflow version " + tf.__version__)
Cassava Leaf Disease Classification
13,694,227
%%time learn = create_cnn(data, models.resnet50, lin_ftrs=[2048], model_dir=MODEL_PATH) learn.load(f'{name}-stage-6' )<predict_on_test>
data = pd.read_csv(".. /input/cassava-leaf-disease-classification/train.csv" )
Cassava Leaf Disease Classification
13,694,227
preds, _ = learn.get_preds(DatasetType.Test )<concatenate>
IMG_SIZE = 512 BATCH_SIZE = 18 STEPS_PER_EPOCH = len(data)*0.8/BATCH_SIZE VALIDATION_STEPS = len(data)*0.2/BATCH_SIZE EPOCHS = 20
Cassava Leaf Disease Classification
13,694,227
preds = torch.cat(( preds, torch.ones_like(preds[:, :1])) , 1 )<feature_engineering>
model = keras.models.load_model('.. /input/notebook454e103ae7/EfficientNetB0.h5' )
Cassava Leaf Disease Classification
13,694,227
preds[:, 5004] = 0.06<define_variables>
submission_file = pd.read_csv(os.path.join('.. /input/cassava-leaf-disease-classification/sample_submission.csv')) submission_file
Cassava Leaf Disease Classification
13,694,227
classes = learn.data.classes + ['new_whale']<import_modules>
preds = [] for image_id in submission_file.image_id: image = Image.open(os.path.join(f'.. /input/cassava-leaf-disease-classification/test_images/{image_id}')) image = image.resize(( IMG_SIZE, IMG_SIZE)) image = np.expand_dims(image, axis = 0) preds.append(np.argmax(model.predict(image))) submission_file['label'] = pr...
Cassava Leaf Disease Classification
13,694,227
<save_to_csv><EOS>
submission_file.to_csv('submission.csv', index = False )
Cassava Leaf Disease Classification
14,158,600
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<prepare_output>
import os import json import numpy as np import pandas as pd import seaborn as sn import matplotlib.pyplot as plt import cv2
Cassava Leaf Disease Classification
14,158,600
create_submission(preds, learn.data, name, classes )<feature_engineering>
BASE_DIR = ".. /input/cassava-leaf-disease-classification/"
Cassava Leaf Disease Classification
14,158,600
pd.read_csv(f'{name}.csv' ).Id.str.split().apply(lambda x: x[0] == 'new_whale' ).mean()<load_from_csv>
with open(os.path.join(BASE_DIR, "label_num_to_disease_map.json")) as file: map_classes = json.loads(file.read()) map_classes = {int(k): v for k, v in map_classes.items() } print(json.dumps(map_classes, indent=4))
Cassava Leaf Disease Classification
14,158,600
<define_variables>
input_files = os.listdir(os.path.join(BASE_DIR, "train_images")) print(f"Number of train images: {len(input_files)}" )
Cassava Leaf Disease Classification