kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
13,048,268 | preds_test=np.zeros([len(x_test),img_size_target, img_size_target],dtype=np.float32)
avg_thres=0
test_batch_length=1000
for i in range(n_split):
model = models[i]
avg_thres+=threshes[i]
for b in range(int(len(x_test)/test_batch_length)) :
print(str(i)+' split: '+str(b)+' batch')
x_test_batch=x_test[b*test_batch_lengt... | train['label'].value_counts().sort_index() | Cassava Leaf Disease Classification |
13,048,268 | pred_dict = {idx: RLenc(np.round(downsample(preds_test[i])> avg_thres)) for i, idx in enumerate(tqdm_notebook(test_df.index.values)) }<save_to_csv> | class CassavaDataset(Dataset):
def __init__(self, data_dir, transform=None, phase='train', df=None):
self.df = df
self.data_dir = data_dir
self.transform = transform
self.phase = phase
if self.phase == 'test':
img_dir = 'test_images'
else:
img_dir = 'train_images'
self.img_path = glob.glob(os.path.join(self.data_dir, i... | Cassava Leaf Disease Classification |
13,048,268 | sub = pd.DataFrame.from_dict(pred_dict,orient='index')
sub.index.names = ['id']
sub.columns = ['rle_mask']
sub.to_csv('submission.csv' )<set_options> | class ImageTransform:
def __init__(self, img_size=224, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)) :
self.transform = {
'train': albu.Compose([
albu.RandomShadow(p=0.5),
albu.RandomResizedCrop(img_size, img_size, interpolation=cv2.INTER_AREA),
albu.ColorJitter(p=0.5),
albu.CLAHE(p=0.5),
albu.HorizontalFlip(p... | Cassava Leaf Disease Classification |
13,048,268 | plt.style.use('seaborn-white')
sns.set_style("white")
<normalization> | transform = ImageTransform()
dataset = CassavaDataset(data_dir, transform, phase='train', df=train)
img, label = dataset.__getitem__(0)
print(img.size() , label)
print(img.max())
print(img.min() ) | Cassava Leaf Disease Classification |
13,048,268 | 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... | dataloader = DataLoader(dataset, batch_size=8)
imgs, labels = next(iter(dataloader))
print(imgs.size() ) | Cassava Leaf Disease Classification |
13,048,268 | 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.
... | transform = ImageTransform()
dataset = CassavaDataset(data_dir, transform, phase='test', df=None)
img, label = dataset.__getitem__(0)
print(img.size() , label)
print(img.max())
print(img.min() ) | Cassava Leaf Disease Classification |
13,048,268 | 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)]<feature_enginee... | dataloader = DataLoader(dataset, batch_size=1)
imgs, labels = next(iter(dataloader))
print(imgs.size() ) | Cassava Leaf Disease Classification |
13,048,268 | 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> | class CassavaDataModule(pl.LightningDataModule):
def __init__(self, data_dir, cfg, transform, cv, fold):
super(CassavaDataModule, self ).__init__()
self.data_dir = data_dir
self.cfg = cfg
self.transform = transform
self.cv = cv
self.fold = fold
def prepare_data(self):
self.df = pd.read_csv(os.path.join(self.data_dir, '... | Cassava Leaf Disease Classification |
13,048,268 | 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> | class Timm_model(nn.Module):
def __init__(self, model_name='efficientnet_b0', pretrained=True, out_dim=5):
super(Timm_model, self ).__init__()
self.base = create_model(model_name, pretrained=pretrained)
if 'efficientnet' in model_name:
self.base.classifier = nn.Linear(in_features=self.base.classifier.in_features, out_... | Cassava Leaf Disease Classification |
13,048,268 | train_df["coverage"] = train_df.masks.map(np.sum)/ pow(img_size_ori, 2 )<categorify> | z = torch.randn(4, 3, 224, 224)
model = Timm_model(pretrained=False)
out = model(z)
print(out.size() ) | Cassava Leaf Disease Classification |
13,048,268 | 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 )<split> | class CassavaLightningSystem(pl.LightningModule):
def __init__(self, net, cfg, experiment=None):
super(CassavaLightningSystem, self ).__init__()
self.net = net
self.cfg = cfg
self.experiment = experiment
self.criterion = nn.CrossEntropyLoss()
self.best_loss = 1e+9
self.best_acc = None
self.epoch_num = 0
self.acc_fn = m... | Cassava Leaf Disease Classification |
13,048,268 | ids_train, ids_valid, x_train, x_valid, y_train, y_valid, cov_train, cov_test, depth_train, depth_test = train_test_split(
train_df.index.values,
np.array(train_df.images.map(upsample ).tolist() ).reshape(-1, img_size_target, img_size_target, 1),
np.array(train_df.masks.map(upsample ).tolist() ).reshape(-1, img_size_t... | class cfg:
exp = {
'exp_name': 'test'
}
data = {
'img_size': 256,
'n_splits': 5
}
train = {
'batch_size': 64,
'epoch': 10,
'seed': 42,
'lr': 0.005,
'model_name': 'efficientnet_b0'
} | Cassava Leaf Disease Classification |
13,048,268 | 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... | data_dir = '/kaggle/input/cassava-leaf-disease-classification'
seed_everything(cfg.train['seed'])
cv = StratifiedKFold(n_splits=cfg.data['n_splits'], shuffle=True, random_state=cfg.train['seed'])
transform = ImageTransform(img_size=cfg.data['img_size'] ) | Cassava Leaf Disease Classification |
13,048,268 | model = UNet(( img_size_target,img_size_target,1),start_ch=16,depth=5,batchnorm=True )<choose_model_class> | def main(data_dir, transform, cfg, cv, fold, TTA=5):
net = Timm_model(model_name=cfg.train['model_name'], pretrained=False)
dm = CassavaDataModule(data_dir, cfg, transform, cv, fold=fold)
model = CassavaLightningSystem(net, cfg, experiment=None)
trainer = Trainer(
logger=False,
max_epochs=cfg.train['epoch'],
gpus=1... | Cassava Leaf Disease Classification |
13,048,268 | sgd = SGD(lr=0.01, decay=1e-4, momentum=0.9, nesterov=True)
model.compile(loss=weighted_bce_dice_loss, optimizer="adam", metrics=["accuracy",iouMetric] )<define_search_model> | TTA = 3
models = []
for fold in range(cfg.data['n_splits']):
m = main(data_dir, transform, cfg, cv, fold, TTA)
models.append(m)
del m | Cassava Leaf Disease Classification |
13,048,268 | <train_model><EOS> | sub_paths = glob.glob('submission_fold*')
for i, path in enumerate(sub_paths):
tmp = pd.read_csv(path)
if i == 0:
res = tmp
else:
for j in range(5):
res[f'label_{j}'] += tmp[f'label_{j}']
label_cols = [c for c in res.columns if c != 'image_id']
res['label'] = np.argmax(res[label_cols].values, axis=1)
res = res[['ima... | Cassava Leaf Disease Classification |
13,035,386 | <SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<define_variables> | %%capture
sys.path.append('/kaggle/input/efficientnet-keras-dataset/efficientnet_kaggle')
! pip install -e /kaggle/input/efficientnet-keras-dataset/efficientnet_kaggle | Cassava Leaf Disease Classification |
13,035,386 | train_index_list=list(range(len(x_train)))
epoch_list=[]<define_variables> | print("Tensorflow version " + tf.__version__ ) | Cassava Leaf Disease Classification |
13,035,386 | for i in range(1000):
shuffle(train_index_list)
epoch_list+=train_index_list<define_variables> | DIM = 512
IMAGE_SIZE = [DIM, DIM]
EFFNET = 6
PHASE = 'inference'
PRETRAINED_WEIGHTS = 'imagenet'
GCS_PATH1 = KaggleDatasets().get_gcs_path(f'cassava-tfrecords-{DIM}x{DIM}')if PHASE=='train' else f"/kaggle/input/cassava-tfrecords-{DIM}x{DIM}"
GCS_PATH2 = KaggleDatasets().get_gcs_path('cassava-leaf-disease-classification... | Cassava Leaf Disease Classification |
13,035,386 | def gen_flow(X,y):
batch_size=32
i=0
imgs=[]
masks=[]
while True:
for j in range(32):
imgs.append(x_train[i*32+j])
masks.append(y_train[i*32+j])
yield imgs,masks
i+=1<categorify> | test_df = pd.read_csv(GCS_PATH2 + '/sample_submission.csv')
train_df = pd.read_csv(GCS_PATH2 + '/train.csv' ) | Cassava Leaf Disease Classification |
13,035,386 | def gen_flow_for_two_inputs(X, y):
genX1 = gen.flow(X,y, batch_size=batch_size)
while True:
X=genX1.next()
img_mask=np.concatenate([X[0],X[1]],axis=3)
seq_det=seq.to_deterministic()
img_mask_aug=seq_det.augment_images(img_mask)
img_mask_aug=crop_batch(img_mask_aug,0.1)
img_aug=img_mask_aug[:,:,:,0]
mask_aug=np.roun... | ROT_ = 180.0
SHR_ = 2.0
HZOOM_ = 8.0
WZOOM_ = 8.0
HSHIFT_ = 8.0
WSHIFT_ = 8.0 | Cassava Leaf Disease Classification |
13,035,386 | sgd = SGD(lr=0.01, decay=1e-4, momentum=0.9, nesterov=True)
model.compile(loss=bce_dice_loss, optimizer=sgd, metrics=["accuracy",iouMetric] )<train_model> | 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 |
13,035,386 | early_stopping = EarlyStopping(patience=20, verbose=1)
model_checkpoint = ModelCheckpoint("./keras.model", save_best_only=True, verbose=1)
reduce_lr = ReduceLROnPlateau(factor=0.1, patience=20, min_lr=0.000001, verbose=1)
epochs = 200
batch_size = 16
gen = ImageDataGenerator()
gen_flow = gen_flow_for_two_inputs(x_tr... | def to_float32(image, label):
return tf.cast(image, tf.float32), label | Cassava Leaf Disease Classification |
13,035,386 | model.load_weights("./keras.model",{"bce_dice_loss":bce_dice_loss,'iouMetric':iouMetric})
<predict_on_test> | def decode_image(image):
image = tf.image.decode_jpeg(image, channels=3)
image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
return image | Cassava Leaf Disease Classification |
13,035,386 | preds_valid = model.predict(x_valid ).reshape(-1, img_size_target, img_size_target)
preds_valid = np.array([downsample(x)for x in preds_valid])
y_valid_ori = np.array([train_df.loc[idx].masks for idx in ids_valid] )<compute_train_metric> | def read_tfrecord(example, labeled):
tfrecord_format = {
"image": tf.io.FixedLenFeature([], tf.string),
"target": tf.io.FixedLenFeature([], tf.int64)
} if labeled else {
"image": tf.io.FixedLenFeature([], tf.string),
"image_name": tf.io.FixedLenFeature([], tf.string)
}
example = tf.io.parse_single_example(example, tf... | Cassava Leaf Disease Classification |
13,035,386 | thresholds = np.linspace(0, 1, 50)
ious = np.array([iou_metric_batch(y_valid_ori, np.int32(preds_valid > threshold)) for threshold in tqdm_notebook(thresholds)] )<find_best_params> | def load_dataset(filenames, labeled=True, ordered=False):
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTOTUNE)
dataset = dataset.with_options(ignore_order)
dataset = dataset.map(partial(read_tfrecord,... | Cassava Leaf Disease Classification |
13,035,386 | threshold_best_index = np.argmax(ious[9:-10])+ 9
iou_best = ious[threshold_best_index]
threshold_best = thresholds[threshold_best_index]<categorify> | TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH1 + '/ld_train*.tfrec')
TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH2 + '/test_tfrecords/ld_test*.tfrec')
print('Train Files:',len(TRAINING_FILENAMES))
print('Test Files:',len(TEST_FILENAMES)) | Cassava Leaf Disease Classification |
13,035,386 | 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 count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n)
NUM_TRAINING_IMAGES = int(count_data_items(TRAINING_FILENAMES)*(FOLDS-1.) /FOLDS)
NUM_VALIDATION_IMAGES = int(count_data_items(TRAINING_FILENAMES)*(1./FOLDS))
NUM_TEST_IMAGES =... | Cassava Leaf Disease Classification |
13,035,386 | preds_test = model.predict(x_test )<compute_test_metric> | TRAINING_FILENAMES, VALID_FILENAMES = train_test_split(
tf.io.gfile.glob(GCS_PATH1 + '/ld_train*.tfrec'),
test_size=0.35, random_state=5
)
TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH2 + '/test_tfrecords/ld_test*.tfrec' ) | Cassava Leaf Disease Classification |
13,035,386 | pred_dict = {idx: RLenc(np.round(downsample(preds_test[i])> threshold_best)) for i, idx in enumerate(tqdm_notebook(test_df.index.values)) }<save_to_csv> | def dropout(image, DIM=DIM, PROBABILITY = 0.75, CT = 8, SZ = 0.2):
P = tf.cast(tf.random.uniform([],0,1)<PROBABILITY, tf.int32)
if(P==0)|(CT==0)|(SZ==0): return image
for k in range(CT):
x = tf.cast(tf.random.uniform([],0,DIM),tf.int32)
y = tf.cast(tf.random.uniform([],0,DIM),tf.int32)
WIDTH = tf.cast(SZ*DIM,tf.int3... | Cassava Leaf Disease Classification |
13,035,386 | sub = pd.DataFrame.from_dict(pred_dict,orient='index')
sub.index.names = ['id']
sub.columns = ['rle_mask']
sub.to_csv('submission.csv' )<set_options> | def get_training_dataset(training_fikenames=TRAINING_FILENAMES):
dataset = load_dataset(training_fikenames, labeled=True)
dataset = dataset.map(data_augment, num_parallel_calls=AUTOTUNE)
dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
dataset = dataset.batch(BATCH_SIZE)
dataset = dataset.prefetch(AUTOTUN... | Cassava Leaf Disease Classification |
13,035,386 | %matplotlib inline<categorify> | def get_validation_dataset(valid_filenames=VALID_FILENAMES, ordered=False):
dataset = load_dataset(valid_filenames, labeled=True, ordered=ordered)
dataset = dataset.batch(BATCH_SIZE)
dataset = dataset.cache()
dataset = dataset.prefetch(AUTOTUNE)
return dataset
| Cassava Leaf Disease Classification |
13,035,386 | def rle_decode(rle_mask):
s = rle_mask.split()
starts, lengths = [np.asarray(x, dtype=int)for x in(s[0:][::2], s[1:][::2])]
starts -= 1
ends = starts + lengths
img = np.zeros(101*101, dtype=np.uint8)
for lo, hi in zip(starts, ends):
img[lo:hi] = 1
return img.reshape(101,101 )<load_from_csv> | def get_test_dataset(ordered=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)
dataset = dataset.batch(BATCH_SIZE)
dataset = dataset.prefetch(AUTOTUNE)
return dataset | Cassava Leaf Disease Classification |
13,035,386 |
df = pd.read_csv('.. /input/submit-802/test_18000-null.csv')
i = 0
j = 0
plt.figure(figsize=(30,15))
plt.subplots_adjust(bottom=0.2, top=0.8, hspace=0.2)
while True:
if str(df.loc[i,'rle_mask'])!=str(np.nan):
decoded_mask = rle_decode(df.loc[i,'rle_mask'])
plt.subplot(1,6,j+1)
plt.imshow(decoded_mask)
plt.title(... | def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n ) | Cassava Leaf Disease Classification |
13,035,386 | test_path = '.. /input/tgs-salt-identification-challenge/test/images/'<categorify> | np.set_printoptions(threshold=15, linewidth=80)
label2name = {"0": "Bacterial Blight",
"1": "Brown Streak Disease",
"2": "Green Mottle",
"3": "Mosaic Disease",
"4": "Healthy"}
def batch_to_numpy_images_and_labels(data):
images, labels = data
numpy_images = images.numpy()
numpy_labels = labels.numpy()
if numpy_labels.d... | Cassava Leaf Disease Classification |
13,035,386 |
def rle_encode(im):
pixels = im.flatten()
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 )<save_to_csv> | testing_dataset = get_test_dataset()
testing_dataset = testing_dataset.unbatch().batch(20)
test_batch = iter(testing_dataset ) | Cassava Leaf Disease Classification |
13,035,386 | df.to_csv('crf_correction.csv',index=False )<import_modules> | display_batch_of_images(next(test_batch)) | Cassava Leaf Disease Classification |
13,035,386 | import pandas as pd
import numpy as np<import_modules> | def onehot(image,label):
CLASSES = 5
return image,tf.one_hot(label,CLASSES ) | Cassava Leaf Disease Classification |
13,035,386 | import pandas as pd
import numpy as np<categorify> | def cutmix(image, label, PROBABILITY = 1.0):
DIM = IMAGE_SIZE[0]
CLASSES = 5
imgs = []; labs = []
for j in range(AUG_BATCH):
P = tf.cast(tf.random.uniform([],0,1)<=PROBABILITY, tf.int32)
k = tf.cast(tf.random.uniform([],0,AUG_BATCH),tf.int32)
x = tf.cast(tf.random.uniform([],0,DIM),tf.int32)
y = tf.cast(tf.random.un... | Cassava Leaf Disease Classification |
13,035,386 | le = LabelEncoder()
def get_dictionary(s):
try:
i = eval(s)
except:
i = {}
return i
def prepare(df):
global json_cols
global train_dict
df[['release_month', 'release_day', 'release_year']] = df['release_date'].str.split('/', expand=True ).replace(np.nan, 0 ).astype(int)
df['release_year'].map(lambda x : x if x > 100 ... | def get_training_dataset(dataset=TRAINING_FILENAMES, do_aug=True):
if do_aug:
dataset = dataset.map(data_augment, num_parallel_calls=AUTOTUNE)
dataset = dataset.repeat()
dataset = dataset.batch(AUG_BATCH)
if do_aug:
dataset = dataset.map(transform, num_parallel_calls=AUTOTUNE)
dataset = dataset.unbatch()
dataset = d... | Cassava Leaf Disease Classification |
13,035,386 | from sklearn.model_selection import KFold<choose_model_class> | def get_validation_dataset(dataset, do_onehot=True):
dataset = dataset.batch(BATCH_SIZE)
if do_onehot: dataset = dataset.map(onehot, num_parallel_calls=AUTOTUNE)
dataset = dataset.cache()
dataset = dataset.prefetch(AUTOTUNE)
return dataset | Cassava Leaf Disease Classification |
13,035,386 | random_seed = 2019
k = 10
fold = list(KFold(k, shuffle=True, random_state=random_seed ).split(train))
np.random.seed(random_seed)
<define_variables> | class DataGenerator(tf.keras.utils.Sequence):
def __init__(self, path, list_IDs, labels, batch_size, img_size, img_channel):
self.path = path
self.list_IDs = list_IDs
self.labels = labels
self.batch_size = batch_size
self.img_size = img_size
self.img_channel = img_channel
self.indexes = np.arange(len(self.list_IDs))
de... | Cassava Leaf Disease Classification |
13,035,386 | result_dict = {}
val_pred = np.zeros(train.shape[0])
test_pred = np.zeros(test.shape[0])
final_err = 0
verbose = False<import_modules> | def get_lr_callback(batch_size=8, show = False):
lr_start = 0.000015000
lr_max = 0.000000250 * strategy.num_replicas_in_sync * 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 +... | Cassava Leaf Disease Classification |
13,035,386 | import xgboost as xgb<train_model> | model_dict = {0: efn.EfficientNetB0,
1: efn.EfficientNetB1,
2: efn.EfficientNetB2,
3: efn.EfficientNetB3,
4: efn.EfficientNetB4,
5: efn.EfficientNetB5,
6: efn.EfficientNetB6,
7: efn.EfficientNetB7,}
def get_model() :
with strategy.scope() :
inp = tf.keras.layers.Input(shape=(DIM,DIM,3))
base = model_dict[EFFNET](input_... | Cassava Leaf Disease Classification |
13,035,386 | def xgb_model(trn_x, trn_y, val_x, val_y, test, verbose):
params = {'objective':'reg:linear',
'eta': 0.01,
'max_depth':6,
'subsample':0.6,
'colsample_bytree':0.7,
'eval_metric':'rmse',
'seed':random_seed,
'silent':True,
}
record = dict()
model = xgb.train(params,
xgb.DMatrix(trn_x, trn_y),
100000,
[(xgb.DMatrix(trn_x, ... | TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH1 + '/ld_train*.tfrec')
kfold = KFold(FOLDS, shuffle = True, random_state = 42)
probabilities = []
for f,(trn_ind, val_ind)in enumerate(kfold.split(TRAINING_FILENAMES)) :
print() ; print('='*50)
print(f' fold: {f+1} | model: EfficientNetB{EFFNET} | image_size: {DIM}')
p... | Cassava Leaf Disease Classification |
13,035,386 | <prepare_output><EOS> | if PHASE == 'inference':
test_df['label'] = predictions
test_df = test_df[["image_id","label"]]
test_df.to_csv('submission.csv',index=False)
test_df | Cassava Leaf Disease Classification |
12,984,721 | <SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<create_dataframe> | warnings.filterwarnings('ignore')
| Cassava Leaf Disease Classification |
12,984,721 | df_sub = pd.DataFrame()
df_sub['id'] = sub['id']
df_sub['revenue'] = reve[0]<save_to_csv> | training_folder = '.. /input/cassava-leaf-disease-classification/train_images/' | Cassava Leaf Disease Classification |
12,984,721 | df_sub.to_csv('submission_1.csv', index=False )<set_options> | 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.head() | Cassava Leaf Disease Classification |
12,984,721 | %matplotlib inline
warnings.filterwarnings(action="ignore")
pd.set_option('display.max_columns', 500)
pd.set_option('display.max_rows', 500)
print(os.listdir(".. /input"))<load_from_csv> | training_percentage = 0.8
training_item_count = int(len(samples_df)*training_percentage)
validation_item_count = len(samples_df)-int(len(samples_df)*training_percentage)
training_df = samples_df[:training_item_count]
validation_df = samples_df[training_item_count:] | Cassava Leaf Disease Classification |
12,984,721 | train = pd.read_csv(".. /input/train.csv")
test = pd.read_csv(".. /input/test.csv" )<load_from_csv> | batch_size = 8
image_size = 512
input_shape =(image_size, image_size, 3)
dropout_rate = 0.4
classes_to_predict = sorted(training_df.label.unique() ) | Cassava Leaf Disease Classification |
12,984,721 | train = pd.read_csv(".. /input/train.csv")
test = pd.read_csv(".. /input/test.csv" )<prepare_x_and_y> | training_data = tf.data.Dataset.from_tensor_slices(( training_df.filepath.values, training_df.label.values))
validation_data = tf.data.Dataset.from_tensor_slices(( validation_df.filepath.values, validation_df.label.values)) | Cassava Leaf Disease Classification |
12,984,721 | X_train = train.drop(['revenue'],axis=1)
y_train = train['revenue']
print(X_train.shape, y_train.shape )<feature_engineering> | 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_d... | Cassava Leaf Disease Classification |
12,984,721 | dict_columns = ['belongs_to_collection', 'genres', 'production_companies','production_countries', 'spoken_languages', 'Keywords', 'cast', 'crew']
def text_to_dict(df):
for column in dict_columns:
df[column] = df[column].apply(lambda x: {} if pd.isna(x)else ast.literal_eval(x))
return df
train = text_to_dict(train)
tes... | 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 |
12,984,721 | X = pd.concat([X_train, test], axis=0, ignore_index=True )<feature_engineering> | adapt_data = tf.data.Dataset.from_tensor_slices(training_df.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_ca... | Cassava Leaf Disease Classification |
12,984,721 | X['has_homepage'] = X['homepage'].isnull() == False
X['is_original_english'] = X['original_language'] == 'en'
X['has_collection'] = X['belongs_to_collection'].isnull() == False
X['has_two_titles'] = X['original_title'] != X['title']
X.drop(['status','original_language','poster_path', 'homepage', 'imdb_id','belongs_to_c... | 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 |
12,984,721 | X.loc[pd.isnull(X['spoken_languages'])== True,'spoken_languages'] = 0
X['lang'] = list(map(lambda x: [i['iso_639_1'] for i in eval(x)] if x!=0 else [], X['spoken_languages'].values))
X['n_lang'] = X['lang'].apply(lambda x: len(x))
spoken_features = ['' + i for i in ['', 'la', 'it', 'cs', 'ta', 'pt', 'hu', 'zh', 'pl', '... | image = Image.open(".. /input/cassava-leaf-disease-classification/train_images/3412658650.jpg")
plt.imshow(image)
plt.show() | Cassava Leaf Disease Classification |
12,984,721 | X.loc[pd.isnull(X['genres'])== True,'genres'] = 0
genres = set(' '.join([' '.join(i)for i in list(map(lambda x: [i['name'] for i in eval(x)] if x!=0 else [], X['genres'].values)) ] ).split())
X['genres'] = list(map(lambda x: [i['name'] for i in eval(x)] if x!=0 else [], X['genres'].values))
for i in genres:
X['genre_'... | image = tf.expand_dims(np.array(image), 0 ) | Cassava Leaf Disease Classification |
12,984,721 | X['n_genres'] = X['genres'].apply(lambda x: len(x))
X['release_month'] = 0
X['release_day'] = 0
X['release_year'] = 0
X = pd.concat([X, X['release_date'].str.split('/', expand=True)], axis=1)
X.head(2 )<data_type_conversions> | plt.figure(figsize=(10, 10))
for i in range(9):
augmented_image = data_augmentation_layers(image)
ax = plt.subplot(3, 3, i + 1)
plt.imshow(augmented_image[0])
plt.axis("off" ) | Cassava Leaf Disease Classification |
12,984,721 | X.iloc[:,-1] = X.iloc[:,-1].fillna('0' ).astype(int )<feature_engineering> | efficientnet = EfficientNetB3(weights=".. /input/efficientnetb3-notop/efficientnetb3_notop.h5",
include_top=False,
input_shape=input_shape,
drop_connect_rate=dropout_rate)
inputs = Input(shape=input_shape)
augmented = data_augmentation_layers(inputs)
efficientnet = efficientnet(augmented)
pooling = layers.GlobalAve... | Cassava Leaf Disease Classification |
12,984,721 | year_mod = []
for i in X.iloc[:,-1].values:
if i in range(0, 19):
year_mod.extend([2000 + i])
else:
year_mod.extend([1900 + i])
year_mod
X['release_year'] = year_mod<categorify> | %%time
model.get_layer('efficientnetb3' ).get_layer('normalization' ).adapt(adapt_data_batches ) | Cassava Leaf Disease Classification |
12,984,721 | X = pd.concat([X, pd.get_dummies(X[0], prefix='release_month')], axis=1)
X.head(2 )<data_type_conversions> | epochs = 8
decay_steps = int(round(len(training_df)/batch_size)) *epochs
cosine_decay = CosineDecay(initial_learning_rate=1e-4, decay_steps=decay_steps, alpha=0.3)
callbacks = [ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True)]
model.compile(loss="sparse_categorical_crossentropy", opti... | Cassava Leaf Disease Classification |
12,984,721 | X['release_date'] = pd.to_datetime(X['release_date'])
X['release_weekday'] = X['release_date'].dt.weekday.fillna(8 ).astype(int )<feature_engineering> | history = model.fit(training_data_batches,
epochs = epochs,
validation_data=validation_data_batches,
callbacks=callbacks ) | Cassava Leaf Disease Classification |
12,984,721 | X.loc[:,'production_companies'] = X.loc[:,'production_companies'].fillna('[]')
companies = ','.join([','.join(i)for i in list(map(lambda x: [i['name'] for i in eval(x)], X['production_companies'].values)) ] ).split(',')
unique_companies = set(companies)
X['production_companies'] = list(map(lambda x: [i['name'] for i... | model.load_weights("best_model.h5" ) | Cassava Leaf Disease Classification |
12,984,721 | prod_count = {i: sum([1 for j in companies if i == j])for i in unique_companies}
most_famous_prod = [k for k,v in prod_count.items() if v > 100 and k]
famous_prod = [k for k,v in prod_count.items() if 30 <= v < 100 and k]
X['n_production_companies'] = X['production_companies'].apply(lambda x: len(x))
X['most_famous_pro... | test_time_augmentation_layers = tf.keras.Sequential(
[
layers.experimental.preprocessing.RandomFlip("horizontal_and_vertical"),
layers.experimental.preprocessing.RandomZoom(( -0.2, 0)) ,
layers.experimental.preprocessing.RandomContrast(( 0.2,0.2))
]
) | Cassava Leaf Disease Classification |
12,984,721 | X.loc[:,'production_countries'] = X.loc[:,'production_countries'].fillna('[]')
countries = ','.join([','.join(i)for i in list(map(lambda x: [i['iso_3166_1'] for i in eval(x)], X['production_countries'].values)) ] ).split(',')
unique_countries = set(countries)
X['production_countries'] = list(map(lambda x: [i['iso_31... | 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 |
12,984,721 | country_count = {i: sum([1 for j in countries if i == j])for i in unique_countries}
most_famous_countries= [k for k,v in country_count.items() if v > 100 and k]
famous_countries = [k for k,v in country_count.items() if 30 <= v < 100 and k]
X['n_production_countries'] = X['production_countries'].apply(lambda x: len(x))
... | validation_df["results"] = run_predictions_over_image_list(validation_df["image_id"], training_folder ) | Cassava Leaf Disease Classification |
12,984,721 | X['has_tagline'] = X['tagline'].apply(lambda x: pd.isnull(x))
X.drop(['genres', 'overview', 'production_companies', 'production_countries', 'release_date', 'tagline', 'release_month', 'release_day', 0, 2,
'title', 'Keywords', 'cast','crew'], axis=1, inplace=True)
X.head(2 )<feature_engineering> | 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(validation_df)
for idx, p... | Cassava Leaf Disease Classification |
12,984,721 | X['budget_log'] = np.log1p(X['budget'] )<data_type_conversions> | 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 |
12,984,721 | X['inflationBudget'] = X['budget'] + X['budget']*1.8/100*(2019-X['release_year'])
X['runtime'] = X['runtime'].fillna(X['runtime'].mean())
X[1] = X[1].fillna(1)
for f in X.dtypes[(X.dtypes == 'bool')|(X.dtypes == 'object')].index:
X[f] = X[f].astype(int )<drop_column> | submission_df["label"] = run_predictions_over_image_list(submission_df["image_id"], test_folder ) | Cassava Leaf Disease Classification |
12,984,721 | data_dropping_names = data.drop(['original_title','overview','tagline','title'], axis=1)
train = data_dropping_names[data_dropping_names['source'] == 'train'].copy()
test = data_dropping_names[data_dropping_names['source'] == 'test'].copy()
train_labels = train['revenue_log']
train.drop(['id', 'revenue', 'source', 're... | submission_df.to_csv("submission.csv", index=False ) | Cassava Leaf Disease Classification |
13,153,262 | num_pipeline = Pipeline([
('imputer', SimpleImputer(strategy="median")) ,
('robust_scaler', RobustScaler())
] )<train_model> | warnings.filterwarnings("ignore")
warnings.filterwarnings("ignore", category=DeprecationWarning ) | Cassava Leaf Disease Classification |
13,153,262 | n_fold = 5
folds = KFold(n_splits=n_fold, shuffle=True, random_state=42)
def train_model(X, X_test, y, params=None, folds=folds, model_type='lgb', plot_feature_importance=False, model=None):
prediction = np.zeros(X_test.shape[0])
scores = []
feature_importance = pd.DataFrame()
for fold_n,(train_index, valid_index)in ... | img_train = '.. /input/cassava-leaf-disease-classification/train_images'
img_test = '.. /input/cassava-leaf-disease-classification/test_images'
base_weight = '.. /input/cassava-baseline/'
train_df = pd.read_csv('.. /input/cassava-train-folds/train_folds.csv')
BATCH_SIZE = 64 | Cassava Leaf Disease Classification |
13,153,262 | train_dummies = pd.get_dummies(X[:X_train.shape[0]])
test_dummies = pd.get_dummies(X[X_train.shape[0]:])
train_dummies, test_dummies = train_dummies.align(test_dummies, axis=1, join='inner' )<train_model> | class TestDataset(Dataset):
def __init__(self,df,im_path,transforms=None):
self.df = df
self.im_path = im_path
self.transforms = transforms
def __getitem__(self,idx):
img_path = self.df.iloc[idx]['image_id']
img = Image.open(self.im_path+"/"+img_path)
if self.transforms:
img = self.transforms(**{"image": np.array(img)... | Cassava Leaf Disease Classification |
13,153,262 | params = {
'num_leaves': 30,
'min_data_in_leaf': 20,
'objective': 'regression',
'max_depth': 6,
'learning_rate': 0.01,
"boosting": "gbdt",
"feature_fraction": 0.9,
"bagging_freq": 1,
"bagging_fraction": 0.9,
"bagging_seed": 11,
"metric": 'rmse',
"lambda_l1": 0.2,
}
score_lgb, prediction_lgb, _ = train_model(train_dummi... | class Net(nn.Module):
def __init__(self,model_name='efficientnet-b3',pool_type=F.adaptive_avg_pool2d):
super().__init__()
self.pool_type = pool_type
self.backbone = EfficientNet.from_name(model_name)
in_features = getattr(self.backbone,'_fc' ).in_features
self.classifier = nn.Linear(in_features,5)
def forward(self,x)... | Cassava Leaf Disease Classification |
13,153,262 | sub = pd.read_csv('.. /input/sample_submission.csv')
sub['revenue'] = np.expm1(prediction_lgb)
sub.to_csv("lgb_model.csv", index=False )<sort_values> | imagenet_stats = {'mean':[0.485, 0.456, 0.406], 'std':[0.229, 0.224, 0.225]}
test_tfms = A.Compose([
A.Resize(384,384,always_apply=1,p=1),
ToTensor(normalize=imagenet_stats)
] ) | Cassava Leaf Disease Classification |
13,153,262 | score_xgb.sort(reverse=True)
dictvalues.update({'RMSE_XGB': score_xgb} )<save_to_csv> | val_preds = []
val_targets = []
for fold in range(5):
df_t = train_df[train_df.kfold==fold].reset_index(drop=True)
dataset_val = TestDataset(df_t,img_train,test_tfms)
dataloader_val = DataLoader(dataset_val, batch_size=BATCH_SIZE, num_workers=4, shuffle=False)
temp = pred(base_weight+f"fold{fold}.pth",dataloader_val... | Cassava Leaf Disease Classification |
13,153,262 | sub['revenue'] = np.expm1(prediction_xgb)
sub.to_csv("XGB_model.csv", index=False )<save_to_csv> | print(f"accuracy : {accuracy_score(val_targets,val_preds)}" ) | Cassava Leaf Disease Classification |
13,153,262 | sub['revenue'] = np.expm1(prediction_cat)
sub.to_csv("cat_model.csv", index=False )<save_to_csv> | submission_df = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv')
submission_df.iloc[:, 1] = 0
submission_df.head() | Cassava Leaf Disease Classification |
13,153,262 | sub['revenue'] = np.expm1(( prediction_lgb + prediction_xgb + prediction_cat)/ 3)
sub.to_csv("combined.csv", index=False )<import_modules> | if submission_df.shape[0] == 1:
submission_df = pd.DataFrame([{'image_id': '2216849948.jpg', 'label': 0},{'image_id': '2216849948.jpg', 'label': 0}])
submission_df.reset_index(drop=True, inplace=True)
submission_df.head() | Cassava Leaf Disease Classification |
13,153,262 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import LabelEncoder
from collections import Counter
from sklearn.model_selection import train_test_split
import lightgbm as lgb<load_from_csv> | submissions=None
for fold in range(5):
dataset_test = TestDataset(submission_df,img_test,test_tfms)
dataloader_test = DataLoader(dataset_test, batch_size=BATCH_SIZE, num_workers=4, shuffle=False)
test_preds = pred(base_weight+f"fold{fold}.pth",dataloader_test)
if submissions is None:
submissions = test_preds /5
else... | Cassava Leaf Disease Classification |
13,153,262 | train = pd.read_csv('.. /input/tmdb-box-office-prediction/train.csv')
test = pd.read_csv('.. /input/tmdb-box-office-prediction/test.csv')
sample_submission = pd.read_csv('.. /input/tmdb-box-office-prediction/sample_submission.csv' )<feature_engineering> | submission_df['label'] = torch.argmax(submissions, dim=1)
submission_df.to_csv('submission.csv', index=False)
submission_df
| Cassava Leaf Disease Classification |
13,773,813 | train['has_collection'] = train['belongs_to_collection'].apply(lambda x: 1 if str(x)!= 'nan' else 0)
train['collection_id'] = train['belongs_to_collection'].apply(lambda x: eval(x)[0]['id'] if str(x)!= 'nan' else 0)
test['has_collection'] = test['belongs_to_collection'].apply(lambda x: 1 if str(x)!= 'nan' else 0)
te... | 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 |
13,773,813 | train = train.drop(['belongs_to_collection'], axis=1)
test = test.drop(['belongs_to_collection'], axis=1 )<define_variables> | CFG = {
'img_size': 512,
'tta': 3,
'valid_bs': 16,
'device': 'cuda' if torch.cuda.is_available() else 'cpu',
'effnet_models': ['model_4.pt', 'model_5.pt', 'model_6.pt', 'model_7.pt'],
'resnet_models': ['model_6.pt', 'model_8.pt', 'model_9.pt', 'model_10.pt']
} | Cassava Leaf Disease Classification |
13,773,813 | list_of_genres = list(train['genres'].apply(lambda x: [i['name'] for i in eval(x)] if str(x)!= 'nan' else [] ).values )<feature_engineering> | class DiseaseDatasetInference(torch.utils.data.Dataset):
def __init__(self, df, transform=None, opt_label=True):
self.df = df.reset_index(drop=True ).copy()
self.transform = transform
self.opt_label = opt_label
if self.opt_label:
self.data = [(row['image_id'], row['label'])for _, row in self.df.iterrows() ]
else:
self.... | Cassava Leaf Disease Classification |
13,773,813 | top_genres = [m[0] for m in Counter([i for j in list_of_genres for i in j] ).most_common(15)]
train['all_genres'] = train['genres'].apply(lambda x: ' '.join(sorted([i['name'] for i in eval(x)])) if(isinstance(x,int)or isinstance(x,str)) == True else '')
for gen in top_genres:
train['genre_' + gen] = train['all_genres'... | df = pd.read_csv('/kaggle/input/cassava-leaf-disease-classification/sample_submission.csv')
PATH = '/kaggle/input/cassava-leaf-disease-classification/test_images/' | Cassava Leaf Disease Classification |
13,773,813 | lang_encoder = LabelEncoder()
train['all_genres'] = lang_encoder.fit_transform(train['all_genres'])
test['all_genres'] = lang_encoder.fit_transform(test['all_genres'] )<categorify> | test_csv = df.copy()
test_csv['image_id'] = PATH + test_csv['image_id']
test_ds = DiseaseDatasetInference(test_csv, transform=get_inference_transforms() , opt_label=False)
test_loader = torch.utils.data.DataLoader(test_ds, batch_size=CFG['valid_bs'], shuffle=False, pin_memory=False ) | Cassava Leaf Disease Classification |
13,773,813 | lang_encoder = LabelEncoder()
train['original_language'] = lang_encoder.fit_transform(train['original_language'])
test['original_language'] = lang_encoder.fit_transform(test['original_language'] )<define_variables> | def inference(model, data_loader, device):
preds = []
model.eval()
test_tqdm = tq.tqdm(data_loader, total=len(data_loader), desc="Testing", position=0, leave=True)
for images in test_tqdm:
images = images.to(device)
preds.extend(model(images ).detach().cpu().numpy())
return preds | Cassava Leaf Disease Classification |
13,773,813 | prod_companies = list(train['production_companies'].apply(lambda x: [i['name'] for i in eval(x)] if str(x)!= 'nan' else '' ).values )<feature_engineering> | class CassavaImageClassifier(nn.Module):
def __init__(self, efnet_arch, n_class, pretrained=False):
super().__init__()
self.efnet_model = timm.create_model(efnet_arch, pretrained=pretrained)
efnet_features = self.efnet_model.classifier.in_features
self.efnet_model.classifier = nn.Linear(efnet_features, n_class)
def f... | Cassava Leaf Disease Classification |
13,773,813 | train['prod_companies_count'] = train['production_companies'].apply(lambda x: len([i for i in eval(x)])if str(x)!= 'nan' else 0)
test['prod_companies_count'] = test['production_companies'].apply(lambda x: len([i for i in eval(x)])if str(x)!= 'nan' else 0 )<define_variables> | effnet_preds = []
for effnet_model_name in CFG['effnet_models']:
print("Model: ", effnet_model_name)
effnet_model = torch.load('/kaggle/input/effete-cassava/ensemble/'+effnet_model_name, map_location=torch.device(CFG['device']))
with torch.no_grad() :
for i in range(CFG['tta']):
effnet_preds += [inference(effnet_model... | Cassava Leaf Disease Classification |
13,773,813 | pop_production = Counter([i for j in prod_companies for i in j] )<feature_engineering> | effnet_outcomes = pd.concat([df['image_id'], pd.DataFrame(effnet_preds)], axis=1 ).sort_values(['image_id'] ) | Cassava Leaf Disease Classification |
13,773,813 | train['production_score'] = train['production_companies'].apply(lambda x: np.tanh(max([pop_production[i['name']] for i in eval(x)])) if str(x)!= 'nan' else 0)
test['production_score'] = test['production_companies'].apply(lambda x: np.tanh(max([pop_production[i['name']] for i in eval(x)])) if str(x)!= 'nan' else 0 )<dr... | class CassavaImageClassifier(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.fc.in_features
self.model.fc = nn.Linear(n_features, n_class)
def forward(self, x):
x = self.model(x)
return... | Cassava Leaf Disease Classification |
13,773,813 | train = train.drop(['production_companies'], axis=1)
test = test.drop(['production_companies'], axis=1 )<feature_engineering> | resnet_preds = []
for resnet_model_name in CFG['resnet_models']:
print("Model: ", resnet_model_name)
resnet_model = torch.load('/kaggle/input/resnet-cassava/resnet/'+resnet_model_name, map_location=torch.device(CFG['device']))
with torch.no_grad() :
for i in range(CFG['tta']):
resnet_preds += [inference(resnet_model, ... | Cassava Leaf Disease Classification |
13,773,813 | train['production_countries'] = train['production_countries'].apply(lambda x: [i['name'] for i in eval(x)][0] if str(x)!= 'nan' else '')
test['production_countries'] = test['production_countries'].apply(lambda x: [i['name'] for i in eval(x)][0] if str(x)!= 'nan' else '' )<categorify> | resnet_outcomes = pd.concat([df['image_id'], pd.DataFrame(resnet_preds)], axis=1 ).sort_values(['image_id'] ) | Cassava Leaf Disease Classification |
13,773,813 | prod_country_encoder = LabelEncoder()
train['production_countries'] = prod_country_encoder.fit_transform(train['production_countries'])
test['production_countries'] = prod_country_encoder.fit_transform(test['production_countries'] )<data_type_conversions> | final_preds =(effnet_outcomes.drop('image_id', axis=1)*0.5 + resnet_outcomes.drop('image_id', axis=1)*0.5 ).to_numpy()
final_preds = softmax(final_preds ).argmax(1 ) | Cassava Leaf Disease Classification |
13,773,813 | train['release_date'] = train['release_date'].apply(lambda x: pd.to_datetime(x))
test['release_date'] = test['release_date'].apply(lambda x: pd.to_datetime(x))<feature_engineering> | accuracy_score(final_preds, df['label'].values ) | Cassava Leaf Disease Classification |
13,773,813 | <drop_column><EOS> | submit = pd.DataFrame({'image_id': df['image_id'].values, 'label': final_preds})
submit.to_csv('submission.csv', index=False ) | Cassava Leaf Disease Classification |
13,685,132 | <SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<feature_engineering> | !pip install --quiet /kaggle/input/kerasapplications
!pip install --quiet /kaggle/input/efficientnet-git | Cassava Leaf Disease Classification |
13,685,132 | train['year'] = train['year'].apply(lambda x: x-100 if x>2020 else x)
test['year'] = test['year'].apply(lambda x: x-100 if x>2020 else x )<feature_engineering> | 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,685,132 | avg_runtime_train = train['runtime'].mean()
train['runtime'] = train['runtime'].apply(lambda x: x if str(x)!= 'nan' else avg_runtime_train)
avg_runtime_test = test['runtime'].mean()
test['runtime'] = test['runtime'].apply(lambda x: x if str(x)!= 'nan' else avg_runtime_test )<feature_engineering> | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.