kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
13,685,132
train['spoken_languages_count'] = train['spoken_languages'].apply(lambda x: len(eval(x)) if str(x)!= 'nan' else 0) test['spoken_languages_count'] = test['spoken_languages'].apply(lambda x: len(eval(x)) if str(x)!= 'nan' else 0 )<drop_column>
BATCH_SIZE = 16 * REPLICAS HEIGHT = 512 WIDTH = 512 CHANNELS = 3 N_CLASSES = 5 TTA_STEPS = 0 USE_REGULAR = False USE_SCL = True
Cassava Leaf Disease Classification
13,685,132
train = train.drop(['spoken_languages'], axis=1) test = test.drop(['spoken_languages'], axis=1 )<define_variables>
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,685,132
list_of_keywords = list(train['Keywords'].apply(lambda x: [i['name'] for i in eval(x)] if str(x)!= 'nan' else [] ).values )<feature_engineering>
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,685,132
train['num_Keywords'] = train['Keywords'].apply(lambda x: len(eval(x)) if str(x)!= 'nan' else 0) train['all_Keywords'] = train['Keywords'].apply(lambda x: ' '.join(sorted([i['name'] for i in eval(x)])) if str(x)!= 'nan' else '') top_keywords = [m[0] for m in Counter([i for j in list_of_keywords for i in j] ).most_com...
model_path_list = glob.glob('/kaggle/input/cassava-leaf-supervised-contrastive-learning/model_reg*.h5') model_path_list.sort() print('Models to predict:') print(*model_path_list, sep=' ') model_path_list_scl = glob.glob('/kaggle/input/cassava-leaf-supervised-contrastive-learning/model_scl*.h5') model_path_list_scl....
Cassava Leaf Disease Classification
13,685,132
keywords_encoder = LabelEncoder() train['all_Keywords'] = keywords_encoder.fit_transform(train['all_Keywords']) test['all_Keywords'] = keywords_encoder.fit_transform(test['all_Keywords'] )<drop_column>
def encoder_fn(input_shape): inputs = L.Input(shape=input_shape, name='inputs') base_model = efn.EfficientNetB3(input_tensor=inputs, include_top=False, weights=None, pooling='avg') model = Model(inputs=inputs, outputs=base_model.outputs) return model def classifier_fn(input_shape, N_CLASSES, encoder, trainable=True)...
Cassava Leaf Disease Classification
13,685,132
train = train.drop(['Keywords'], axis=1) test = test.drop(['Keywords'], axis=1 )<feature_engineering>
files_path = f'{database_base_path}test_images/' test_size = len(os.listdir(files_path)) test_preds = np.zeros(( test_size, N_CLASSES)) if USE_REGULAR: print('Inference for regular trainining models') with strategy.scope() : encoder = encoder_fn(( None, None, CHANNELS)) model = classifier_fn(( None, None, CHANNELS), N...
Cassava Leaf Disease Classification
13,685,132
<feature_engineering><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,753,285
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<define_variables>
package_path = '.. /input/pytorch-image-models/pytorch-image-models-master' sys.path.append(package_path) DATA_DIR = '.. /input/cassava-leaf-disease-classification' MODEL_DIR = '.. /input/efficientnet-baseline-train-amp-aug'
Cassava Leaf Disease Classification
13,753,285
list_of_cast_members = list(train['cast'].apply(lambda x: [i['name'] for i in x] if str(x)!= 'nan' else [] ).values )<define_variables>
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,753,285
top_cast_members = [m[0] for m in Counter([i for j in list_of_cast_members for i in j] ).most_common(50)]<feature_engineering>
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': [6,7,8,9], 'weights': [1,1,1,1] }
Cassava Leaf Disease Classification
13,753,285
for g in top_cast_members: train['cast_member_'+g] = train['cast'].apply(lambda x: 1 if g in str(x)else 0) for g in top_cast_members: test['cast_member_'+g] = test['cast'].apply(lambda x: 1 if g in str(x)else 0 )<drop_column>
train = pd.read_csv(f'{DATA_DIR}/train.csv' )
Cassava Leaf Disease Classification
13,753,285
train = train.drop(['cast'], axis=1) test = test.drop(['cast'], axis=1 )<feature_engineering>
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
13,753,285
train['crew'] = train['crew'].apply(lambda x: eval(x)if str(x)!= 'nan' else []) test['crew'] = test['crew'].apply(lambda x: eval(x)if str(x)!= 'nan' else [] )<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__(self, i...
Cassava Leaf Disease Classification
13,753,285
list_of_crew_members = list(train['crew'].apply(lambda x: [i['name'] for i in x] if str(x)!= 'nan' else [] ).values )<define_variables>
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,753,285
top_crew_members = [m[0] for m in Counter([i for j in list_of_crew_members for i in j] ).most_common(50)]<feature_engineering>
def inference_one_epoch(model, data_loader, device): model.eval() image_preds_all = [] pbar = tqdm(enumerate(data_loader), total=len(data_loader)) for step,(imgs)in pbar: imgs = imgs.to(device ).float() image_preds = model(imgs) image_preds_all += [torch.softmax(image_preds, 1 ).detach().cpu().numpy() ] image_preds_al...
Cassava Leaf Disease Classification
13,753,285
for g in top_crew_members: train['crew_member_'+g] = train['crew'].apply(lambda x: 1 if g in str(x)else 0) for g in top_crew_members: test['crew_member_'+g] = test['crew'].apply(lambda x: 1 if g in str(x)else 0 )<drop_column>
%%time if __name__ == '__main__': seed_everything(CFG['seed']) stratifiedKFold = StratifiedKFold(n_splits=CFG['fold_num']) folds = stratifiedKFold.split(np.arange(train.shape[0]), train.label.values) for fold,(trn_idx, val_idx)in enumerate(folds): if fold > 0: break print(f'Inference fold {fold} started') valid_ = ...
Cassava Leaf Disease Classification
13,753,285
<feature_engineering><EOS>
test['label'] = np.argmax(tst_preds, axis=1) test.to_csv('submission.csv', index=False )
Cassava Leaf Disease Classification
13,684,511
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<drop_column>
!pip install --quiet /kaggle/input/kerasapplications !pip install --quiet /kaggle/input/efficientnet-git
Cassava Leaf Disease Classification
13,684,511
train = train.drop(['homepage'], axis=1) test = test.drop(['homepage'], axis=1 )<drop_column>
import math, re, os import tensorflow as tf import numpy as np import pandas as pd import matplotlib.pyplot as plt from kaggle_datasets import KaggleDatasets from tensorflow import keras from functools import partial from sklearn.model_selection import train_test_split from tensorflow.keras.callbacks import ModelCheckp...
Cassava Leaf Disease Classification
13,684,511
train = train.drop(['poster_path'], axis=1) test = test.drop(['poster_path'], axis=1 )<drop_column>
AUTOTUNE = tf.data.experimental.AUTOTUNE WORK_PATH = '.. /input/cassava-leaf-disease-classification' BATCH_SIZE = 16 * strategy.num_replicas_in_sync IMAGE_SIZE = [512, 512] CHANNELS = 3 CLASSES = ['0', '1', '2', '3', '4'] EPOCHS = 30
Cassava Leaf Disease Classification
13,684,511
train = train.drop(['status'], axis=1) test = test.drop(['status'], axis=1 )<feature_engineering>
def decode_image(image): image = tf.image.decode_jpeg(image, channels=CHANNELS) image = tf.cast(image, tf.float32)/ 255.0 image = tf.reshape(image, [*IMAGE_SIZE, 3]) return image
Cassava Leaf Disease Classification
13,684,511
for col in ['title', 'tagline', 'overview', 'original_title']: train['len_' + col] = train[col].fillna('' ).apply(lambda x: len(str(x))) train['words_' + col] = train[col].fillna('' ).apply(lambda x: len(str(x.split(' ')))) test['len_' + col] = test[col].fillna('' ).apply(lambda x: len(str(x))) test['words_' + col] =...
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,684,511
train = train.drop(["imdb_id", "original_title", "overview", "tagline", "title"], axis=1) test = test.drop(["imdb_id", "original_title", "overview", "tagline", "title"], axis=1 )<prepare_x_and_y>
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,684,511
X = train.drop(['id', 'revenue'], axis=1) Y = np.log1p(train['revenue']) X_test = test.drop(['id'], axis=1 )<split>
TEST_FILENAMES = tf.io.gfile.glob(WORK_PATH + '/test_tfrecords/ld_test*.tfrec' )
Cassava Leaf Disease Classification
13,684,511
X_train, X_valid, Y_train, Y_valid = train_test_split(X, Y, test_size=0.1 )<choose_model_class>
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,684,511
params = {'num_leaves': 30, 'min_data_in_leaf': 20, 'objective': 'regression', 'max_depth': 5, '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, "verbosity": -1} model = lgb.LGBMRegressor(**params, n_es...
with strategy.scope() : base_model = EfficientNetB5(weights=None, include_top=False, input_shape =(None, None, 3), pooling='avg') model = tf.keras.Sequential([ base_model, tf.keras.layers.Dropout (.3), tf.keras.layers.Dense(len(CLASSES), activation='softmax') ]) model.compile( optimizer=tf.keras.optimizers.Adam(lr ...
Cassava Leaf Disease Classification
13,684,511
y_pred_valid = model.predict(X_valid) y_pred = model.predict(X_test, num_iteration=model.best_iteration_ )<save_to_csv>
model.load_weights('.. /input/cassava-leaf-disease-tpu-efficientnetb4/EffNetB5_best_weights.h5' )
Cassava Leaf Disease Classification
13,684,511
sample_submission['revenue'] = np.expm1(y_pred) sample_submission.to_csv("submission.csv", index=False )<set_options>
def to_float32(image, label): return tf.cast(image, tf.float32), label
Cassava Leaf Disease Classification
13,684,511
pd.set_option('max_columns', None) %matplotlib inline plt.style.use('ggplot') stop = set(stopwords.words('english')) py.init_notebook_mode(connected=True) print(os.listdir(".. /input")) <load_from_csv>
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_TEST_IMAGES = count_data_items(TEST_FILENAMES )
Cassava Leaf Disease Classification
13,684,511
<load_from_csv><EOS>
test_ds = get_test_dataset(ordered=True ).map(to_float32) print('Computing predictions...') test_images_ds = test_ds.map(lambda image, idnum: image) probabilities = model.predict(test_images_ds) test_preds = np.argmax(probabilities, axis=-1) test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch() image_na...
Cassava Leaf Disease Classification
13,460,607
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<feature_engineering>
package_path = '.. /input/pytorch-image-models/pytorch-image-models-master'
Cassava Leaf Disease Classification
13,460,607
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) pr...
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,460,607
for i, e in enumerate(train['belongs_to_collection'][:5]): print(i, e )<count_values>
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,460,607
train['belongs_to_collection'].apply(lambda x: len(x)if x != {} else 0 ).value_counts()<feature_engineering>
train = pd.read_csv('.. /input/cassava-leaf-disease-classification/train.csv') train.head()
Cassava Leaf Disease Classification
13,460,607
train['collection_name'] = train['belongs_to_collection'].apply(lambda x: x[0]['name'] if x != {} else 0) train['has_collection'] = train['belongs_to_collection'].apply(lambda x: len(x)if x != {} else 0) test['collection_name'] = test['belongs_to_collection'].apply(lambda x: x[0]['name'] if x != {} else 0) test['has...
train.label.value_counts()
Cassava Leaf Disease Classification
13,460,607
for i, e in enumerate(train['genres'][:5]): print(i, e )<count_values>
submission = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') submission.head()
Cassava Leaf Disease Classification
13,460,607
print('Number of genres in films') genres_count=train['genres'].apply(lambda x: len(x)if x != {} else 0 ).value_counts() genres_count<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,460,607
list_of_genres = list(train['genres'].apply(lambda x: [i['name'] for i in x] if x != {} else [] ).values) list_of_genres<feature_engineering>
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,460,607
train['num_genres'] = train['genres'].apply(lambda x: len(x)if x != {} else 0) train['all_genres'] = train['genres'].apply(lambda x: ' '.join(sorted([i['name'] for i in x])) if x != {} else '') top_genres = [m[0] for m in Counter([i for j in list_of_genres for i in j] ).most_common(15)] for g in top_genres: train['ge...
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,460,607
for i, e in enumerate(train['production_companies'][:5]): print(i, e )<count_values>
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)) test = pd.DataFrame() test['image_id'] = li...
Cassava Leaf Disease Classification
13,460,607
print('Number of production companies in films') train['production_companies'].apply(lambda x: len(x)if x != {} else 0 ).value_counts()<filter>
test['label'] = np.argmax(tst_preds, axis=1) test.head()
Cassava Leaf Disease Classification
13,460,607
<count_values><EOS>
test.to_csv('submission.csv', index=False )
Cassava Leaf Disease Classification
13,273,599
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<define_variables>
!pip install --quiet /kaggle/input/kerasapplications !pip install --quiet /kaggle/input/efficientnet-git
Cassava Leaf Disease Classification
13,273,599
for i, e in enumerate(train['production_countries'][:5]): print(i, e )<count_values>
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,273,599
print('Number of production countries in films') train['production_countries'].apply(lambda x: len(x)if x != {} else 0 ).value_counts()<count_values>
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,273,599
list_of_countries = list(train['production_countries'].apply(lambda x: [i['name'] for i in x] if x != {} else [] ).values) Counter([i for j in list_of_countries for i in j] ).most_common(25 )<feature_engineering>
BATCH_SIZE = 16 * REPLICAS HEIGHT = 512 WIDTH = 512 CHANNELS = 3 N_CLASSES = 5 TTA_STEPS = 8
Cassava Leaf Disease Classification
13,273,599
train['num_countries'] = train['production_countries'].apply(lambda x: len(x)if x != {} else 0) train['all_countries'] = train['production_countries'].apply(lambda x: ' '.join(sorted([i['name'] for i in x])) if x != {} else '') top_countries = [m[0] for m in Counter([i for j in list_of_countries for i in j] ).most_co...
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,273,599
for i, e in enumerate(train['spoken_languages'][:5]): print(i, e )<count_values>
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,273,599
print('Number of spoken languages in films') train['spoken_languages'].apply(lambda x: len(x)if x != {} else 0 ).value_counts()<count_values>
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,273,599
list_of_languages = list(train['spoken_languages'].apply(lambda x: [i['name'] for i in x] if x != {} else [] ).values) Counter([i for j in list_of_languages for i in j] ).most_common(15 )<feature_engineering>
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,273,599
train['num_languages'] = train['spoken_languages'].apply(lambda x: len(x)if x != {} else 0) train['all_languages'] = train['spoken_languages'].apply(lambda x: ' '.join(sorted([i['name'] for i in x])) if x != {} else '') top_languages = [m[0] for m in Counter([i for j in list_of_languages for i in j] ).most_common(30)...
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,273,599
<count_values><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,499,132
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<feature_engineering>
package_path = '.. /input/pytorch-image-models/pytorch-image-models-master'
Cassava Leaf Disease Classification
13,499,132
list_of_keywords = list(train['Keywords'].apply(lambda x: [i['name'] for i in x] if x != {} else [] ).values) train['num_Keywords'] = train['Keywords'].apply(lambda x: len(x)if x != {} else 0) train['all_Keywords'] = train['Keywords'].apply(lambda x: ' '.join(sorted([i['name'] for i in x])) if x != {} else '') top_k...
from datetime import datetime from glob import glob from scipy.ndimage.interpolation import zoom from skimage import io from sklearn import metrics from sklearn.metrics import log_loss from sklearn.metrics import roc_auc_score, log_loss from sklearn.model_selection import GroupKFold, StratifiedKFold from torch import n...
Cassava Leaf Disease Classification
13,499,132
for i, e in enumerate(train['cast'][:1]): print(i, e )<count_values>
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': 3, 'used_epochs': [6,7,8,9], 'weights': [1,1,1,1] }
Cassava Leaf Disease Classification
13,499,132
print('Number of casted persons in films') train['cast'].apply(lambda x: len(x)if x != {} else 0 ).value_counts().head(15 )<count_values>
train = pd.read_csv('.. /input/cassava-leaf-disease-classification/train.csv') train.head()
Cassava Leaf Disease Classification
13,499,132
list_of_cast_names = list(train['cast'].apply(lambda x: [i['name'] for i in x] if x != {} else [] ).values) Counter([i for j in list_of_cast_names for i in j] ).most_common(15 )<count_unique_values>
train.label.value_counts()
Cassava Leaf Disease Classification
13,499,132
list_of_cast_genders = list(train['cast'].apply(lambda x: [i['gender'] for i in x] if x != {} else [] ).values) Counter([i for j in list_of_cast_genders for i in j] ).most_common()<count_values>
submission = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') submission.head()
Cassava Leaf Disease Classification
13,499,132
list_of_cast_characters = list(train['cast'].apply(lambda x: [i['character'] for i in x] if x != {} else [] ).values) Counter([i for j in list_of_cast_characters for i in j] ).most_common(15 )<feature_engineering>
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
13,499,132
train['num_cast'] = train['cast'].apply(lambda x: len(x)if x != {} else 0) top_cast_names = [m[0] for m in Counter([i for j in list_of_cast_names for i in j] ).most_common(15)] for g in top_cast_names: train['cast_name_' + g] = train['cast'].apply(lambda x: 1 if g in str(x)else 0) train['genders_0_cast'] = train['cas...
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,499,132
print('Number of casted persons in films') train['crew'].apply(lambda x: len(x)if x != {} else 0 ).value_counts().head(10 )<count_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,499,132
list_of_crew_names = list(train['crew'].apply(lambda x: [i['name'] for i in x] if x != {} else [] ).values) Counter([i for j in list_of_crew_names for i in j] ).most_common(15 )<count_values>
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,499,132
list_of_crew_jobs = list(train['crew'].apply(lambda x: [i['job'] for i in x] if x != {} else [] ).values) Counter([i for j in list_of_crew_jobs for i in j] ).most_common(15 )<count_values>
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_ind...
Cassava Leaf Disease Classification
13,499,132
list_of_crew_genders = list(train['crew'].apply(lambda x: [i['gender'] for i in x] if x != {} else [] ).values) Counter([i for j in list_of_crew_genders for i in j] ).most_common(15 )<count_values>
df_test_predict_proba_1 = pd.concat( [test, pd.DataFrame(softmax(tst_preds, axis = 1)) ], axis=1 ).sort_values(["image_id"] )
Cassava Leaf Disease Classification
13,499,132
list_of_crew_departments = list(train['crew'].apply(lambda x: [i['department'] for i in x] if x != {} else [] ).values) Counter([i for j in list_of_crew_departments for i in j] ).most_common(14 )<feature_engineering>
variable_list = %who_ls for _ in variable_list: if _ is not "df_test_predict_proba_1": del globals() [_] %who_ls
Cassava Leaf Disease Classification
13,499,132
train['num_crew'] = train['crew'].apply(lambda x: len(x)if x != {} else 0) top_crew_names = [m[0] for m in Counter([i for j in list_of_crew_names for i in j] ).most_common(15)] for g in top_crew_names: train['crew_name_' + g] = train['crew'].apply(lambda x: 1 if g in str(x)else 0) train['genders_0_crew'] = train['cre...
OUTPUT_DIR = './' MODEL_DIR = '.. /input/cassava-resnext50-32x4d-weights/' if not os.path.exists(OUTPUT_DIR): os.makedirs(OUTPUT_DIR) TRAIN_PATH = '.. /input/cassava-leaf-disease-classification/train_images' TEST_PATH = '.. /input/cassava-leaf-disease-classification/test_images'
Cassava Leaf Disease Classification
13,499,132
train['log_revenue'] = np.log1p(train['revenue'] )<feature_engineering>
class CFG: debug=False num_workers=8 model_name='resnext50_32x4d' size=512 batch_size=32 seed=2020 target_size=5 target_col='label' n_fold=5 trn_fold=[0, 1, 2, 3, 4] inference=True
Cassava Leaf Disease Classification
13,499,132
train['log_budget'] = np.log1p(train['budget']) test['log_budget'] = np.log1p(test['budget'] )<count_values>
sys.path.append('.. /input/pytorch-image-models/pytorch-image-models-master') device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') warnings.filterwarnings('ignore' )
Cassava Leaf Disease Classification
13,499,132
train['homepage'].value_counts().head()<import_modules>
def get_score(y_true, y_pred): return accuracy_score(y_true, y_pred) @contextmanager def timer(name): t0 = time.time() LOGGER.info(f'[{name}] start') yield LOGGER.info(f'[{name}] done in {time.time() - t0:.0f} s.') def init_logger(log_file=OUTPUT_DIR+'inference.log'): logger = getLogger(__name__) logger.setLevel(IN...
Cassava Leaf Disease Classification
13,499,132
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.linear_model import LinearRegression import eli5<train_model>
test = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') test.head()
Cassava Leaf Disease Classification
13,499,132
vectorizer = TfidfVectorizer( sublinear_tf=True, analyzer='word', token_pattern=r'\w{1,}', ngram_range=(1, 2), min_df=5) overview_text = vectorizer.fit_transform(train['overview'].fillna('')) linreg = LinearRegression() linreg.fit(overview_text, train['log_revenue']) eli5.show_weights(linreg, vec=vectorizer, top=20,...
def get_transforms(*, data): if data == 'valid': return A.Compose([ A.Resize(CFG.size, CFG.size), A.Transpose(p=0.5), A.HorizontalFlip(p=0.5), A.VerticalFlip(p=0.5), A.ShiftScaleRotate(p=0.5), A.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], ), ToTensorV2() ] )
Cassava Leaf Disease Classification
13,499,132
test.loc[test['release_date'].isnull() == True, 'release_date'] = '01/01/98'<categorify>
class CustomResNext(nn.Module): def __init__(self, model_name='resnext50_32x4d', pretrained=False): super().__init__() self.model = timm.create_model(model_name, pretrained=pretrained) n_features = self.model.fc.in_features self.model.fc = nn.Linear(n_features, CFG.target_size) def forward(self, x): x = self.model(x)...
Cassava Leaf Disease Classification
13,499,132
def fix_date(x): year = x.split('/')[2] if int(year)<= 19: return x[:-2] + '20' + year else: return x[:-2] + '19' + year<data_type_conversions>
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_...
Cassava Leaf Disease Classification
13,499,132
train['release_date'] = train['release_date'].apply(lambda x: fix_date(x)) test['release_date'] = test['release_date'].apply(lambda x: fix_date(x)) train['release_date'] = pd.to_datetime(train['release_date']) test['release_date'] = pd.to_datetime(test['release_date'] )<data_type_conversions>
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...
Cassava Leaf Disease Classification
13,499,132
def process_date(df): date_parts = ["year", "weekday", "month", 'weekofyear', 'day', 'quarter'] for part in date_parts: part_col = 'release_date' + "_" + part df[part_col] = getattr(df['release_date'].dt, part ).astype(int) return df train = process_date(train) test = process_date(test )<set_options>
df_test_predict_proba_2 = pd.concat( [test["image_id"], pd.DataFrame(softmax(predictions, axis = 1)) ], axis=1 ).sort_values(["image_id"] )
Cassava Leaf Disease Classification
13,499,132
py.init_notebook_mode(connected=True) <count_values>
submission = df_test_predict_proba_1[["image_id"]] submission["label"] =( df_test_predict_proba_1.drop(["image_id"], axis=1)* 0.5 + df_test_predict_proba_2.drop(["image_id"], axis=1)* 0.5 ).to_numpy().argmax(1)
Cassava Leaf Disease Classification
13,499,132
train['status'].value_counts()<count_values>
submission.to_csv("submission.csv", index=False )
Cassava Leaf Disease Classification
13,499,132
<drop_column><EOS>
submission.to_csv("submission.csv", index=False )
Cassava Leaf Disease Classification
14,015,712
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<drop_column>
!pip install.. /input/timmwhl/timm-0.3.3-py3-none-any.whl
Cassava Leaf Disease Classification
14,015,712
<categorify>
import random import os import sys import numpy as np import pandas as pd import torch import torch.nn as nn import torchvision import timm from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils from tqdm import tqdm import torch.nn.functional as F import albumentations as A from alb...
Cassava Leaf Disease Classification
14,015,712
for col in ['original_language', 'collection_name', 'all_genres']: le = LabelEncoder() le.fit(list(train[col].fillna('')) + list(test[col].fillna(''))) train[col] = le.transform(train[col].fillna('' ).astype(str)) test[col] = le.transform(test[col].fillna('' ).astype(str))<define_variables>
warnings.filterwarnings("ignore" )
Cassava Leaf Disease Classification
14,015,712
train_texts = train[['title', 'tagline', 'overview', 'original_title']] test_texts = test[['title', 'tagline', 'overview', 'original_title']]<feature_engineering>
DATA_PATH = '.. /input/cassava-leaf-disease-classification/' bs = 16 sz = 448 TIMM_MODEL = 'resnet50'
Cassava Leaf Disease Classification
14,015,712
for col in ['title', 'tagline', 'overview', 'original_title']: train['len_' + col] = train[col].fillna('' ).apply(lambda x: len(str(x))) train['words_' + col] = train[col].fillna('' ).apply(lambda x: len(str(x.split(' ')))) train = train.drop(col, axis=1) test['len_' + col] = test[col].fillna('' ).apply(lambda x: len...
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,015,712
train.loc[train['id'] == 16,'revenue'] = 192864 train.loc[train['id'] == 90,'budget'] = 30000000 train.loc[train['id'] == 118,'budget'] = 60000000 train.loc[train['id'] == 149,'budget'] = 18000000 train.loc[train['id'] == 313,'revenue'] = 12000000 train.loc[train['id'] == 451,'revenue'] = 12000000 train.loc[train['id']...
class CassavaDataset(Dataset): def __init__(self, dataframe, root_dir, transforms=None): super().__init__() self.dataframe = dataframe self.root_dir = root_dir self.transforms = transforms def __len__(self): return len(self.dataframe) def get_img_bgr_to_rgb(self, path): im_bgr = cv2.imread(path) im_rgb = im_bgr[:, :,...
Cassava Leaf Disease Classification
14,015,712
X = train.drop(['id', 'revenue','production_companies'], axis=1) y = np.log1p(train['revenue']) X_test = test.drop(['id','production_companies'], axis=1 )<split>
def test_transforms() : return Compose([ A.Resize(sz, sz), A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0), ToTensorV2(p=1.0), ], p=1.)
Cassava Leaf Disease Classification
14,015,712
X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.1) <create_dataframe>
class CassavaNet(nn.Module): def __init__(self): super().__init__() backbone = timm.create_model(TIMM_MODEL, pretrained=False) n_features = backbone.fc.in_features self.backbone = nn.Sequential(*backbone.children())[:-2] self.classifier = nn.Linear(n_features, 5) self.pool = nn.AdaptiveAvgPool2d(( 1, 1)) def forward_...
Cassava Leaf Disease Classification
14,015,712
lgb_train = lgb.Dataset(X_train, y_train) lgb_eval = lgb.Dataset(X_valid, y_valid, reference=lgb_train) params = {'num_leaves': 30, 'min_data_in_leaf': 20, 'objective': 'regression', 'max_depth': 5, 'learning_rate': 0.01, "boosting": "gbdt", "feature_fraction": 0.9, "bagging_freq": 1, "bagging_fraction": 0.9, "baggin...
model = CassavaNet().to(device )
Cassava Leaf Disease Classification
14,015,712
eli5.show_weights(model1, feature_filter=lambda x: x != '<BIAS>' )<choose_model_class>
def predict(model, ckpts, dataloader): predict_list=[] with torch.no_grad() : for _, data in enumerate(dataloader): avg_preds = [] for ckpt in ckpts: model.load_state_dict(ckpt['state_dict']) model.eval() images, label = data.values() images = images.to(device) outputs, _ = model(images) preds = F.softmax(outputs )....
Cassava Leaf Disease Classification
14,015,712
n_fold = 5 folds = KFold(n_splits=n_fold, shuffle=True, random_state=42 )<split>
test_df = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') test_dir = '.. /input/cassava-leaf-disease-classification/test_images/' test_ds = CassavaDataset(dataframe=test_df, root_dir=test_dir, transforms=test_transforms()) test_dl = DataLoader(test_ds, batch_size=bs, shuffle=False, ...
Cassava Leaf Disease Classification
14,015,712
def train_model(X, X_test, y, params=None, folds=folds, model_type='lgb', plot_feature_importance=False, model=None): oof = np.zeros(X.shape[0]) prediction = np.zeros(X_test.shape[0]) scores = [] feature_importance = pd.DataFrame() for fold_n,(train_index, valid_index)in enumerate(folds.split(X)) : print('Fold', fold...
ckpts=[] trained_model_path = ".. /input/cassavalblsmoothingresnet50" for path in os.listdir(trained_model_path): ckpts.append(torch.load(os.path.join(trained_model_path, path)))
Cassava Leaf Disease Classification
14,015,712
params = {'num_leaves': 30, 'min_data_in_leaf': 10, 'objective': 'regression', 'max_depth': 5, '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, "verbosity": -1} oof_lgb, prediction_lgb, _ = train_model...
test_predict_list=predict(model, ckpts, test_dl )
Cassava Leaf Disease Classification
14,015,712
<feature_engineering><EOS>
test_df['label'] = test_predict_list test_df[['image_id', 'label']].to_csv('submission.csv', index=False) test_df.head()
Cassava Leaf Disease Classification
14,102,111
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<feature_engineering>
import os import tensorflow as tf from tensorflow import keras from keras.preprocessing.image import load_img,img_to_array,smart_resize import matplotlib.pyplot as plt import cv2 import pandas as pd import json import numpy as np
Cassava Leaf Disease Classification
14,102,111
X = new_features(X) X_test = new_features(X_test )<train_model>
model1=keras.models.load_model('.. /input/notebook841c84bbfb/IncepResNetV2.h5') model2=keras.models.load_model('.. /input/notebook841c84bbfb/EfficientNetB_V2.h5' )
Cassava Leaf Disease Classification
14,102,111
oof_lgb, prediction_lgb, _ = train_model(X, X_test, y, params=params, model_type='lgb', plot_feature_importance=True )<train_model>
train_dir='.. /input/cassava-leaf-disease-classification/train_images' test_dir='.. /input/cassava-leaf-disease-classification/test_images' train=pd.read_csv('.. /input/cassava-leaf-disease-classification/train.csv') sample_sub=pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') sample_...
Cassava Leaf Disease Classification
14,102,111
xgb_params = {'eta': 0.01, 'objective': 'reg:linear', 'max_depth': 7, 'subsample': 0.8, 'colsample_bytree': 0.8, 'eval_metric': 'rmse', 'seed': 11, 'silent': True} oof_xgb, prediction_xgb= train_model(X, X_test, y, params=xgb_params, model_type='xgb', plot_feature_importance=True )<define_variables>
def sample_df(sample_size=100): df= train.sample(sample_size) df=df.reset_index() return df dfs=sample_df(sample_size=50) preds=[] y_true=dfs['label'] for im_id in dfs.image_id: img=load_img(train_dir + '/' + im_id) img=img_to_array(img) img=smart_resize(img,(512,512)) img=np.expand_dims(img,axis=0) img=img/255 pr...
Cassava Leaf Disease Classification
14,102,111
cat_params = {'learning_rate': 0.002, 'depth': 5, 'l2_leaf_reg': 10, 'colsample_bylevel': 0.8, 'bagging_temperature': 0.2, 'od_type': 'Iter', 'od_wait': 100, 'random_seed': 11, 'allow_writing_files': False} oof_cat, prediction_cat = train_model(X, X_test, y, params=cat_params, model_type='cat' )<create_dataframe>
sample_test=pd.DataFrame({'Prediction':preds, 'Actual':y_true}) sample_test.head(30 )
Cassava Leaf Disease Classification
14,102,111
<train_on_grid><EOS>
predictions=[] for img_id in sample_sub.image_id: img=load_img(test_dir + '/' + img_id) img=img_to_array(img) img=smart_resize(img,(512,512)) img=np.expand_dims(img,axis=0) img=img/255 lab=np.argmax(( model1.predict(img)* 0.5)+(model2.predict(img)*0.5)) predictions.append(lab) submission=pd.DataFrame({'image_id':sa...
Cassava Leaf Disease Classification
13,958,924
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<save_to_csv>
package_path = '.. /input/pytorch-image-models/pytorch-image-models-master'
Cassava Leaf Disease Classification
13,958,924
sub = pd.read_csv('.. /input/sample_submission.csv') sub['revenue'] = np.expm1(prediction_lgb) sub.to_csv("lgb.csv", index=False) sub['revenue'] = np.expm1(( prediction_lgb + prediction_xgb)/ 2) sub.to_csv("blend.csv", index=False) sub['revenue'] = np.expm1(( prediction_lgb + prediction_xgb + prediction_cat)/ 3) ...
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