kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
14,240,018 | 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... | 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 |
14,240,018 | 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... | CFG = {
'fold_num': 5,
'seed': 719,
'model_arch': 'tf_efficientnet_b4_ns',
'img_size': 512,
'epochs': 10,
'train_bs': 32,
'valid_bs': 32,
'lr': 1e-4,
'num_workers': 4,
'accum_iter': 1,
'verbose_step': 1,
'device': 'cuda:0',
'tta': 3,
'used_epochs': [4,5,6,7],
'weights': [1,1,1,1]
} | Cassava Leaf Disease Classification |
14,240,018 | 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... | train = pd.read_csv('.. /input/cassava-leaf-disease-classification/train.csv')
train.head() | Cassava Leaf Disease Classification |
14,240,018 | plt.style.use('seaborn-white')
sns.set_style('white')
plt.rcParams['figure.figsize'] = [16, 10]
plt.rcParams['font.size'] = 14
%matplotlib inline
warnings.filterwarnings("ignore")
BatchNormalization, Activation, GlobalAveragePooling2D,
MaxPooling2D, concatenate, Reshape, Add, multiply)
t_start = time.time()<define_... | train.label.value_counts() | Cassava Leaf Disease Classification |
14,240,018 | basic_name = f'Unet_resnet'
save_model_name = basic_name + '.model'
submission_file = basic_name + '.csv'
TRAIN_IMAGE_DIR = '.. /input/train/images/'
TRAIN_MASK_DIR = '.. /input/train/masks/'
TEST_IMAGE_DIR = '.. /input/test/images/'
img_size = 101
seed=1994
batch_size = 128
epochs = 120<compute_train_metric> | submission = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv')
submission.head() | Cassava Leaf Disease Classification |
14,240,018 | def get_iou_vector(A, B):
batch_size = A.shape[0]
metric = []
for batch in range(batch_size):
t, p = A[batch]>0, B[batch]>0
intersection = np.logical_and(t, p)
union = np.logical_or(t, p)
iou =(np.sum(intersection > 0)+ 1e-10)/(np.sum(union > 0)+ 1e-10)
thresholds = np.arange(0.5, 1, 0.05)
s = []
for thresh in thre... | 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,240,018 | train_df = pd.read_csv(".. /input/train.csv", index_col="id", usecols=[0])
train_df["images"] = [np.array(load_img(TRAIN_IMAGE_DIR + "{}.png".format(idx), color_mode = "grayscale")) / 255
for idx in tqdm_notebook(train_df.index)]
train_df["masks"] = [np.array(load_img(TRAIN_MASK_DIR + "{}.png".format(idx), color_mode ... | 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,240,018 | X = np.array(train_df.images.tolist() ).reshape(-1, img_size, img_size, 1)
y = np.array(train_df.masks.tolist() ).reshape(-1, img_size, img_size, 1)
x_train, x_valid, y_train, y_valid = \
train_test_split(
X, y,
test_size=0.2,
stratify=train_df.coverage_class,
random_state=seed
)<define_search_model> | 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,240,018 | def BatchActivate(x):
x = BatchNormalization()(x)
x = Activation('elu' )(x)
return x
def convolution_block(x, filters, size, strides=(1,1), padding='same', activation=True):
x = Conv2D(filters, size, strides=strides, padding=padding )(x)
if activation==True: x = BatchActivate(x)
return x
def residual_block(blockInp... | 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,240,018 | def build_model(input_layer, start_neurons, DropoutRatio=0.5):
conv1 = unet_layer(input_layer,start_neurons * 1,use_csSE_ratio=2)
pool1 = MaxPooling2D(( 2,2))(conv1)
pool1 = Dropout(DropoutRatio/3 )(pool1)
conv2 = unet_layer(pool1, start_neurons * 2,use_csSE_ratio=2)
pool2 = MaxPooling2D(( 2,2))(conv2)
pool2 = Dro... | if __name__ == '__main__':
seed_everything(CFG['seed'])
folds = StratifiedKFold(n_splits=CFG['fold_num'] ).split(np.arange(train.shape[0]), train.label.values)
for fold,(trn_idx, val_idx)in enumerate(folds):
if fold > 0:
break
print('Inference fold {} started'.format(fold))
valid_ = train.loc[val_idx,:].reset_index(d... | Cassava Leaf Disease Classification |
14,240,018 | def do_augmentation(seqs, seq2_train, X_train, y_train):
seq_det = seqs.to_deterministic()
X_train_aug = seq_det.augment_image(X_train)
X_train_aug = seq2_train.augment_image(X_train_aug)
y_train_aug = seq_det.augment_image(y_train)
if y_train_aug.shape !=(101, 101):
X_train_aug = ia.imresize_single_image(X_train_au... | OUTPUT_DIR = './'
if not os.path.exists(OUTPUT_DIR):
os.makedirs(OUTPUT_DIR)
test['label'] = np.argmax(tst_preds, axis=1)
test.head() | Cassava Leaf Disease Classification |
14,240,018 | <train_model><EOS> | test.to_csv(OUTPUT_DIR+'submission.csv', index=False ) | Cassava Leaf Disease Classification |
14,476,793 | <SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<choose_model_class> | sys.path.append('.. /input/timm-pytorch-image-models/pytorch-image-models-master')
warnings.filterwarnings("ignore" ) | Cassava Leaf Disease Classification |
14,476,793 | model1 = load_model(save_model_name, custom_objects={'my_iou_metric':my_iou_metric})
input_x = model1.layers[0].input
output_layer = model1.layers[-1].input
model2 = Model(input_x, output_layer)
model2.compile(loss=symmetric_lovasz, optimizer=Adam(lr=0.01), metrics=[my_iou_metric_2] )<train_on_grid> | DATA_PATH = '.. /input/cassava-leaf-disease-classification/'
TRAIN_DIR = DATA_PATH + 'train_images/'
TEST_DIR = DATA_PATH + 'test_images/'
MODEL_PATH = '.. /input/cassavanet-baseline-models/'
N_TTA = 8
HEIGHT = 512
WIDTH = 512
CHANNELS = 3
N_CLASSES = 5
MODEL_LIST = [0,1,2,3,4,5]
IMG_MEAN = [0.485, 0.456, 0.406]
IMG_ST... | Cassava Leaf Disease Classification |
14,476,793 | early_stopping = EarlyStopping(monitor='val_my_iou_metric_2', mode = 'max',patience=30, verbose=1)
model_checkpoint = ModelCheckpoint(save_model_name,monitor='val_my_iou_metric_2', mode = 'max', save_best_only=True, verbose=1)
reduce_lr = ReduceLROnPlateau(monitor='val_my_iou_metric_2', mode = 'max',factor=0.5, patie... | 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
SEED = 1234
seed_everything(SEED)
DEVICE = torch.device("cuda:0" if torch.... | Cassava Leaf Disease Classification |
14,476,793 | model = load_model(save_model_name,custom_objects={'my_iou_metric_2': my_iou_metric_2, 'symmetric_lovasz': symmetric_lovasz} )<predict_on_test> | class CassavaNet(nn.Module):
def __init__(self, model_name=None, pretrained=False):
super().__init__()
self.model_name = model_name
if model_name == 'deit_base_patch16_224' or model_name == 'deit_base_patch16_384':
self.model = torch.hub.load('facebookresearch/deit:main', model_name, pretrained=pretrained)
else:
self.... | Cassava Leaf Disease Classification |
14,476,793 | def predict_result(model,x_test,img_size):
x_test_reflect = np.array([np.fliplr(x)for x in x_test])
preds_test = model.predict(x_test ).reshape(-1, img_size, img_size)
preds_test2_refect = model.predict(x_test_reflect ).reshape(-1, img_size, img_size)
preds_test += np.array([ np.fliplr(x)for x in preds_test2_refect]... | class GetData(Dataset):
def __init__(self, Dir, FNames, labels,Type):
self.dir = Dir
self.fnames = FNames
self.lbs = labels
self.type = Type
def __len__(self):
return len(self.fnames)
def __getitem__(self, index):
x = imread(os.path.join(self.dir, self.fnames[index]))
if "train" in self.type:
aug_data = train_transfor... | Cassava Leaf Disease Classification |
14,476,793 | thresholds_ori = np.linspace(0.3, 0.7, 31)
thresholds = np.log(thresholds_ori/(1-thresholds_ori))
ious = np.array([iou_metric_batch(y_valid, preds_valid > threshold)for threshold in tqdm_notebook(thresholds)])
print(ious);<categorify> | Aug_Norm = A.Normalize(mean=IMG_MEAN, std=IMG_STD, max_pixel_value=255.0, p=1.0)
test_aug = Compose([
A.HorizontalFlip(p=0.5),
A.VerticalFlip(p=0.5),
A.ShiftScaleRotate(p = 1.0),
A.ColorJitter(brightness=0.1, contrast=0.2, saturation=0.2, hue=0.00, always_apply=False, p=1.0),
A.RandomCrop(height= HEIGHT, width = WIDTH... | Cassava Leaf Disease Classification |
14,476,793 | def rle_encode(im):
pixels = im.flatten(order='F')
pixels = np.concatenate([[0], pixels, [0]])
runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
runs[1::2] -= runs[::2]
return ' '.join(str(x)for x in runs )<predict_on_test> | models = []
count = 0
for model_fpath in os.listdir(MODEL_PATH):
if count in MODEL_LIST:
print("Model Loaded:",model_fpath)
model_name_split = model_fpath.split('_f')[0]
model = CassavaNet(model_name_split,pretrained = False)
info = torch.load(MODEL_PATH + model_fpath,map_location = torch.device(DEVICE))
model.load_s... | Cassava Leaf Disease Classification |
14,476,793 | test_images = os.listdir(TEST_IMAGE_DIR)
x_test = np.array([(np.array(load_img(TEST_IMAGE_DIR + "{}".format(idx), color_mode = "grayscale")))/ 255
for idx in tqdm_notebook(test_images)] ).reshape(-1, img_size, img_size, 1)
preds_test = predict_result(model,x_test,img_size)
pred_dict = {idx[:10]: rle_encode(np.round(... | submission = pd.DataFrame()
list_files = os.listdir(TEST_DIR)
submission['image_id'] = pd.Series(list_files)
submission['label'] = 0
submission.head() | Cassava Leaf Disease Classification |
14,476,793 | sub = pd.DataFrame.from_dict(pred_dict,orient='index')
sub.index.names = ['id']
sub.columns = ['rle_mask']
sub.to_csv(submission_file )<train_model> | start_time = time.time()
BATCH_SIZE = 1
test_set = GetData(TEST_DIR,submission['image_id'], submission['label'], Type = 'test')
test_loader = DataLoader(test_set, batch_size=BATCH_SIZE, shuffle=False, num_workers=8,pin_memory = True)
with torch.no_grad() :
for i,(images,labels)in enumerate(test_loader):
voting = np.z... | Cassava Leaf Disease Classification |
14,476,793 | <set_options><EOS> | submission.to_csv('submission.csv',index=False)
submission.head() | Cassava Leaf Disease Classification |
14,527,205 | <SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<init_hyperparams> | ')
')
')
| Cassava Leaf Disease Classification |
14,527,205 | def set_learning_rate(optimizer, lr):
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def get_learning_rate(optimizer):
return optimizer.param_groups[0]['lr']
class LearningRate() :
def __init__(self, initial_lr, iteration_type):
self.initial_lr = initial_lr
self.iteration_type = iteration_type
def ge... | !pip install.. /input/cassava-models/Keras_Applications-1.0.8-py3-none-any.whl
!pip install.. /input/cassava-models/efficientnet-1.1.0-py3-none-any.whl
| Cassava Leaf Disease Classification |
14,527,205 |
def save_checkpoint(checkpoint_path, model, optimizer):
state = {'state_dict': model.state_dict() ,
'optimizer' : optimizer.state_dict() }
torch.save(state, checkpoint_path)
print('model saved to %s' % checkpoint_path)
def load_checkpoint(checkpoint_path, model, optimizer):
state = torch.load(checkpoint_path)
mode... | AUTO = tf.data.experimental.AUTOTUNE
EPOCHS = 20
BATCH_SIZE = 32 * strategy.num_replicas_in_sync
IMAGE_SIZE = [512, 512]
SEED = 123
LR = 0.0001
TTA = 10
VERBOSE = 2
N_CLASSES = 5
TEST_FILENAMES = '.. /input/cassava-leaf-disease-classification/test_images/*.jpg' | Cassava Leaf Disease Classification |
14,527,205 | def train_model(model,epochs,
learning_rate,loss_function,
optimizer, dataset, dataset_val,
batch_size
):
snapshot = SnapshotLR(
initial_lr=0.000001,max_lr=0.0001,
total_iters=epochs,n_cycles=30,
iteration_type="epochs"
)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer,
mode="max",
factor=0.97,
m... | def data_augment(image, image_name):
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([]... | Cassava Leaf Disease Classification |
14,527,205 | <categorify><EOS> | def get_model() :
with strategy.scope() :
inp = tf.keras.layers.Input(shape =(*IMAGE_SIZE, 3))
x = efn.EfficientNetB5(weights = None, include_top = False )(inp)
x = tf.keras.layers.GlobalAveragePooling2D()(x)
x = tf.keras.layers.Dropout(0.2 )(x)
output = tf.keras.layers.Dense(N_CLASSES, activation = 'softmax' )(x)
... | Cassava Leaf Disease Classification |
14,520,819 | <SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<normalization> | package_path = '.. /input/pytorch-image-models/pytorch-image-models-master'
| Cassava Leaf Disease Classification |
14,520,819 | def load_image(path,pad=True, mask = False):
flip = False
if "_gael" in path:
path = path.replace("_gael","")
flip = True
img = cv2.imread(str(path))
if flip:
img = cv2.flip(img, 0)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
height, width, _ = img.shape
if pad:
if height % 32 == 0:
y_min_pad = 0
y_max_pad = 0
else... | 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 |
14,520,819 | def pred_resize(predictions,height,width):
if height % 32 == 0:
y_min_pad = 0
y_max_pad = 0
else:
y_pad = 32 - height % 32
y_min_pad = int(y_pad / 2)
y_max_pad = y_pad - y_min_pad
if width % 32 == 0:
x_min_pad = 0
x_max_pad = 0
else:
x_pad = 32 - width % 32
x_min_pad = int(x_pad / 2)
x_max_pad = x_pad - x_min_pad
p... | CFG = {
'fold_num': 5,
'seed': 719,
'model_arch': 'vit_base_patch16_384',
'img_size': 384,
'epochs': 10,
'train_bs': 32,
'valid_bs': 32,
'lr': 1e-4,
'num_workers': 4,
'accum_iter': 1,
'verbose_step': 1,
'device': 'cuda:0',
'used_folds':[0,2,3],
'used_epochs': [7,8,9],
'tta': 3
} | Cassava Leaf Disease Classification |
14,520,819 | def stack_and_resize(predictions,height,width):
preds_stacked = np.vstack(predictions)[:, 0, :, :]
return pred_resize(preds_stacked,height,width )<set_options> | train = pd.read_csv('.. /input/cassava-leaf-disease-classification/train.csv')
train.head() | Cassava Leaf Disease Classification |
14,520,819 | warnings.filterwarnings("ignore" )<load_from_csv> | train.label.value_counts() | Cassava Leaf Disease Classification |
14,520,819 |
directory = '.. /input/tgs-salt-identification-challenge'
depths_df = pd.read_csv(os.path.join(directory, 'train.csv'))
train_path = os.path.join(directory, 'train')
test_path = os.path.join(directory, 'test')
ids_val = _pickle.load(open(".. /input/intermediatetgs/val_index.obj","rb"))
ids_train = _pickle.load(open... | submission = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv')
submission.head() | Cassava Leaf Disease Classification |
14,520,819 | epoch =100
learning_rate = 0.0001
loss_fn = torch.nn.BCELoss()
optimizer = torch.optim.Adam(model.parameters() , lr=learning_rate, eps=1e-7)
load_checkpoint(".. /input/80pytorchgamma/high_val_iou_tgs.pth", model, optimizer)
model = train_model(model,epoch,learning_rate,
loss_fn,optimizer, dataset,
dataset_val,32
)<pr... | 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,520,819 | val_predictions = []
val_masks = []
for image, mask in tqdm_notebook(data.DataLoader(dataset_val, batch_size = 32)) :
image = Variable(image.type(torch.FloatTensor ).cuda())
y_pred = model(image ).cpu().data.numpy()
val_predictions.append(y_pred)
val_masks.append(mask)
val_predictions_stacked = stack_and_resize(val_... | 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,520,819 | metric_by_threshold = []
for threshold in np.linspace(0.3, 0.7, 50):
val_binary_prediction =(val_predictions_stacked > threshold ).astype(int)
iou_values = []
for y_mask, p_mask in zip(val_masks_stacked, val_binary_prediction):
iou = jaccard_similarity_score(y_mask.flatten() , p_mask.flatten())
iou_values.append(iou)... | class ViTBase16(nn.Module):
def __init__(self, n_classes, pretrained=False):
super(ViTBase16, self ).__init__()
self.model = timm.create_model(CFG['model_arch'], pretrained=pretrained)
self.model.head = nn.Linear(self.model.head.in_features, n_classes)
def forward(self, x):
x = self.model(x)
return x | Cassava Leaf Disease Classification |
14,520,819 | threshold = best_threshold
binary_prediction =(all_predictions_stacked > threshold ).astype(int)
all_masks = []
for p_mask in list(binary_prediction):
p_mask = rle_encoding(p_mask)
all_masks.append(' '.join(map(str, p_mask)) )<save_to_csv> | if __name__ == '__main__':
tst_preds_avg = []
seed_everything(CFG['seed'])
for fold in CFG['used_folds']:
print('Inference fold {} started'.format(fold))
test = pd.DataFrame()
test['image_id'] = list(os.listdir('.. /input/cassava-leaf-disease-classification/test_images/'))
test_ds = CassavaDataset(test, '.. /input/cas... | Cassava Leaf Disease Classification |
14,520,819 | submit = pd.DataFrame([test_file_list, all_masks] ).T
submit.columns = ['id', 'rle_mask']
submit.to_csv('submit_baseline_torch.csv', index = False )<load_from_csv> | test['label'] = np.argmax(np.mean(tst_preds_avg, axis=0), axis=-1)
test.head() | Cassava Leaf Disease Classification |
14,520,819 | <count_missing_values><EOS> | test.to_csv('submission.csv', index=False ) | Cassava Leaf Disease Classification |
14,462,070 | <SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<data_type_conversions> | package_paths = ['.. /input/imgclsmob/imgclsmob-master',
'.. /input/efficientnetpytorch/EfficientNet-PyTorch-master',
'.. /input/timm-pytorch-image-models/pytorch-image-models-master']
for package_path in package_paths:
sys.path.append(package_path ) | Cassava Leaf Disease Classification |
14,462,070 | tgs = ".. /input"
tgs1 = ".. /input/tgs-salt-identification-challenge"
def getImage(imgId):
path = Path(tgs+"/train/images/")/ '{}'.format(imgId)
img = imread(path)
return img.astype(np.uint8)
def getGrayImage(imgId):
path = Path(tgs+"/train/images/")/'{}'.format(imgId)
img = imread(path ).astype(np.uint8)
img = c... | import numpy as np
import pandas as pd
import os
import torch
import random
from albumentations import *
from albumentations.pytorch import ToTensorV2
from torch.utils.data import Dataset, DataLoader
import timm
import torch.nn as nn
import torch.nn.functional as F
from efficientnet_pytorch import EfficientNet
from pyt... | Cassava Leaf Disease Classification |
14,462,070 | thresholds = [0.5, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95]
n_thresholds = len(thresholds)
def IoUhelper(TrueMask, predictedMask):
intersection = cv2.bitwise_and(TrueMask, predictedMask)
union = cv2.bitwise_or(TrueMask, predictedMask)
intersectionCnt = cv2.countNonZero(intersection)
unionCnt = cv2.coun... | 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 | Cassava Leaf Disease Classification |
14,462,070 | def rle_encoding(mask):
mask = mask.ravel()
encoding = ""
i = 0
while(i<len(mask)) :
currCnt = 0
start = i
if(mask[i] == 255):
while(i < len(mask)and mask[i] == 255):
currCnt+=1
i+=1
encoding+=(" "+ str(start+1)+ " " + str(currCnt))
else: i+=1
return encoding.strip()<categorify> | class CasDataset(Dataset):
def __init__(self, df, path, transforms):
self.df = df
self.path = path
self.transforms = transforms
def __len__(self):
return self.df.shape[0]
def __getitem__(self, idx):
image = cv2.imread(self.path+self.df.loc[idx, 'image_id'])
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
if self.trans... | Cassava Leaf Disease Classification |
14,462,070 | imgId = train[haveMask].index[18]
rle_orig = train[haveMask].rle_mask[18]
img1 = getImage(imgId+".png")
img2 = getMask(imgId+".png")
rle1 = rle_encoding(np.transpose(img2))
print("Original Encoding
", rle_orig)
print("Len1 = ", len(rle_orig.split()))
print("-------")
print("Encoding
", rle1)
print("Len2 = ", len(r... | class CasModel(nn.Module):
def __init__(self, num_classes=5, model="resnet34"):
super().__init__()
if model == "resnet16":
self.backbone = ptcv_get_model("resnet16", pretrained=False)
self.backbone.features.final_pool = nn.AdaptiveAvgPool2d(1)
self.backbone.output = nn.Sequential(nn.Linear(512, num_classes))
elif mod... | Cassava Leaf Disease Classification |
14,462,070 | TRAIN_IMAGE_DIR = tgs+'/train/images'
TRAIN_MASK_DIR = tgs+'/train/masks'
TEST_MASK_DIR = tgs+'/test/images'
im_height = 128
im_width = 128
train_image_list = os.listdir(TRAIN_IMAGE_DIR)
train_mask_list = os.listdir(TRAIN_MASK_DIR)
test_image_list = os.listdir(TEST_MASK_DIR )<prepare_x_and_y> | def inference_one_epoch(model, data_loader, device):
model.eval()
image_preds_all = []
for step,(imgs)in enumerate(data_loader):
imgs = imgs.to(device ).float()
image_preds = model(imgs)
image_preds_all += [torch.softmax(image_preds, 1 ).detach().cpu().numpy() ]
image_preds_all = np.concatenate(image_preds_all, axis=0... | Cassava Leaf Disease Classification |
14,462,070 | X_train_image = np.zeros(( len(train_image_list),
im_height, im_width, 1), dtype = np.uint8)
Y_train_mask = np.zeros(( len(train_mask_list),
im_height, im_width, 1), dtype = np.uint8)
for i in tqdm(range(len(train_image_list))):
imgId = train_image_list[i]
img = getGrayImage(imgId)
img = cv2.resize(img,(im_height, i... | seed_everything(960630)
test_df = pd.DataFrame()
test_df['image_id'] = list(os.listdir('.. /input/cassava-leaf-disease-classification/test_images/'))
test_data = CasDataset(test_df, '.. /input/cassava-leaf-disease-classification/test_images/', transforms_test ) | Cassava Leaf Disease Classification |
14,462,070 |
<count_values> | test_loader = DataLoader(
test_data,
batch_size=32,
num_workers=8,
shuffle=False,
pin_memory=False,
) | Cassava Leaf Disease Classification |
14,462,070 | print(np.count_nonzero(Y_train_mask[2]))
print(cntOne[2] )<count_unique_values> | test_preds = []
device = torch.device('cuda:0')
model = CasModel(model="resnet34" ).to(device)
for fold in range(5):
model.load_state_dict(torch.load(f'.. /input/casresnet34/resnet34_f_{fold}.pth'))
with torch.no_grad() :
for t in range(tta):
test_preds += [inference_one_epoch(model, test_loader, device)] | Cassava Leaf Disease Classification |
14,462,070 | x = np.array([0, 1.0, 3.0, 1.6])
bins = np.array([0, 1.0, 2.5, 4.0, 10.0])
inds = np.digitize(x, bins)
np.unique(inds )<count_unique_values> | test_preds = np.mean(test_preds, axis=0)
test_df['label'] = np.argmax(test_preds, axis=1)
test_df.head() | Cassava Leaf Disease Classification |
14,462,070 | <split><EOS> | test_df.to_csv('submission.csv', index=False ) | Cassava Leaf Disease Classification |
13,863,118 | <SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<normalization> | !pip install --quiet /kaggle/input/kerasapplications
!pip install --quiet /kaggle/input/efficientnet-git | Cassava Leaf Disease Classification |
13,863,118 | def augment(X, Y):
print("FlipLR")
X1 = np.append(X, [np.fliplr(x)for x in X], axis = 0)
Y1 = np.append(Y, [np.fliplr(y)for y in Y], axis = 0)
print("Roll")
X = np.append(X1, [np.roll(x, 40, axis = 1)for x in X1], axis = 0)
Y = np.append(Y1, [np.roll(y, 40, axis = 1)for y in Y1], axis = 0)
m = X.shape[0]
np.rando... | 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,863,118 | print(train_Y[70, :, :, 0])
train_X =(train_X.astype(np.float32)/255.0)
train_Y =(train_Y/255.0 ).astype(np.bool ).astype(np.uint8)
val_X =(val_X.astype(np.float32)/255.0)
val_Y =(val_Y/255.0 ).astype(np.bool ).astype(np.uint8)
print(train_X.dtype, train_Y.dtype)
print(train_Y[70, :, :, 0] )<import_modules> | strategy = tf.distribute.get_strategy()
AUTO = tf.data.experimental.AUTOTUNE
REPLICAS = strategy.num_replicas_in_sync
print(f'REPLICAS: {REPLICAS}' ) | Cassava Leaf Disease Classification |
13,863,118 | import keras
<import_modules> | BATCH_SIZE = 16 * REPLICAS
HEIGHT = 512
WIDTH = 512
CHANNELS = 3
N_CLASSES = 5
TTA_STEPS = 8 | Cassava Leaf Disease Classification |
13,863,118 | from keras.models import *
from keras.layers import *
from keras.optimizers import *
from keras.callbacks import *<define_search_model> | 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 |
13,863,118 | def batchActivate(x):
x = BatchNormalization()(x)
x = Activation('relu' )(x)
return x
def residualBlock(blockInput, numChannel, matchChannel = False):
x = batchActivate(blockInput)
x = Conv2D(numChannel,(3, 3), activation= None, padding = "same",
use_bias = False )(x)
x = batchActivate(x)
x = Conv2D(numChannel,(3,... | 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])
... | Cassava Leaf Disease Classification |
13,863,118 | inputs = Input(shape =(im_height, im_width, 1))
init = Conv2D(16,(7, 7), activation="relu", padding = "same" )(inputs)
conv1 = residualBlock(init, 16)
conv1 = residualBlock(conv1, 16)
c1 = residualBlock(conv1, 16)
c1 = BatchNormalization()(c1)
p1 = MaxPooling2D(pool_size=(2, 2))(c1)
conv2 = residualBlock(p1, 32, ... | 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 |
13,863,118 | earlyStopping = EarlyStopping(patience = 20, verbose = 1)
checkpointer = ModelCheckpoint('model-tgs-salt-1.h5',monitor = 'val_my_iou_metric',
verbose=1, save_best_only=True)
reducelr=ReduceLROnPlateau(monitor='val_my_iou_metric',patience=5,
min_lr=0.00001, verbose=1,factor=0.5)
epochs = 50
batch_size = 64
history = ... | 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 (.5 )(base_model.output)
output = L.Dense(N_CLASSES, activation='softmax', name='output' )(x)
model = Model... | Cassava Leaf Disease Classification |
13,863,118 | model1 = load_model("./model-tgs-salt-1.h5",
custom_objects = {'my_iou_metric':my_iou_metric} )<set_options> | 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 |
13,863,118 | <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 |
13,643,882 | <SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<predict_on_test> | import numpy as np
import os
import pandas as pd
from fastai.vision.all import * | Cassava Leaf Disease Classification |
13,643,882 | totIoU = 0.0
m = val_X.shape[0]
for i in tqdm(range(m)) :
img = val_X[i:i+1, :, :]
origMask = val_Y[i:i+1, :, :]
predMask = model1.predict(img)
origMask = cv2.inRange(origMask[0, :, :, 0], 0.55, 255)
predMask = cv2.inRange(predMask[0, :, :, 0], 0.55, 255)
totIoU += meanHit(origMask, predMask)
print("mean IoU = ", t... | set_seed(42 ) | Cassava Leaf Disease Classification |
13,643,882 | X_test_image = X_test_image/255.0<set_options> | train_df = pd.read_csv(dataset_path/'train.csv' ) | Cassava Leaf Disease Classification |
13,643,882 | gc.collect()<categorify> | train_df['path'] = train_df['image_id'].map(lambda x:dataset_path/'train_images'/x)
train_df = train_df.drop(columns=['image_id'])
train_df = train_df.sample(frac=1 ).reset_index(drop=True)
train_df.head(10 ) | Cassava Leaf Disease Classification |
13,643,882 | origSize =(101, 101)
submit_names = []
submit_rleMasks = []
for i in tqdm(range(len(test_image_list))):
img = X_test_image[i:i+1,:,:]
predMask = model1.predict(img)
predMask = cv2.inRange(predMask[0, :, :, 0], 0.55, 255)
predMask = cv2.resize(predMask, origSize)
submit_names.append(test_image_list[i][:-4])
submit_... | dls = ImageDataLoaders.from_df(train_df,
splitter=RandomSplitter(0.2, seed=42),
label_col=0,
fn_col=1,
bs=bs,
item_tfms=item_tfms,
batch_tfms=batch_tfms ) | Cassava Leaf Disease Classification |
13,643,882 | sub = pd.DataFrame({'id':submit_names, 'rle_mask': submit_rleMasks})
print(sub.shape)
sub.head()<feature_engineering> | learn = cnn_learner(dls, resnet50, metrics=[error_rate, accuracy] ).to_native_fp16() | Cassava Leaf Disease Classification |
13,643,882 | for i in tqdm(range(len(test_image_list))):
if(len(sub.iloc[i, 1])== 0):
sub.iloc[i, 1] = np.nan<save_to_csv> | learn.freeze()
learn.fine_tune(1, cbs=[MixUp(0.5)] ) | Cassava Leaf Disease Classification |
13,643,882 | sub.to_csv("tgsModel1.csv", index = False )<install_modules> | learn.save('estagio-1' ) | Cassava Leaf Disease Classification |
13,643,882 | !pip3 install pycocotools<set_options> | learn = learn.load('estagio-1' ) | Cassava Leaf Disease Classification |
13,643,882 | %matplotlib inline
%reload_ext autoreload
%autoreload 2
print(torch.__version__)
torch.cuda.is_available()
torch.backends.cudnn.benchmark=True<load_from_csv> | learn = learn.to_native_fp32() | Cassava Leaf Disease Classification |
13,643,882 | MASKS_FN = 'train.csv'
TRAIN_DN = Path('train/images/')
MASKS_DN = Path('train/masks/')
TEST = Path('test/images/')
PATH = Path('/kaggle/input/tgs-salt-identification-challenge/')
PATH128 = Path('/tmp/128/')
TMP = Path('/tmp/')
MODEL = Path('/tmp/model/')
PRETRAINED = Path('/kaggle/input/is-there-salt-resnet34/m... | learn.save('estagio-2' ) | Cassava Leaf Disease Classification |
13,643,882 | train_names_png = [TRAIN_DN/f for f in os.listdir(PATH/TRAIN_DN)]
train_names = list(seg.index.values)
masks_names_png = [MASKS_DN/f for f in os.listdir(PATH/MASKS_DN)]
test_names_png = [TEST/f for f in os.listdir(PATH/TEST)]<categorify> | sample_df = pd.read_csv(dataset_path/'sample_submission.csv')
sample_df.head() | Cassava Leaf Disease Classification |
13,643,882 | with ThreadPoolExecutor(4)as e: e.map(resize_mask, train_names_png )<categorify> | _sample_df = sample_df.copy()
_sample_df['path'] = _sample_df['image_id'].map(lambda x:dataset_path/'test_images'/x)
_sample_df = _sample_df.drop(columns=['image_id'])
test_dl = dls.test_dl(_sample_df ) | Cassava Leaf Disease Classification |
13,643,882 | with ThreadPoolExecutor(4)as e: e.map(resize_mask, masks_names_png )<categorify> | test_dl.show_batch() | Cassava Leaf Disease Classification |
13,643,882 | with ThreadPoolExecutor(4)as e: e.map(resize_mask, test_names_png )<define_variables> | preds, _ = learn.tta(dl=test_dl, n=8, beta=0 ) | Cassava Leaf Disease Classification |
13,643,882 | PATH = PATH128<import_modules> | sample_df['label'] = preds.argmax(dim=-1 ).numpy() | Cassava Leaf Disease Classification |
13,643,882 | <compute_test_metric><EOS> | sample_df.to_csv('submission.csv',index=False ) | Cassava Leaf Disease Classification |
13,055,692 | <SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<load_pretrained> | Path.ls = lambda x: list(x.iterdir())
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
effnet_path = '.. /input/efficientnet-pytorch/'
sys.path.append(effnet_path)
test_path = Path(".. /input/cassava-leaf-disease-classification/test_images")
test_fnames = test_path.ls() | Cassava Leaf Disease Classification |
13,055,692 | def get_base() :
layers = cut_model(f(True), cut)
return nn.Sequential(*layers)
def load_pretrained(model, path):
weights = torch.load(PRETRAINED, map_location=lambda storage, loc: storage)
model.load_state_dict(weights, strict=False)
return model<categorify> | test_df = pd.read_csv(".. /input/cassava-leaf-disease-classification/sample_submission.csv")
train_df = pd.read_csv(".. /input/cassava-leaf-disease-classification/train.csv")
num_classes = train_df['label'].nunique() | Cassava Leaf Disease Classification |
13,055,692 | class SaveFeatures() :
features=None
def __init__(self, m): self.hook = m.register_forward_hook(self.hook_fn)
def hook_fn(self, module, input, output): self.features = output
def remove(self): self.hook.remove()<concatenate> | mean = [0.4589, 0.5314, 0.3236]
std = [0.2272, 0.2297, 0.2200]
test_tfms = albumentations.Compose([
albumentations.RandomResizedCrop(256, 256),
albumentations.HorizontalFlip(p=0.5),
albumentations.HueSaturationValue(
hue_shift_limit=0.2,
sat_shift_limit=0.2,
val_shift_limit=0.2,
p=0.5
),
albumentations.RandomBrightne... | Cassava Leaf Disease Classification |
13,055,692 | class UnetBlock(nn.Module):
def __init__(self, up_in, x_in, n_out):
super().__init__()
up_out = x_out = n_out//2
self.x_conv = nn.Conv2d(x_in, x_out, 1)
self.tr_conv = nn.ConvTranspose2d(up_in, up_out, 2, stride=2)
self.bn = nn.BatchNorm2d(n_out)
def forward(self, up_p, x_p):
up_p = self.tr_conv(up_p)
x_p = self.x_... | test_dl = make_dataloaders(df=test_df, split="test" ) | Cassava Leaf Disease Classification |
13,055,692 | class UnetModel() :
def __init__(self,model,name='unet'):
self.model,self.name = model,name
def get_layer_groups(self, precompute):
lgs = list(split_by_idxs(children(self.model.rn), [lr_cut]))
return lgs + [children(self.model)[1:]]<prepare_x_and_y> | class EfficientNetModel(nn.Module):
def __init__(self, arch="b4", dropout=0.2, n_out=5,
pretrained=True, freeze=True):
super().__init__()
if pretrained:
self.model = EfficientNet.from_pretrained(f"efficientnet-{arch}")
if freeze:
for p in self.model.parameters() :
p.requires_grad = False
else:
self.model = EfficientNe... | Cassava Leaf Disease Classification |
13,055,692 | x_names = [f'{x}.png' for x in train_names]
x_names_path = np.array([str(TRAIN_DN/x)for x in x_names])
y_names = [x for x in x_names]
y_names_path = np.array([str(MASKS_DN/x)for x in x_names] )<set_options> | model = model = EfficientNetModel(pretrained=False, freeze=False ).to(device)
model.load_state_dict(torch.load(".. /input/pytorch-better-normalization-onecycle-lr-train/effnet.pt", map_location=device))
model.eval() ; | Cassava Leaf Disease Classification |
13,055,692 | aug_tfms = [RandomRotate(4, tfm_y=TfmType.CLASS),
RandomFlip(tfm_y=TfmType.CLASS),
RandomLighting(0.05, 0.05, tfm_y=TfmType.CLASS)]
<split> | def inference_one_pass(model, test_dl):
model.eval()
all_preds = []
with torch.no_grad() :
for batch in tqdm(test_dl):
preds = model(batch.to(device))
all_preds.append(preds)
return torch.cat(all_preds, dim=0 ) | Cassava Leaf Disease Classification |
13,055,692 | lr=3e-3
wd=1e-7
lrs = np.array([lr/100,lr/10,lr])
n_folds = 8
out=np.zeros(( 18000,sz,sz))
alpha = 0
for i in range(n_folds):
val_size = 4000//n_folds
val_idxs=list(range(i*val_size,(i+1)*val_size))
(( val_x,trn_x),(val_y,trn_y)) = split_by_idx(val_idxs, x_names_path, y_names_path)
test_x = np.array(test_names_png)
... | num_passes = 5
tta = None
for _ in range(num_passes):
all_preds = inference_one_pass(model, test_dl)
if tta is None:
tta = all_preds
else:
tta += all_preds
tta /= float(num_passes)
label_preds = tta.argmax(dim=1 ) | Cassava Leaf Disease Classification |
13,055,692 | out = out/n_folds
alpha = alpha/n_folds<categorify> | test_df['label'] = label_preds.cpu().numpy() | Cassava Leaf Disease Classification |
13,055,692 | <create_dataframe><EOS> | test_df.to_csv("submission.csv", index=False ) | Cassava Leaf Disease Classification |
13,021,276 | <SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<set_options> | tez_path = '.. /input/tez-lib/'
effnet_path = '.. /input/efficientnet-pytorch/'
sys.path.append(tez_path)
sys.path.append(effnet_path ) | Cassava Leaf Disease Classification |
13,021,276 | plt.style.use('seaborn-white')
sns.set_style("white")
<train_model> | import os
import albumentations
import pandas as pd
import numpy as np
import tez
from tez.datasets import ImageDataset
import torch
import torch.nn as nn
from torch.nn import functional as F
from efficientnet_pytorch import EfficientNet | Cassava Leaf Disease Classification |
13,021,276 | img_size_ori = 101
img_size_target = 128
def upsample(img):
if img_size_ori == img_size_target:
return img
return resize(img,(img_size_target, img_size_target), mode='constant', preserve_range=True)
def downsample(img):
if img_size_ori == img_size_target:
return img
return resize(img,(img_size_ori, img_size_ori), mode... | class LeafModel(tez.Model):
def __init__(self, num_classes):
super().__init__()
self.effnet = EfficientNet.from_name("efficientnet-b4")
self.dropout = nn.Dropout(0.1)
self.out = nn.Linear(1792, num_classes)
self.step_scheduler_after = "epoch"
def forward(self, image, targets=None):
batch_size, _, _, _ = image.shape
... | Cassava Leaf Disease Classification |
13,021,276 | debug=False
train_df = pd.read_csv(".. /input/tgs-salt-identification-challenge/train.csv", index_col="id", usecols=[0])
depths_df = pd.read_csv(".. /input/tgs-salt-identification-challenge/depths.csv", index_col="id")
train_df = train_df.join(depths_df)
test_df = depths_df[~depths_df.index.isin(train_df.index)]
if ... | test_aug = albumentations.Compose([
albumentations.RandomResizedCrop(256, 256),
albumentations.Transpose(p=0.5),
albumentations.HorizontalFlip(p=0.5),
albumentations.VerticalFlip(p=0.5),
albumentations.HueSaturationValue(
hue_shift_limit=0.2,
sat_shift_limit=0.2,
val_shift_limit=0.2,
p=0.5
),
albumentations.RandomBri... | Cassava Leaf Disease Classification |
13,021,276 | def dice_coef(y_true, y_pred):
y_true_f = K.flatten(y_true)
y_pred = K.cast(y_pred, 'float32')
y_pred_f = K.cast(K.greater(K.flatten(y_pred), 0.5), 'float32')
intersection = y_true_f * y_pred_f
score = 2.* K.sum(intersection)/(K.sum(y_true_f)+ K.sum(y_pred_f))
return score
def dice_loss(y_true, y_pred):
smooth = 1.
... | dfx = pd.read_csv(".. /input/cassava-leaf-disease-classification/sample_submission.csv")
image_path = ".. /input/cassava-leaf-disease-classification/test_images/"
test_image_paths = [os.path.join(image_path, x)for x in dfx.image_id.values]
test_targets = dfx.label.values
test_dataset = ImageDataset(
image_paths=test_... | Cassava Leaf Disease Classification |
13,021,276 | train_df["images"] = [np.array(load_img(".. /input/tgs-salt-identification-challenge/train/images/{}.png".format(idx), grayscale=True)) / 255 for idx in tqdm_notebook(train_df.index)]<feature_engineering> | train_dfx = pd.read_csv(".. /input/cassava-leaf-disease-classification/train.csv")
model = LeafModel(num_classes=train_dfx.label.nunique())
model.load(".. /input/leafmodel/model.bin" ) | Cassava Leaf Disease Classification |
13,021,276 | train_df["masks"] = [np.array(load_img(".. /input/tgs-salt-identification-challenge/train/masks/{}.png".format(idx), grayscale=True)) / 255 for idx in tqdm_notebook(train_df.index)]<feature_engineering> | final_preds = None
for j in range(5):
preds = model.predict(test_dataset, batch_size=32, n_jobs=-1, device="cuda")
temp_preds = None
for p in preds:
if temp_preds is None:
temp_preds = p
else:
temp_preds = np.vstack(( temp_preds, p))
if final_preds is None:
final_preds = temp_preds
else:
final_preds += temp_preds
fina... | Cassava Leaf Disease Classification |
13,021,276 | train_df["coverage"] = train_df.masks.map(np.sum)/ pow(img_size_ori, 2 )<categorify> | final_preds = final_preds.argmax(axis=1 ) | Cassava Leaf Disease Classification |
13,021,276 | def cov_to_class(val):
for i in range(0, 11):
if val * 10 <= i :
return i
train_df["coverage_class"] = train_df.coverage.map(cov_to_class )<define_search_model> | dfx.label = final_preds | Cassava Leaf Disease Classification |
13,021,276 | def conv_block(m, dim, acti, bn, res, do=0):
n = Conv2D(dim, 3, activation=acti, padding='same' )(m)
n = BatchNormalization()(n)if bn else n
n = Dropout(do )(n)if do else n
n = Conv2D(dim, 3, activation=acti, padding='same' )(n)
n = BatchNormalization()(n)if bn else n
return Concatenate()([m, n])if res else n
d... | dfx.to_csv("submission.csv", index=False ) | Cassava Leaf Disease Classification |
13,048,268 | n_split=6
skf=StratifiedKFold(n_splits=n_split)
models=[]
historys=[]
epochs = 200
batch_size = 32
if debug:
epochs=3
sub_model_list=[1,0,2,3,5,2]
for i in range(n_split):
print('reading '+str(i)+' model')
if i==1:
data_root='baseline-0-760-0-143-6fold-split-1st/'
elif i==2:
data_root='fork-of-baseline-0-760-0-143-6f... | %matplotlib inline
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None ) | Cassava Leaf Disease Classification |
13,048,268 | threshes=[]
for i,(trdex,valdex)in enumerate(skf.split(X=train_df.index.values,y=train_df.coverage_class.values)) :
ids_valid=train_df.index.values[valdex]
y_valid=np.array(train_df.loc[ids_valid].masks.map(upsample ).tolist() ).reshape(-1, img_size_target, img_size_target, 1)
x_valid=np.array(train_df.loc[ids_valid].... | data_dir = '/kaggle/input/cassava-leaf-disease-classification'
train = pd.read_csv(os.path.join(data_dir, 'train.csv'))
sub = pd.read_csv(os.path.join(data_dir, 'sample_submission.csv')) | Cassava Leaf Disease Classification |
13,048,268 | def RLenc(img, order='F', format=True):
bytes = img.reshape(img.shape[0] * img.shape[1], order=order)
runs = []
r = 0
pos = 1
for c in bytes:
if(c == 0):
if r != 0:
runs.append(( pos, r))
pos += r
r = 0
pos += 1
else:
r += 1
if r != 0:
runs.append(( pos, r))
pos += r
r = 0
if format:
z = ''
for rr in runs:
z += '{} ... | 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 | Cassava Leaf Disease Classification |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.