kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
13,020,876
list_geres_name=['Comedy','Thriller','Action','Drama','Romance']<feature_engineering>
train = pd.read_csv('.. /input/cassava-leaf-disease-classification/train.csv') train.head()
Cassava Leaf Disease Classification
13,020,876
for i in list_geres_name: new_data['geres_name'+'_'+i]=new_data['geres_name'].apply(lambda x: 1 if i in x else 0 )<drop_column>
train.label.value_counts()
Cassava Leaf Disease Classification
13,020,876
new_data=new_data.drop('geres_name',axis=1 )<data_type_conversions>
submission = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') submission.head()
Cassava Leaf Disease Classification
13,020,876
new_data['production_countries']=new_data['production_countries'].fillna('QQ' )<feature_engineering>
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
13,020,876
new_data['production_countries'].loc[new_data['production_countries']=='Unknow']['production_countries']='QQ'<count_unique_values>
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,020,876
list_pro_coun=list(new_data['production_countries']) d = Counter([j for i in list_pro_coun for j in i] ).most_common(5) d<feature_engineering>
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
13,020,876
for i in d: new_data['production_cou_name'+'_'+i[0]]=new_data['production_countries'].apply(lambda x: 1 if i[0] in x else 0 )<feature_engineering>
if __name__ == '__main__': seed_everything(CFG['seed']) test = pd.DataFrame() test['image_id'] = list(os.listdir('.. /input/cassava-leaf-disease-classification/test_images/')) final_vals = [] final_preds = [] for cfg in CFGs: test_ds = CassavaDataset(test, '.. /input/cassava-leaf-disease-classification/test_images/', ...
Cassava Leaf Disease Classification
13,020,876
new_data['pro_country_count']=new_data['production_companies'].apply(lambda x:len(x))<groupby>
test['label'] = np.argmax(final_preds/len(CFGs), axis=1) print(test.head()) test.to_csv('submission.csv', index=False )
Cassava Leaf Disease Classification
13,080,105
pro_count_rev=new_data.loc[train.index].groupby('pro_country_count' ).revenue.median()<drop_column>
ImageFile.LOAD_TRUNCATED_IMAGES = True warnings.simplefilter('ignore') %matplotlib inline
Cassava Leaf Disease Classification
13,080,105
new_data=new_data.drop('production_countries',axis=1 )<categorify>
n_epochs = 10 n_patience = 5 n_folds = 3 train_bsize = 24 valid_bsize = 48 test_bsize = 48 seed = 42 effnet_output = {0: 1280, 1: 1280, 2: 1408, 3: 1536, 4: 1792, 5: 2048, 6: 2304, 7: 2560} IMG_SIZE = 512 EFFNET_MODEL = 4 AUGMENTATION =[albumentations.ShiftScaleRotate(shift_limit=0.2, scale_limit=0.2, rotate_limit=15, ...
Cassava Leaf Disease Classification
13,080,105
new_data['production_companies'].loc[new_data['production_companies']=='unknow']='u'<drop_column>
path = '.. /input/cassava-leaf-disease-classification/' trained_path = '.. /input/cassava-b4-512-final/'
Cassava Leaf Disease Classification
13,080,105
d.remove(( 'u',414)) <concatenate>
df = pd.read_csv(path + 'train.csv') N_CLASSES = df.label.nunique()
Cassava Leaf Disease Classification
13,080,105
dd=[] for i in d: dd.append(i[0] )<concatenate>
class ClassificationDataset: def __init__(self, image_paths, targets, resize, augmentations=None): self.image_paths = image_paths self.targets = targets self.resize = resize self.augmentations = augmentations def __len__(self): return len(self.image_paths) def __getitem__(self, item): image = Image.open(self.image_pat...
Cassava Leaf Disease Classification
13,080,105
dd=[] for i in d: dd.append(i[0] )<drop_column>
class Engine: @staticmethod def train( data_loader, model, optimizer, device, scheduler=None, accumulation_steps=1, fp16=True, ): losses = AverageMeter() accuracies = AverageMeter() final_predictions = [] model.train() if accumulation_steps > 1: optimizer.zero_grad() if fp16: scaler = torch.cuda.amp.GradScaler() for ...
Cassava Leaf Disease Classification
13,080,105
new_data=new_data.drop('spoken_languages',axis=1 )<feature_engineering>
class EfficientNet(nn.Module): def __init__(self, num_classes): super(EfficientNet, self ).__init__() self.base_model = timm.create_model(f"tf_efficientnet_b{str(EFFNET_MODEL)}_ns", pretrained=False) self.dropout = nn.Dropout(0.2) self.out = nn.Linear( in_features=effnet_output[EFFNET_MODEL], out_features=num_classe...
Cassava Leaf Disease Classification
13,080,105
new_data['runtime'].loc[new_data['runtime']==0]=1 new_data['time_budget']=new_data['budget'].fillna(0)/new_data['runtime'].fillna(1 )<drop_column>
test = pd.read_csv(path + "sample_submission.csv" )
Cassava Leaf Disease Classification
13,080,105
<drop_column><EOS>
final_preds = None for i in range(n_folds): preds = predict(fold = i, apply_tta=IS_TTA) 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 final_preds /= n_folds final_pr...
Cassava Leaf Disease Classification
13,081,575
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<feature_engineering>
print("Tensorflow version " + tf.__version__ )
Cassava Leaf Disease Classification
13,081,575
for i in list1: new_data['title_is'+i]=new_data['title'].fillna('' ).apply(lambda x: 1 if i in x else 0 )<feature_engineering>
AUTOTUNE = tf.data.experimental.AUTOTUNE GCS_PATH = ".. /input/cassava-leaf-disease-classification" GCS_PATH_STRATIFICATED =".. /input/cassava-recreate-stratificated-tfrecords" REPLICAS = strategy.num_replicas_in_sync BATCH_SIZE = 128 AUG_BATCH = BATCH_SIZE IMAGE_SIZE = [512, 512] DIM = IMAGE_SIZE[0] CLASSES = ['0', '1...
Cassava Leaf Disease Classification
13,081,575
for col in ['tagline', 'overview','title']: new_data['len_' + col] =new_data[col].fillna('' ).apply(lambda x: len(x)) new_data['words_' + col] = new_data[col].fillna('' ).apply(lambda x: len(x.split(' '))) new_data=new_data.drop(col,axis=1 )<feature_engineering>
test_df = pd.read_csv(GCS_PATH + '/sample_submission.csv') train_df = pd.read_csv(GCS_PATH + '/train.csv' )
Cassava Leaf Disease Classification
13,081,575
new_data['budget_popularity']=new_data['budget']*1.0/new_data['popularity']<count_values>
files_test = np.sort(np.array(tf.io.gfile.glob(GCS_PATH + '/test_tfrecords/*.tfrec')) )
Cassava Leaf Disease Classification
13,081,575
a=new_data.groupby(['release_year'] ).release_month.value_counts() b=new_data.groupby(['release_year','release_month'] ).release_day.value_counts() new_data[(new_data['release_year']==2017)&(new_data['release_day']==30)] <categorify>
ROT_ = 180.0 SHR_ = 2.0 HZOOM_ = 8.0 WZOOM_ = 8.0 HSHIFT_ = 8.0 WSHIFT_ = 8.0
Cassava Leaf Disease Classification
13,081,575
new_data['_releaseYear_popularity_ratio'] = new_data['release_year'] / new_data['popularity'] new_data['_releaseYear_popularity_ratio2'] = new_data['popularity'] / new_data['release_year'] new_data['runtime_to_mean_year'] = new_data['runtime'] / new_data.groupby("release_year")["runtime"].transform('mean') new_data['p...
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,081,575
<feature_engineering>
def to_float32(image, label): return tf.cast(image, tf.float32), label
Cassava Leaf Disease Classification
13,081,575
<split>
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,081,575
new_train=new_data.loc[train.index] new_test=new_data.loc[test.index]<train_model>
def read_labeled_tfrecord(example): tfrec_format = { 'image' : tf.io.FixedLenFeature([], tf.string), 'target' : tf.io.FixedLenFeature([], tf.int64) } example = tf.io.parse_single_example(example, tfrec_format) return example['image'], example['target']
Cassava Leaf Disease Classification
13,081,575
x=new_train.drop('revenue',axis=1) y=new_train['revenue'] x=x.fillna(0) decision_tree = DecisionTreeRegressor(max_depth = 6) decision_tree.fit(x, y) <train_model>
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,081,575
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42) model_XG = xgboost.XGBRegressor() model_XG.fit(x_train,y_train) y_predict_rf = model_XG.predict(x_test) print(mean_squared_error(y_test, y_predict_rf)) <drop_column>
def read_unlabeled_tfrecord(example, return_image_name): 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'] if return_image_name else '0'
Cassava Leaf Disease Classification
13,081,575
X_test=new_test.drop('revenue',axis=1) X_test=X_test.fillna(0 )<predict_on_test>
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,081,575
ypred=model_XG.predict(X_test )<prepare_x_and_y>
TRAINING_FILENAMES = tf.io.gfile.glob('.. /input/cassava-leaf-disease-classification/train_tfrecords/' + '*train*.tfrec') TEST_FILENAMES = tf.io.gfile.glob('.. /input/cassava-leaf-disease-classification/test_tfrecords/' + 'ld_test*.tfrec' )
Cassava Leaf Disease Classification
13,081,575
dtrain = xgb.DMatrix(x, y) dtest = xgb.DMatrix(X_test )<train_on_grid>
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,081,575
xgb_params = { 'eta': 0.08, 'max_depth': 15, 'subsample': 0.7, 'colsample_bytree': 0.7, 'objective': 'reg:linear', 'eval_metric': 'rmse', 'silent': 1 } cv_output = xgb.cv(xgb_params, dtrain, num_boost_round=1000, early_stopping_rounds=400, verbose_eval=50, show_stdv=False) cv_output[['train-rmse-mean', 'test-rmse-mean...
def data_augment(image, label): image = tf.image.random_flip_left_right(image) return image, label
Cassava Leaf Disease Classification
13,081,575
y_predict1 = abs(model.predict(dtest))<prepare_x_and_y>
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,081,575
train=x y_train=np.log1p(y) test=X_test y=y_train<compute_train_metric>
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,081,575
n_folds = 5 def rmsle_cv(model): kf = KFold(n_folds, shuffle=True, random_state=42 ).get_n_splits(train.values) rmse = np.sqrt(-cross_val_score(model, train.values,y_train.values, scoring="neg_mean_squared_error", cv=kf)) return(rmse) def eval_model(model, name): start_time = time.time() score = rmsle_cv(model) prin...
def onehot(image,label): CLASSES = 5 return image,tf.one_hot(label,CLASSES )
Cassava Leaf Disease Classification
13,081,575
mod_lasso = make_pipeline(RobustScaler() , Lasso(alpha=0.005, random_state=1)) eval_model(mod_lasso, "lasso") mod_enet = make_pipeline(RobustScaler() , ElasticNet(alpha=0.0005, l1_ratio=.9, random_state=3)) eval_model(mod_enet, "enet") mod_cat = CatBoostRegressor(iterations=10000, learning_rate=0.01, depth=5, eval_me...
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,081,575
class StackingAveragedModels(BaseEstimator, RegressorMixin, TransformerMixin): def __init__(self, base_models, meta_model, n_folds=5): self.base_models = base_models self.meta_model = meta_model self.n_folds = n_folds def fit(self, X, y): self.base_models_ = [list() for x in self.base_models] self.meta_model_ = clone(s...
def get_dataset(files, augment = False, shuffle = False, repeat = False, labeled=True, return_image_names=False, batch_size=16, dim=512): ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTOTUNE) ds = ds.cache() if repeat: ds = ds.repeat() if shuffle: ds = ds.shuffle(1024*8) opt = tf.data.Options() opt.experim...
Cassava Leaf Disease Classification
13,081,575
def rmsle(y, y_pred): return np.sqrt(mean_squared_error(y, y_pred)) def predict(model): model.fit(train.values,y_train.values) train_pred = model.predict(train.values) pred = np.expm1(model.predict(test.values)) print(rmsle(y_train, train_pred)) return(pred )<predict_on_test>
class DataGenerator(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)) def __len__(self)...
Cassava Leaf Disease Classification
13,081,575
prediction1=0 prediction = predict(mod_lasso) prediction = predict(mod_enet) prediction = predict(mod_xgb) prediction1+=prediction prediction = predict(mod_gboost) prediction1+=prediction prediction = predict(mod_lgb) prediction1+=prediction prediction = predict(mod_stacked) prediction1+=prediction prediction<sav...
Cassava Leaf Disease Classification
13,081,575
new_test['id']=new_test.index new_test['revenue']=prediction new_test[['id','revenue']].to_csv('submission_Dragon2.csv', index=False) new_test[['id','revenue']].head()<save_to_csv>
test_generator = DataGenerator('.. /input/cassava-leaf-disease-classification/'+'test_images/', test_df['image_id'], test_df['label'], 1, DIM, 3 )
Cassava Leaf Disease Classification
13,081,575
new_test['revenue']=prediction1/4 new_test[['id','revenue']].to_csv('submission_Dragon3.csv', index=False) new_test[['id','revenue']].head()<define_variables>
BASE_WEIGHTS_PATH = 'https://storage.googleapis.com/keras-applications/' WEIGHTS_HASHES = { 'b0':('902e53a9f72be733fc0bcb005b3ebbac', '50bc09e76180e00e4465e1a485ddc09d'), 'b1':('1d254153d4ab51201f1646940f018540', '74c4e6b3e1f6a1eea24c589628592432'), 'b2':('b15cce36ff4dcbd00b6dd88e7857a6ad', '111f8e2ac8aa800a7a99e3239...
Cassava Leaf Disease Classification
13,081,575
package_path = '.. /input/vision-transformer-pytorch/VisionTransformer-Pytorch' sys.path.append(package_path) <define_variables>
def get_model(weights='imagenet'): inp = tf.keras.layers.Input(shape=(DIM,DIM,3)) base = EfficientNetB0(input_shape=(DIM,DIM,3),weights=None,include_top=False) x = base(inp) x = tf.keras.layers.GlobalAveragePooling2D()(x) x = tf.keras.layers.Flatten()(x) x = tf.keras.layers.Dense(5,activation='softmax' )(x) model ...
Cassava Leaf Disease Classification
13,081,575
package_path = '.. /input/pytorch-image-models/pytorch-image-models-master' sys.path.append(package_path )<import_modules>
skf = KFold(n_splits=FOLDS,shuffle=True,random_state=12) for fold,(idxT,idxV)in enumerate(skf.split(np.arange(5))): if fold==(FOLDS-1): idxTT = idxT; idxVV = idxV print(' print('Fold',fold,'has TRAIN:',idxT,'VALID:',idxV )
Cassava Leaf Disease Classification
13,081,575
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...
pred = np.zeros(( test_df.shape[0],5)) for fold,(idxT,idxV)in enumerate(skf.split(np.arange(5))): print() ; print(' print(' print(' files_train = tf.io.gfile.glob([GCS_PATH_STRATIFICATED + '/train%.2i*.tfrec'%x for x in idxT]) files_valid = tf.io.gfile.glob([GCS_PATH_STRATIFICATED + '/train%.2i*.tfrec'%x for x in idxV...
Cassava Leaf Disease Classification
13,081,575
CFG = { 'fold_num': 10, 'seed': 719, 'model_arch': 'tf_efficientnet_b3_ns', 'img_size': 384, 'epochs': 60, 'train_bs': 28, 'valid_bs': 32, 'lr': 1e-2, 'num_workers': 5, 'accum_iter': 1, 'verbose_step': 2, 'device': 'cuda:0', 'tta': 6, 'used_epochs': [6,7,8,9], 'weights': [1,1,1,1] }<load_from_csv>
ds = get_dataset(files_test, augment=False, repeat=False, dim=IMAGE_SIZE[0], labeled=False, return_image_names=True) image_names = np.array([img_name.numpy().decode("utf-8") for img, img_name in iter(ds.unbatch())] )
Cassava Leaf Disease Classification
13,081,575
<count_values><EOS>
prediction = np.argmax(pred, axis=1) test_df['label'] = prediction test_df = test_df[["image_id","label"]] test_df.to_csv('submission.csv',index=False) test_df
Cassava Leaf Disease Classification
13,857,194
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<load_from_csv>
!pip install --quiet /kaggle/input/kerasapplications !pip install --quiet /kaggle/input/efficientnet-git
Cassava Leaf Disease Classification
13,857,194
submission = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') submission.head()<categorify>
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,857,194
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...
try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() print(f'Running on TPU {tpu.master() }') except ValueError: tpu = None if tpu: tf.config.experimental_connect_to_cluster(tpu) tf.tpu.experimental.initialize_tpu_system(tpu) strategy = tf.distribute.experimental.TPUStrategy(tpu) else: strategy = tf.distr...
Cassava Leaf Disease Classification
13,857,194
HorizontalFlip, VerticalFlip, IAAPerspective, ShiftScaleRotate, CLAHE, RandomRotate90, Transpose, ShiftScaleRotate, Blur, OpticalDistortion, GridDistortion, HueSaturationValue, IAAAdditiveGaussianNoise, GaussNoise, MotionBlur, MedianBlur, IAAPiecewiseAffine, RandomResizedCrop, IAASharpen, IAAEmboss, RandomBrightnessCon...
BATCH_SIZE = 16 * REPLICAS HEIGHT = 512 WIDTH = 512 CHANNELS = 3 N_CLASSES = 5 TTA_STEPS = 3
Cassava Leaf Disease Classification
13,857,194
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...
database_base_path = '/kaggle/input/cassava-leaf-disease-classification/' submission = pd.read_csv(f'{database_base_path}sample_submission.csv') display(submission.head()) TEST_FILENAMES = tf.io.gfile.glob(f'{database_base_path}test_tfrecords/ld_test*.tfrec') NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES) print...
Cassava Leaf Disease Classification
13,857,194
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...
model_path_list = glob.glob('/kaggle/input/cassava-leaf-disease-tpu-tensorflow-training/*.h5') model_path_list.sort() print('Models to predict:') print(*model_path_list, sep=' ' )
Cassava Leaf Disease Classification
13,857,194
test['label'] = np.argmax(tst_preds, axis=1) test.head()<save_to_csv>
model_path_list_2 = glob.glob('/kaggle/input/cassava-leaf-disease-training-with-tpu-v2-pods/*.h5') model_path_list_2.sort() print('Models to predict:') print(*model_path_list_2, sep=' ' )
Cassava Leaf Disease Classification
13,857,194
test.to_csv('submission.csv', index=False )<install_modules>
def model_fn(input_shape, N_CLASSES): inputs = L.Input(shape=input_shape, name='inputs') base_model = efn.EfficientNetB3(input_tensor=inputs, include_top=False, weights=None, pooling='avg') model = tf.keras.Sequential([ base_model, L.Dropout (.25), L.Dense(N_CLASSES, activation='softmax', name='output') ]) return m...
Cassava Leaf Disease Classification
13,857,194
!pip install.. /input/timm034/timm-0.3.4-py3-none-any.whl<import_modules>
files_path = f'{database_base_path}test_images/' test_preds = np.zeros(( len(os.listdir(files_path)) , N_CLASSES)) print('First model') for model_path in model_path_list: print(model_path) K.clear_session() model.load_weights(model_path) if TTA_STEPS > 0: test_ds = get_dataset(files_path, tta=True) for step in rang...
Cassava Leaf Disease Classification
13,857,194
<define_variables><EOS>
submission = pd.DataFrame({'image_id': image_names, 'label': test_preds}) submission.to_csv('submission.csv', index=False) display(submission.head() )
Cassava Leaf Disease Classification
14,111,611
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<define_variables>
!pip install --quiet.. /input/kerasapplications/keras-team-keras-applications-3b180cb !pip install --quiet /kaggle/input/efficientnet-git
Cassava Leaf Disease Classification
14,111,611
ls.. /input/cdl-cspresnext50-512/<define_variables>
Flatten,GlobalAveragePooling2D,BatchNormalization, Activation print(tf.__version__ )
Cassava Leaf Disease Classification
14,111,611
model_pths = [ '.. /input/cdl-cspresnext50-512/light_best_model_fold0.pth', '.. /input/cdl-cspresnext50-512/light_best_model_fold1.pth', '.. /input/cdl-cspresnext50-512/light_best_model_fold2.pth', '.. /input/cdl-cspresnext50-512/light_best_model_fold3.pth', '.. /input/cdl-cspresnext50-512/light_best_model_fold4.pth', ...
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
14,111,611
class net(nn.Module): def __init__(self, model_name=enet_type, pretrained=False): super().__init__() self.model = timm.create_model(model_name, pretrained=pretrained) n_features = self.model.head.fc.in_features self.model.head.fc = nn.Linear(n_features, 5) def forward(self, x): output = self.model(x) return output<c...
SEED = 100 DEBUG = False WANDB = False VALIDATION_SIZE = 0.2 BATCH_SIZE = 32 *REPLICAS LEARNING_RATE = 3e-5 * REPLICAS EPOCHS=40 MODEL_NAME = "EfficentNetB4" N_FOLDS = 5 TTA = True N_TTA = 7 T_1 = 0.2 T_2 = 1.2 SMOOTH_FRACTION = 0.01 N_ITER = 5 HEIGHT = 512 WIDTH = 512 HEIGHT_RS = 512 WIDTH_RS = 512 CHANNELS = 3 N_CLAS...
Cassava Leaf Disease Classification
14,111,611
class LEAFDataset(Dataset): def __init__(self, folder, transforms=None): self.file_names = os.listdir(folder) self.transforms = transforms def __len__(self): return len(self.file_names) def __getitem__(self, index): image_id = self.file_names[index] image_file = os.path.join(image_folder, image_id) image = cv2.imrea...
def transform_rotation(image, height, rotation): DIM = height XDIM = DIM%2 rotation = rotation * tf.random.uniform([1],dtype='float32') rotation = math.pi * rotation / 180. c1 = tf.math.cos(rotation) s1 = tf.math.sin(rotation) one = tf.constant([1],dtype='float32') zero = tf.constant([0],dtype='float32') rotation...
Cassava Leaf Disease Classification
14,111,611
transform = albumentations.Compose([ albumentations.Resize(image_size, image_size), albumentations.Normalize() , ToTensorV2() ] )<load_pretrained>
def data_augment(image, label): p_rotation = tf.random.uniform([], 0, 1.0, dtype=tf.float32) 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, dt...
Cassava Leaf Disease Classification
14,111,611
res = [] for model_pth in model_pths: model = net(enet_type) model.load_state_dict(torch.load(model_pth)) model.eval() model.to(device) test_dataset = LEAFDataset(image_folder, transforms=transform) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, num_workers=num_workers) single_model_...
copyfile(src = ".. /input/bitempered-logistic-loss-tensorflow-v2/bi_tempered_loss.py", dst = ".. /working/loss.py")
Cassava Leaf Disease Classification
14,111,611
sub = pd.DataFrame({'image_id': image_ids_list, 'label': probs});sub.head()<save_to_csv>
with strategy.scope() : class BiTemperedLogisticLoss(tf.keras.losses.Loss): def __init__(self, t1, t2, lbl_smth, n_iter): super(BiTemperedLogisticLoss, self ).__init__() self.t1 = t1 self.t2 = t2 self.lbl_smth = lbl_smth self.n_iter = n_iter def call(self, y_true, y_pred): return bi_tempered_logistic_loss(y_pred, y_tru...
Cassava Leaf Disease Classification
14,111,611
sub.to_csv('submission.csv', index=False )<save_to_csv>
files_path = '.. /input/cassava-leaf-disease-classification/test_images' TEST_FILENAMES = tf.io.gfile.glob('.. /input/cassava-leaf-disease-classification/test_tfrecords/*') model_base_path = '.. /input/cassava-efficientnetb4' model_path_list = os.listdir(model_base_path) model_path_list = ['EfficentNet4_best_btl_fold...
Cassava Leaf Disease Classification
14,111,611
<define_variables><EOS>
test_preds = np.argmax(test_preds, axis=-1) image_names = [img_name.numpy().decode('utf-8')for img, img_name in iter(test_ds.unbatch())] 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,057,068
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<define_variables>
sys.path = [ '.. /input/efficientnet-pytorch/EfficientNet-PyTorch/EfficientNet-PyTorch-master', ] + sys.path sys.path = [ '.. /input/ttach-kaggle/ttach/', ] + sys.path
Cassava Leaf Disease Classification
13,057,068
package_path = '.. /input/pytorch-image-models/pytorch-image-models-master' sys.path.append(package_path )<import_modules>
warnings.filterwarnings('ignore' )
Cassava Leaf Disease Classification
13,057,068
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...
DIR_INPUT = '/kaggle/input/cassava-leaf-disease-classification' DIR_WEIGHTS = '/kaggle/input/cassava-pytorch-starter-train' SEED = 42 N_FOLDS = 1 BATCH_SIZE = 16 SIZE = 512 CROP = 512 init_lr = 5e-5 n_epochs = 5
Cassava Leaf Disease Classification
13,057,068
CFG = { 'fold_num': 10, 'seed': 719, 'model_arch': 'tf_efficientnet_b3_ns', 'img_size': 384, 'epochs': 100, 'train_bs': 28, 'valid_bs': 32, 'lr': 1e-2, 'num_workers': 10, 'accum_iter': 1, 'verbose_step': 2, 'device': 'cuda:0', 'tta': 10, 'used_epochs': [6,7,8,9], 'weights': [1,1,1,1] }<load_from_csv>
modelname="efficientnet-b0" modelname2="efficientnet-b2" class enetv2(nn.Module): def __init__(self, out_dim=1, ModelName="efficientnet-b0"): super(enetv2, self ).__init__() self.basemodel = EfficientNet.from_name(ModelName) self.myfc = nn.Linear(self.basemodel._fc.in_features, out_dim) self.basemodel._fc = nn.Identi...
Cassava Leaf Disease Classification
13,057,068
train = pd.read_csv('.. /input/cassava-leaf-disease-classification/train.csv') train.head()<count_values>
transforms_test = A.Compose([ A.Resize(height=SIZE, width=SIZE, p=1.0), ] )
Cassava Leaf Disease Classification
13,057,068
train.label.value_counts()<load_from_csv>
submission_df = pd.read_csv(DIR_INPUT + '/sample_submission.csv') submission_df.iloc[:, 1] = 0 submission_df.head()
Cassava Leaf Disease Classification
13,057,068
submission = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') submission.head()<categorify>
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) commit = True else: commit = False submission_df.head()
Cassava Leaf Disease Classification
13,057,068
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...
dataset_test = CassavaDataset(df=submission_df, dataset='test', transforms=transforms_test) dataloader_test = DataLoader(dataset_test, batch_size=BATCH_SIZE, num_workers=4, shuffle=False )
Cassava Leaf Disease Classification
13,057,068
HorizontalFlip, VerticalFlip, IAAPerspective, ShiftScaleRotate, CLAHE, RandomRotate90, Transpose, ShiftScaleRotate, Blur, OpticalDistortion, GridDistortion, HueSaturationValue, IAAAdditiveGaussianNoise, GaussNoise, MotionBlur, MedianBlur, IAAPiecewiseAffine, RandomResizedCrop, IAASharpen, IAAEmboss, RandomBrightnessCon...
submissions = None device = torch.device("cuda:0")if torch.cuda.is_available() else torch.device('cpu') for i_fold in range(N_FOLDS): model = enetv2(5, modelname2 ).to(device) model.to(device) checkpoint2 = torch.load(f".. /input/cassavadata/efficientnet-b2_512_final_epoch10_fold0.pth", map_location=device) model.l...
Cassava Leaf Disease Classification
13,057,068
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...
pl_df = pd.read_csv(DIR_INPUT + '/sample_submission.csv') if pl_df.shape[0] == 1: pl_df = pd.DataFrame([{'image_id': '2216849948.jpg', 'label': 0},{'image_id': '2216849948.jpg', 'label': 0}]) pl_df.reset_index(drop=True, inplace=True) pl_df['label'] = torch.argmax(submissions, dim=1) pl_df["pl"] = np.ones_like(torc...
Cassava Leaf Disease Classification
13,057,068
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...
df_train = pd.read_csv(os.path.join(DIR_INPUT,"train.csv")) df_train["pl"] = np.zeros_like(df_train["image_id"]) df_train = pd.concat([df_train, pl_df] ).reset_index()
Cassava Leaf Disease Classification
13,057,068
test['label'] = np.argmax(tst_preds, axis=1) test.head()<save_to_csv>
class CassavaDataset2(Dataset): def __init__(self, df, dataset='train', transforms=None): self.df = df self.transforms=transforms self.dataset=dataset def __len__(self): return self.df.shape[0] def __getitem__(self, idx): imageid = self.df.loc[idx, "image_id"] label = self.df.loc[idx, "label"] dir = self.df.loc[idx, "p...
Cassava Leaf Disease Classification
13,057,068
test.to_csv('submission.csv', index=False )<define_variables>
scaler = torch.cuda.amp.GradScaler(enabled=False) def train_epoch(loader, optimizer): model.train() train_loss = [] bar = tqdm(loader) i = 0 for(data, target)in bar: data, target = data.to(device), target.to(device ).long() loss_func = criterion optimizer.zero_grad() with torch.cuda.amp.autocast(enabled=False): logit...
Cassava Leaf Disease Classification
13,057,068
tez_path = '.. /input/tez-lib/' effnet_path = '.. /input/efficientnet-pytorch/' timm_path = '.. /input/timm-pytorch-image-models/pytorch-image-models-master' sys.path.append(tez_path) sys.path.append(effnet_path) sys.path.append(timm_path )<import_modules>
for epoch in range(1, n_epochs+1): torch.cuda.empty_cache() scheduler.step(epoch-1) train_loss = train_epoch(dataloader_train , optimizer )
Cassava Leaf Disease Classification
13,057,068
import os import albumentations import pandas as pd import numpy as np import timm import tez from tez.datasets import ImageDataset import torch import torch.nn as nn from torch.nn import functional as F from tqdm import tqdm from efficientnet_pytorch import EfficientNet<feature_engineering>
submissions = None device = torch.device("cuda:0")if torch.cuda.is_available() else torch.device('cpu') for i_fold in range(N_FOLDS): model.eval() transforms = tta.Compose( [ tta.HorizontalFlip() , ] ) tta_models = [] for model in [model]: tta_models.append(tta.ClassificationTTAWrapper(model, transforms)) for net i...
Cassava Leaf Disease Classification
13,057,068
<choose_model_class><EOS>
submission_df['label'] = torch.argmax(submissions, dim=1) submission_df.to_csv('submission.csv', index=False) submission_df
Cassava Leaf Disease Classification
14,109,551
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<set_options>
!pip install.. /input/vision-transformer/vision_transformer_pytorch-1.0.2-py2.py3-none-any.whl
Cassava Leaf Disease Classification
14,109,551
img_size = 512 test_aug = albumentations.Compose([ albumentations.RandomResizedCrop(img_size, img_size), 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 ),...
model = VisionTransformer.from_name('ViT-B_16', num_classes=5) model.load_state_dict(torch.load('.. /input/vitb16trained/ViT-B_16_trained.pt',map_location=torch.device('cpu')) )
Cassava Leaf Disease Classification
14,109,551
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_...
test_df = pd.read_csv(".. /input/cassava-leaf-disease-classification/sample_submission.csv") image_path = ".. /input/cassava-leaf-disease-classification/test_images/" test_targets = test_df.label.values test_aug = albu.Compose([ albu.CenterCrop(512, 512, p=1.) , albu.Resize(384, 384), albu.Normalize( mean=[0.485, 0.4...
Cassava Leaf Disease Classification
14,109,551
train_dfx = pd.read_csv(".. /input/cassava-leaf-disease-classification/train.csv") model_path = ".. /input/cassava-model-3" model0 = EfficientnetModel(num_classes=train_dfx.label.nunique()) model0.load(f"{model_path}/efficentnet_model_fold0.bin", device='cuda') model1 = EfficientnetModel(num_classes=train_dfx.label....
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") predictions=[] for imgs in test_loader: imgs = imgs.to(device) with torch.no_grad() : model=model.to(device) outputs = model(imgs) _, predicted = torch.max(outputs, dim=1) predicted=predicted.to('cpu') predictions.append(predicted )
Cassava Leaf Disease Classification
14,109,551
<feature_engineering><EOS>
test_df['label'] = np.concatenate(predictions) test_df.to_csv('submission.csv', index=False )
Cassava Leaf Disease Classification
13,418,167
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<define_variables>
package_path = '.. /input/pytorch-image-models/pytorch-image-models-master'
Cassava Leaf Disease Classification
13,418,167
def most_common(lst): data = Counter(lst) return max(lst, key=data.get) final_preds = list() for index, row in new_df.iterrows() : out_list = [row['model0'], row['model1'], row['model2'], row['model3'], row['model4'],row['model5'], row['model6'], row['model7'], row['model8'], row['model9'] ] final_preds.append(most_c...
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
13,418,167
<predict_on_test>
CFG = { 'fold_num': 10, 'seed': 719, 'model_arch': 'tf_efficientnet_b3_ns', 'img_size': 512, 'epochs': 32, 'train_bs': 28, 'valid_bs': 32, 'lr': 1e-4, 'num_workers': 4, 'accum_iter': 1, 'verbose_step': 1, 'device': 'cuda:0', 'tta': 1, 'used_epochs': [6,7,8,9], 'weights': [1,1,1,1] }
Cassava Leaf Disease Classification
13,418,167
<save_to_csv>
train = pd.read_csv('.. /input/cassava-leaf-disease-classification/train.csv') train.head()
Cassava Leaf Disease Classification
13,418,167
dfx.label = final_preds dfx.to_csv("submission.csv", index=False )<define_variables>
train.label.value_counts()
Cassava Leaf Disease Classification
13,418,167
BATCH_SIZE = 1 image_size = 512 enet_type = ['tf_efficientnet_b4_ns'] * 5 model_path = ['.. /input/cassava-models-eff/baseline_cld_fold0_epoch8_tf_efficientnet_b4_ns_512.pth', '.. /input/cassava-models-eff/baseline_cld_fold1_epoch9_tf_efficientnet_b4_ns_512.pth', '.. /input/cassava-models-eff/baseline_cld_fold2_epoch9_...
submission = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') submission.head()
Cassava Leaf Disease Classification
13,418,167
transforms_valid = albumentations.Compose([ albumentations.CenterCrop(image_size, image_size, p=1), albumentations.Resize(image_size, image_size), albumentations.Normalize() ] )<define_variables>
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
13,418,167
OUTPUT_DIR = './' MODEL_DIR = '.. /input/cassava-models-res/' 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'<define_search_space>
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,418,167
class CFG: debug=False num_workers=8 model_name='resnext50_32x4d' size=512 batch_size=32 seed=2020 target_size=5 target_col='label' n_fold=5 trn_fold=[0, 1, 2, 3, 4] inference=True<load_from_csv>
class CassvaImgClassifier(nn.Module): def __init__(self, model_arch, n_class, pretrained=False): super().__init__() self.model = timm.create_model(model_arch, pretrained=pretrained) n_features = self.model.classifier.in_features self.model.classifier = nn.Linear(n_features, n_class) def forward(self, x): x = self.mod...
Cassava Leaf Disease Classification
13,418,167
test = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') test['filepath'] = test.image_id.apply(lambda x: os.path.join('.. /input/cassava-leaf-disease-classification/test_images', f'{x}')) <create_dataframe>
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
13,418,167
test_dataset_efficient = CLDDataset(test, 'test', transform=transforms_valid) test_loader_efficient = torch.utils.data.DataLoader(test_dataset_efficient, batch_size=BATCH_SIZE, shuffle=False, num_workers=4 )<categorify>
test['label'] = np.argmax(tst_preds, axis=1) test.head()
Cassava Leaf Disease Classification
13,418,167
<choose_model_class><EOS>
test.to_csv('submission.csv', index=False )
Cassava Leaf Disease Classification
14,240,018
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<define_search_model>
package_path = '.. /input/pytorch-image-models/pytorch-image-models-master'
Cassava Leaf Disease Classification