kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
13,880,662
train=pd.read_csv('.. /input/train.csv',index_col=0) test=pd.read_csv('.. /input/test.csv',index_col=0 )<feature_engineering>
submission = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv' )
Cassava Leaf Disease Classification
13,880,662
test['revenue']=-99<drop_column>
def vote_in_ensemble(v1, v2, v3): if v1 == v2: return v1 if v2 == v3: return v2 if v1 == v3: return v3 return v1
Cassava Leaf Disease Classification
13,880,662
train=train.drop('belongs_to_collection',axis=1) test=test.drop('belongs_to_collection',axis=1 )<feature_engineering>
def predict_for_pretrained(model): ds_test = generator(JPEG_PATH,np.sort(submission.image_id.values)) preds = np.argmax(model.predict(ds_test, verbose=True), axis=-1) return preds dense_preds = predict_for_pretrained(dense201) inception_preds = predict_for_pretrained(inception) efficient_net_preds = predict_for_pret...
Cassava Leaf Disease Classification
13,880,662
<feature_engineering><EOS>
submission["label"] = result submission.to_csv("submission.csv", index=False )
Cassava Leaf Disease Classification
13,628,995
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<concatenate>
!pip install --quiet /kaggle/input/kerasapplications !pip install --quiet /kaggle/input/efficientnet-git
Cassava Leaf Disease Classification
13,628,995
new_data=pd.concat([train,test],axis=0) new_data.head()<count_missing_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 = 21 seed_everything(seed) warnings.filterwarnings('ignore' )
Cassava Leaf Disease Classification
13,628,995
new_data.isnull().sum()<filter>
BATCH_SIZE = 32 * REPLICAS HEIGHT = 512 WIDTH = 512 CHANNELS = 3 N_CLASSES = 5 TTA_STEPS = 8
Cassava Leaf Disease Classification
13,628,995
new_data[new_data['release_date'].isnull() ]<feature_engineering>
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,628,995
new_data['release_date']=new_data['release_date'].fillna('3/20/01' )<data_type_conversions>
def get_name(file_path): parts = tf.strings.split(file_path, os.path.sep) name = parts[-1] return name def decode_image(image_data): image = tf.image.decode_jpeg(image_data, channels=3) image = tf.cast(image, tf.float32)/ 255.0 return image def center_crop(image): image = tf.reshape(image, [600, 800, CHANNELS]) h, w...
Cassava Leaf Disease Classification
13,628,995
new_data['release_year']=pd.to_datetime(new_data['release_date'] ).dt.year new_data['release_month']=pd.to_datetime(new_data['release_date'] ).dt.month new_data['release_day']=pd.to_datetime(new_data['release_date'] ).dt.day<feature_engineering>
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,628,995
new_data['release_year'].loc[new_data['release_year']>=2018]-=100<drop_column>
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,628,995
new_data=new_data.drop('release_date',axis=1 )<define_variables>
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,628,995
weiji=[1929,1930,1930,1931,1932,1933,1934,1935,1936,1937,1938,1939,1940,1941,1942,1943,1944,1945,1950,1951,1952,1953,1961,1962,1963,1964,1965,1966,1967,1968,1969,1971,1973,1974,1975,1980,1981,1982,1983,1984,1985,1986,1987,1988,1989, 1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2007,2008,2009,2010,2011]<feature_eng...
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,906,147
for i in weiji: new_data['is_'+str(i)]=new_data['release_year'].apply(lambda x:1 if x==i else 0 )<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,906,147
new_data['homepage_fact']=new_data['homepage'].apply(lambda x: 0 if x is np.nan else 1 )<feature_engineering>
CFG = { 'vit_img_size': 384, 'tta': 3, 'valid_bs': 16, 'device': 'cuda' if torch.cuda.is_available() else 'cpu', 'vit_models': ['model_5.pt', 'model_6.pt', 'model_7.pt', 'model_8.pt'] }
Cassava Leaf Disease Classification
13,906,147
new_data['homepage_end']=new_data[new_data['homepage'].notna() ]['homepage'].str.findall(r'\.( [a-z]+ )(?:\/|$)' ).apply(lambda x:x[0]) new_data['homepage_end'].head()<data_type_conversions>
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,906,147
new_data['homepage_end']=new_data['homepage_end'].fillna('unknow' )<categorify>
def get_inference_transforms(img_size = 512): return Compose([ CenterCrop(img_size, img_size, p=0.5), Resize(img_size, img_size), Transpose(p=0.5), RandomRotate90(p=0.25), ShiftScaleRotate(p=0.5), HorizontalFlip(p=0.5), VerticalFlip(p=0.5), HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0....
Cassava Leaf Disease Classification
13,906,147
page=pd.get_dummies(new_data['homepage_end']) page.head()<drop_column>
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,906,147
new_data=new_data.drop('homepage',axis=1 )<drop_column>
test_csv = df.copy() test_csv['image_id'] = PATH + test_csv['image_id']
Cassava Leaf Disease Classification
13,906,147
new_data=new_data.drop('poster_path',axis=1 )<feature_engineering>
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,906,147
new_data['len_overview']=new_data['overview'].fillna('NAN' ).apply(lambda x:len(x)) new_data['len_overview'][new_data['len_overview']==0]=1 new_data['len_overview_budget']=new_data['budget']/(new_data['len_overview']+1 )<sort_values>
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.head.in_features self.model.head = nn.Linear(n_features, n_class) def forward(self, x): x = self.model(x) re...
Cassava Leaf Disease Classification
13,906,147
len_rew_sort=new_data['len_overview'].sort_values(ascending=True) len_rew_sort.head()<define_variables>
vit_test_ds = DiseaseDatasetInference(test_csv, transform=get_inference_transforms(img_size=CFG['vit_img_size']), opt_label=False) vit_test_loader = torch.utils.data.DataLoader(vit_test_ds, batch_size=CFG['valid_bs'], shuffle=False, pin_memory=False )
Cassava Leaf Disease Classification
13,906,147
length=len(new_data['len_overview']) m=0.1 n=0.1 arr_len_ove=[] for i in range(1,11): arr_len_ove.append(round(length*m)) m+=n arr_len_ove<filter>
vit_preds = [] for vit_model_name in CFG['vit_models']: print("Model: ", vit_model_name) vit_model = torch.load('/kaggle/input/vit-cassava/'+vit_model_name, map_location=torch.device(CFG['device'])) with torch.no_grad() : for i in range(CFG['tta']): vit_preds += [inference(vit_model, vit_test_loader, CFG['device'])] v...
Cassava Leaf Disease Classification
13,906,147
for i in range(10): qu=qu_arr[i] if i==0: new_data['len_overview'].loc[(new_data['len_overview']<len_rew_sort.iloc[arr_len_ove[i]-1])]=qu else: new_data['len_overview'].loc[(new_data['len_overview']<len_rew_sort.iloc[arr_len_ove[i]-1])&(new_data['len_overview'] >qu_arr[i-1])]=qu print(i,qu )<groupby>
vit_outcomes = pd.concat([df['image_id'], pd.DataFrame(vit_preds)], axis=1 ).sort_values(['image_id'] )
Cassava Leaf Disease Classification
13,906,147
len_ove_agg=new_data.groupby('len_overview' ).revenue.aggregate(['min','max','std'] )<feature_engineering>
final_preds = vit_outcomes.drop('image_id', axis=1 ).to_numpy().argmax(1 )
Cassava Leaf Disease Classification
13,906,147
new_data['geres_name']=new_data['genres'].str.findall(r''name'\s?:\s?'(\w+)'') new_data['geres_name'].head()<drop_column>
submit = pd.DataFrame({'image_id': df['image_id'].values, 'label': final_preds}) submit.to_csv('submission.csv', index=False )
Cassava Leaf Disease Classification
13,786,497
new_data=new_data.drop('genres',axis=1 )<find_best_params>
test_df = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') print(test_df) AUTOTUNE = tf.data.experimental.AUTOTUNE GCS_PATH = '.. /input/cassava-leaf-disease-classification' BATCH_SIZE = 16*8 IMAGE_SIZE = [512,512] CLASSES = ["1", "2", "3", "4", "5"] def dataset_sizes(filenames): n =...
Cassava Leaf Disease Classification
13,786,497
country=new_data['production_countries'].str.findall(r'[A-Z]{2,5}') <feature_engineering>
def to_float32(image, label): return tf.cast(image, tf.float32), label def decode_img(img): img = tf.io.decode_jpeg(img, channels = 3) img = tf.cast(img, tf.float32)/255.0 img = tf.reshape(img, [*IMAGE_SIZE, 3]) return img def read_tfrecord(example, labeled): if labeled: TFREC_FORMAT = { "image": tf.io.FixedLenFeatur...
Cassava Leaf Disease Classification
13,786,497
new_data['production_countries']=country <feature_engineering>
test_ds = get_test_data(ordered=True) test_ds = test_ds.map(to_float32) testing_dataset = get_test_data() testing_dataset = testing_dataset.unbatch().batch(1) print('Computing predictions...') test_images_ds = testing_dataset test_images_ds = test_ds.map(lambda image, idnum: image) prob1 = model_15.predict(test_im...
Cassava Leaf Disease Classification
13,786,497
<drop_column><EOS>
print('Generating submission.csv file...') test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch() test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U') np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='image_id,label', ...
Cassava Leaf Disease Classification
13,431,242
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<concatenate>
package_path = '.. /input/pytorchimagemodels'
Cassava Leaf Disease Classification
13,431,242
new_data=pd.concat([new_data,page],axis=1 )<feature_engineering>
import os import random import cv2 import timm import pandas as pd import numpy as np import matplotlib.pyplot as plt import albumentations as A import albumentations.pytorch as Apy import torch import torchvision from torch import nn from torchvision import transforms from torch.utils.data import Dataset,DataLoader fr...
Cassava Leaf Disease Classification
13,431,242
new_data['production_companies']=new_data['production_companies'].str.findall(r''name'?:\s?'([A-Za-z]+)') new_data.fillna('Unknow') print('接下来就是地图可视化了' )<drop_column>
config = { 'fold_num': 1, 'seed': 719, 'model_arch': 'resnext50d_32x4d', 'img_size': 512, 'valid_bs': 256, 'num_workers': 4, 'accum_iter': 1, 'verbose_step': 1, 'device': 'cuda:0' if torch.cuda.is_available() else "cpu", }
Cassava Leaf Disease Classification
13,431,242
new_data=new_data.drop('imdb_id',axis=1 )<feature_engineering>
submission = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') submission.head()
Cassava Leaf Disease Classification
13,431,242
new_data['spoken_languages']=new_data['spoken_languages'].str.findall(r''([a-z]{2})'' )<data_type_conversions>
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) return im_bgr[:, :, ::-1]
Cassava Leaf Disease Classification
13,431,242
new_data['production_companies']=new_data['production_companies'].fillna('unknow' )<data_type_conversions>
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,431,242
new_data['spoken_languages']=new_data['spoken_languages'].fillna('unknow' )<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.fc.in_features self.model.fc = nn.Linear(n_features, n_class) def forward(self, x): x = self.model(x) return x
Cassava Leaf Disease Classification
13,431,242
new_data['Keywords']=new_data['Keywords'].str.findall(r''?:\s?'([a-z]+\s?[a-z]+)'' ).fillna('unkonw' )<count_unique_values>
test = pd.DataFrame() test['image_id'] = list(os.listdir('.. /input/cassava-leaf-disease-classification/test_images/')) test_ds = CassavaDataset(test, '.. /input/cassava-leaf-disease-classification/test_images/', transforms=get_inference_transforms() , output_label=False) tst_loader = torch.utils.data.DataLoader( tes...
Cassava Leaf Disease Classification
13,431,242
<feature_engineering><EOS>
test['label'] = np.argmax(tst_preds, axis=1) test.to_csv('submission.csv', index=False )
Cassava Leaf Disease Classification
13,315,962
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<drop_column>
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,315,962
new_data=new_data.drop('Keywords',axis=1 )<data_type_conversions>
class CFG: debug=False num_workers=20 model_name='resnext50_32x4d' size=512 batch_size=32 seed=42 target_size=5 target_col='label' n_fold=5 trn_fold=[0, 1, 2, 3, 4] inference=True
Cassava Leaf Disease Classification
13,315,962
new_data['cast']=new_data['cast'].fillna('unknow' )<feature_engineering>
test = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') test.head()
Cassava Leaf Disease Classification
13,315,962
for i in d: m=i[0][0] new_data['cast_name_'+m]=new_data['cast'].apply(lambda x:1 if m in x else 0 )<count_values>
class TestDataset(Dataset): def __init__(self, df, transform=None): self.df = df self.file_names = df['image_id'].values self.transform = transform def __len__(self): return len(self.df) def __getitem__(self, idx): file_name = self.file_names[idx] file_path = f'{TEST_PATH}/{file_name}' image = cv2.imread(file_path) i...
Cassava Leaf Disease Classification
13,315,962
list_cast_gender=list(new_data['cast'].str.findall(r''gender'\s?:\s?(\d+)\s?')) Counter([i for j in list_cast_gender for i in j] ).most_common()<feature_engineering>
def get_transforms(*, data): if data == 'valid': return A.Compose([ A.Resize(CFG.size, CFG.size), A.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], ), ToTensorV2() , ] )
Cassava Leaf Disease Classification
13,315,962
new_data['cast_gender_0']=new_data['cast'].str.findall(r''gender'\s?:\s?(\d+)\s?' ).apply(lambda x: x.count('0')) new_data['cast_gender_1']=new_data['cast'].str.findall(r''gender'\s?:\s?(\d+)\s?' ).apply(lambda x: x.count('1')) new_data['cast_gender_2']=new_data['cast'].str.findall(r''gender'\s?:\s?(\d+)\s?' ).apply(la...
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,315,962
for g in top_cast_char: m=g[0] new_data['cast_char_'+m]=new_data['cast'].apply(lambda x:1 if m in x else 0 )<drop_column>
def load_state(model_path): model = CustomResNext(CFG.model_name, pretrained=False) try: model.load_state_dict(torch.load(model_path)['model'], strict=True) state_dict = torch.load(model_path)['model'] except: state_dict = torch.load(model_path)['model'] state_dict = {k[7:] if k.startswith('module.')else k: state_dic...
Cassava Leaf Disease Classification
13,315,962
<feature_engineering><EOS>
model = CustomResNext(CFG.model_name, pretrained=False) states = [load_state(MODEL_DIR+f'{CFG.model_name}_fold{fold}.pth')for fold in CFG.trn_fold] test_dataset = TestDataset(test, transform=get_transforms(data='valid')) test_loader = DataLoader(test_dataset, batch_size=CFG.batch_size, shuffle=False, num_workers=CFG.n...
Cassava Leaf Disease Classification
13,376,525
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<feature_engineering>
import numpy as np import pandas as pd from tensorflow import keras
Cassava Leaf Disease Classification
13,376,525
new_data['overview']=new_data['overview'].fillna('' )<import_modules>
model = keras.models.Sequential() model.add(keras.applications.Xception(input_shape=(300, 300, 3), weights=None, include_top=False)) model.add(keras.layers.GlobalAveragePooling2D()) model.add(keras.layers.Dense(5, activation='softmax')) model.summary()
Cassava Leaf Disease Classification
13,376,525
from sklearn.linear_model import LinearRegression import eli5 from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer <train_on_grid>
model.load_weights(".. /input/cassava-xception-try/best_weights_xception.h5" )
Cassava Leaf Disease Classification
13,376,525
<load_pretrained><EOS>
preds = [] ss = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') for image in ss.image_id: img = keras.preprocessing.image.load_img('.. /input/cassava-leaf-disease-classification/test_images/' + image) img = keras.preprocessing.image.img_to_array(img) img = keras.preprocessing.image...
Cassava Leaf Disease Classification
13,293,951
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<feature_engineering>
OUTPUT_DIR = './' MODEL_DIR = '.. /input/cassava-xception-4fold/' 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,293,951
new_data['crew_0']=new_data['crew'].fillna('' ).str.replace(',','' ).str.replace('}','' ).str.findall(''gender\S?'\s?:\s?\S?(\d+)\s?\S?' ).apply(lambda x:x.count('0')) new_data['crew_1']=new_data['crew'].fillna('' ).str.replace(',','' ).str.replace('}','' ).str.findall(''gender\S?'\s?:\s?\S?(\d+)\s?\S?' ).apply(lambda ...
class CFG: debug=False num_workers=0 model_name='xception' size=386 batch_size=32 seed=2020 target_size=5 target_col='label' n_fold=4 trn_fold=[0, 1, 2, 3] train=False inference=True
Cassava Leaf Disease Classification
13,293,951
for i in d: new_data['crew_depart_is_'+i[0]]=new_data['crew'].fillna('' ).apply(lambda x:1 if i[0] in x else 0) for i in dd: new_data['crew_job_is_'+i[0]]=new_data['crew'].fillna('' ).apply(lambda x:1 if i[0] in x else 0 )<feature_engineering>
test = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') test.head()
Cassava Leaf Disease Classification
13,293,951
new_data['crew']=new_data['crew'].str.replace(',','' ).str.replace('}','' ).str.replace(r''gender'\s?\S?:\s?\S?\s+'id'\s?:\s?\d+','' ).str.findall(r''department'\s?\S?:\s+\S?(\S+)\S?\s?\S?\s+'job\S?'\s?:\s?'(\D+)\S\s?\S?'name\S?'\s?:\s?'(\D+)'\s?\S?'profile_path\S?':\s+'?(\S+)\S?\s?\s?\S?' )<feature_engineering>
class TestDataset(Dataset): def __init__(self, df, transform=None): self.df = df self.file_names = df['image_id'].values self.transform = transform def __len__(self): return len(self.df) def __getitem__(self, idx): file_name = self.file_names[idx] file_path = f'{TEST_PATH}/{file_name}' image = cv2.imread(file_path) i...
Cassava Leaf Disease Classification
13,293,951
new_data['len_crew']=new_data['crew'].fillna('1' ).apply(lambda x:len(x))<filter>
def get_transforms(*, data): if data == 'train': return Compose([ RandomResizedCrop(CFG.size, CFG.size), Transpose(p=0.5), HorizontalFlip(p=0.5), VerticalFlip(p=0.5), ShiftScaleRotate(p=0.5), Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], ), ToTensorV2() , ]) elif data == 'valid': return Compose([...
Cassava Leaf Disease Classification
13,293,951
new_train=new_data.loc[np.array(train.index)]<feature_engineering>
class CustomResNext(nn.Module): def __init__(self, model_name='xception', 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) retur...
Cassava Leaf Disease Classification
13,293,951
new_train['production_countries']=new_train['production_countries'].fillna('' )<feature_engineering>
def inference(model, states, test_loader, device): model.to(device) tk0 = tqdm(enumerate(test_loader), total=len(test_loader)) probs = [] for i,(images)in tk0: images = images.to(device) avg_preds = [] for state in states: model.load_state_dict(state['model']) model.eval() with torch.no_grad() : y_preds = model(imag...
Cassava Leaf Disease Classification
13,293,951
new_train['production_countries']=new_train['production_countries'].apply(lambda x:'_'.join(x))<count_values>
model = CustomResNext(CFG.model_name, pretrained=False) states = [torch.load(f'.. /input/cassava-xception-4fold/xception_fold{fold}_best.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=Fals...
Cassava Leaf Disease Classification
13,322,937
count=new_train['production_countries'].value_counts() count=count[count>5]<groupby>
print("Tensorflow version " + tf.__version__)
Cassava Leaf Disease Classification
13,322,937
bud=new_train.groupby('production_countries' ).budget.mean()<sort_values>
AUTOTUNE = tf.data.experimental.AUTOTUNE REPLICAS = strategy.num_replicas_in_sync FILENAMES = tf.io.gfile.glob(".. /input/cassava-leaf-disease-classification" + '/test_tfrecords/ld_test*.tfrec') BATCH_SIZE = 128 * strategy.num_replicas_in_sync IMAGE_SIZE = [512, 512] classes = ['0', '1', '2', '3', '4'] os.environ['PYT...
Cassava Leaf Disease Classification
13,322,937
bud=bud.sort_values(ascending=False)[:10]<groupby>
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 def read_labeled_tfrecord(example): LABELED_TFREC_FORMAT = { "image": tf.io.FixedLenFeature([], tf.string), "target": tf.io.FixedLenFeature([], tf...
Cassava Leaf Disease Classification
13,322,937
rev=new_train.groupby('production_countries' ).revenue.mean()<sort_values>
VALIDATE = False
Cassava Leaf Disease Classification
13,322,937
rev=rev.sort_values(ascending=False)[:10]<filter>
FOLDS=5 SEED=34 if VALIDATE: GCS_PATH = KaggleDatasets().get_gcs_path('cassava-leaf-disease-tfrecords-512x512') TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/*.tfrec') AUG_TYPE = 'CUTMIXUP'
Cassava Leaf Disease Classification
13,322,937
new_train['production_countries'].loc[new_train['production_countries']=='ET']='Ethiopia' along_co=new_train[new_train['production_countries'].apply(lambda x:1 if len(x)==2 else 0)==1] along_co.head()<define_variables>
if VALIDATE: histories = [] oof_pred = []; oof_labels = [] kfold = KFold(FOLDS, shuffle = True, random_state = SEED) for f,(train_index, val_index)in enumerate(kfold.split(TRAINING_FILENAMES)) : print(' print('Getting datasets...'); print('') val_ds = get_val_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_...
Cassava Leaf Disease Classification
13,322,937
count_rev=along_co[['production_countries','revenue']]<prepare_output>
if VALIDATE: y_true = np.concatenate(oof_labels) y_preds = np.concatenate(oof_pred) print(classification_report(np.argmax(y_true, axis=1)if AUG_TYPE is 'CUTMIXUP' else y_true, y_preds)) print(f"OOF accuracy score: {accuracy_score(np.argmax(y_true, axis=1)if AUG_TYPE is 'CUTMIXUP' else y_true, y_preds)}" )
Cassava Leaf Disease Classification
13,322,937
dd=count_rev['production_countries'].unique() mn=pd.DataFrame(dd,columns=['address']) mn.head()<load_pretrained>
JPEG_PATH = ".. /input/cassava-leaf-disease-classification/test_images" JPEG_PATH_TR = ".. /input/cassava-leaf-disease-classification/train_images" def load_image(jpeg_path, image_id): img = cv2.imread(os.path.join(jpeg_path, image_id)) /255.0 img = cv2.resize(img,(512, 512)) [:, :, ::-1] return img def generator(filep...
Cassava Leaf Disease Classification
13,322,937
import geopandas as ge <load_from_csv>
submission = pd.read_csv('.. /input/cassava-leaf-disease-classification/sample_submission.csv') tr = pd.read_csv('.. /input/cassava-leaf-disease-classification/train.csv' )
Cassava Leaf Disease Classification
13,322,937
world = ge.read_file(ge.datasets.get_path('naturalearth_lowres'))<import_modules>
preds_all = [] preds_model = [] for fold in range(FOLDS): print(f" ds_test = generator(JPEG_PATH,submission.image_id.values) K.clear_session() print('Loading and inferring...') model = tf.keras.models.load_model(f'.. /input/cassava-tensorflow-starter-training/EFFNET_{fold}_34_CUTMIXUP_512_full.h5') preds = model.pre...
Cassava Leaf Disease Classification
13,322,937
from mpl_toolkits.axes_grid1 import make_axes_locatable <count_values>
submission["label"] = preds_all.mean(0 ).argmax(1) submission.to_csv("submission.csv", index=False )
Cassava Leaf Disease Classification
13,280,913
dd=count_rev['production_countries'].value_counts() mn['values']=dd.values mn.head()<categorify>
package_path = '.. /input/vision-transformer-pytorch/VisionTransformer-Pytorch' sys.path.append(package_path )
Cassava Leaf Disease Classification
13,280,913
mn['address'][0]='United States' mn['address'][2]='Korea' mn['address'][1]='India' mn['address'][3]='Serbia' mn['address'][4]='United Kingdom' mn['address'][5]='France' mn['address'][6]='New Zealand' mn['address'][7]='Italy' mn['address'][8]='Belgium' mn['address'][9]='Czech Rep.' mn['address'][11]='Russia' mn['address...
import os import pandas as pd import albumentations as albu import matplotlib.pyplot as plt import json import seaborn as sns import cv2 import albumentations as albu import numpy as np
Cassava Leaf Disease Classification
13,280,913
mn=mn.drop(10) mn=mn.drop(34 )<feature_engineering>
BASE_DIR=".. /input/cassava-leaf-disease-classification/" TRAIN_IMAGES_DIR=os.path.join(BASE_DIR,'train_images') train_df=pd.read_csv(os.path.join(BASE_DIR,'train.csv'))
Cassava Leaf Disease Classification
13,280,913
mn['geometry']='unknow'<feature_engineering>
print("Count of training images {0}".format(len(os.listdir(TRAIN_IMAGES_DIR))))
Cassava Leaf Disease Classification
13,280,913
for i in range(39): if i==10 or i==34: continue; d=world[world['name']==mn['address'][i]]['geometry'].values[0] mn['geometry'][i]=d<feature_engineering>
with open(f'{BASE_DIR}/label_num_to_disease_map.json', 'r')as f: name_mapping = json.load(f) name_mapping = {int(k): v for k, v in name_mapping.items() } train_df["class_id"]=train_df["label"].map(name_mapping )
Cassava Leaf Disease Classification
13,280,913
TS = train.loc[:,["original_title","release_date","budget","runtime","revenue"]] TS.dropna() TS.release_date = pd.to_datetime(TS.release_date) TS.loc[:,"Year"] = TS["release_date"].dt.year TS.loc[:,"Month"] = TS["release_date"].dt.month TS = TS[TS.Year<2018]<sort_values>
import torch import torch.nn as nn import torchvision.models as models import torch.optim as optim from torch.utils.data import Dataset, DataLoader from torch.optim.lr_scheduler import ReduceLROnPlateau from sklearn.metrics import accuracy_score from sklearn.model_selection import StratifiedKFold, GroupKFold, KFold, tr...
Cassava Leaf Disease Classification
13,280,913
top3 = train.sort_values(by='popularity',ascending=False)[:10] id3=top3[['title','poster_path','revenue']]<count_values>
class CassavaDataset(Dataset): def __init__(self,df:pd.DataFrame,imfolder:str,train:bool = True, transforms=None): self.df=df self.imfolder=imfolder self.train=train self.transforms=transforms def __getitem__(self,index): im_path=os.path.join(self.imfolder,self.df.iloc[index]['image_id']) x=cv2.imread(im_path,cv2.IMRE...
Cassava Leaf Disease Classification
13,280,913
old_title=new_data['title'].value_counts()<prepare_x_and_y>
train, valid = train_test_split( train_df, test_size=0.1, random_state=42, stratify=train_df.label.values ) train = train.reset_index(drop=True) valid = valid.reset_index(drop=True) train_targets = train.label.values valid_targets = valid.label.values
Cassava Leaf Disease Classification
13,280,913
a=old_title[old_title.values==3].index b=old_title[old_title==2].index<feature_engineering>
train_dataset=CassavaDataset( df=train, imfolder=TRAIN_IMAGES_DIR, train=True, transforms=train_augs ) valid_dataset=CassavaDataset( df=valid, imfolder=TRAIN_IMAGES_DIR, train=True, transforms=valid_augs )
Cassava Leaf Disease Classification
13,280,913
new_data['fan_pai_2']=new_data['title'].apply(lambda x:1 if x in a else 0) new_data['pan_pai_3']=new_data['title'].apply(lambda x:1 if x in b else 0 )<filter>
train_loader = DataLoader( train_dataset, batch_size=16, num_workers=4, shuffle=True, ) valid_loader = DataLoader( valid_dataset, batch_size=16, num_workers=4, shuffle=False, )
Cassava Leaf Disease Classification
13,280,913
new_data.loc[new_data['title'].fillna('un' ).str.contains('Planet of the Apes')]<sort_values>
def train_model(datasets, dataloaders, model, criterion, optimizer, scheduler, num_epochs, device): since = time.time() best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 for epoch in range(num_epochs): print('Epoch {}/{}'.format(epoch, num_epochs-1)) print('-' * 10) for phase in ['train', 'valid']: if...
Cassava Leaf Disease Classification
13,280,913
top10 = train.sort_values(by='revenue',ascending=False)[:10] id10=top10[['title','poster_path','revenue']]<count_values>
datasets={'train':train_dataset,'valid':valid_dataset} dataloaders={'train':train_loader,'valid':valid_loader} device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = VisionTransformer.from_name('ViT-B_16', num_classes=5) optimizer = torch.optim.AdamW(model.parameters() , lr=1e-4, weight_decay=0...
Cassava Leaf Disease Classification
13,280,913
title_count=train['title'].value_counts() len(title_count[title_count.values!=1] )<filter>
model.load_state_dict(torch.load('.. /input/vit-model-1/ViT-B_16.pt'))
Cassava Leaf Disease Classification
13,280,913
train[train['title'].str.contains('Furious')]['title'] <filter>
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
13,280,913
test[test['title'].fillna('Unknow' ).str.contains('Furious')]['title']<drop_column>
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
13,280,913
d.remove(d[7] )<feature_engineering>
test_df['label'] = np.concatenate(predictions)
Cassava Leaf Disease Classification
13,280,913
<feature_engineering><EOS>
test_df.to_csv('submission.csv', index=False )
Cassava Leaf Disease Classification
13,209,362
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<feature_engineering>
import math, os, re, warnings, random, glob import numpy as np import pandas as pd import tensorflow as tf import tensorflow.keras.layers as L import tensorflow.keras.backend as K from tensorflow.keras import Sequential from kaggle_datasets import KaggleDatasets
Cassava Leaf Disease Classification
13,209,362
new_data['spoken_languages_count']=new_data['spoken_languages'].apply(lambda x:len(x))<groupby>
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,209,362
new_data.loc[train.index].groupby('spoken_languages_count' ).revenue.median()<categorify>
BATCH_SIZE = 16 * REPLICAS HEIGHT = 512 WIDTH = 512 CHANNELS = 3 N_CLASSES = 5 TTA_STEPS = 3 IMAGE_SIZE = [512, 512] SEED =555 BATCH_SIZE = 16 * strategy.num_replicas_in_sync AUG_BATCH = BATCH_SIZE
Cassava Leaf Disease Classification
13,209,362
status_du=pd.get_dummies(new_data['status'] )<concatenate>
def data_augment(image, label): image = tf.image.rot90(image,k=np.random.randint(4)) image = tf.image.random_flip_left_right(image , seed=SEED) image= image = tf.image.random_flip_up_down(image, seed=SEED) IMG_SIZE=IMAGE_SIZE[0] image = tf.image.resize_with_crop_or_pad(image, IMG_SIZE + 6, IMG_SIZE + 6) image = tf.i...
Cassava Leaf Disease Classification
13,209,362
new_data=pd.concat([new_data,status_du],axis=1) <drop_column>
def get_name(file_path): parts = tf.strings.split(file_path, os.path.sep) name = parts[-1] return name def decode_image(image_data): image = tf.image.decode_jpeg(image_data, channels=3) image = tf.cast(image, tf.float32)/ 255.0 image = tf.reshape(image, [*IMAGE_SIZE, 3]) return image def resize_image(image, label): ...
Cassava Leaf Disease Classification
13,209,362
new_data=new_data.drop(['status'],axis=1) new_data.head()<drop_column>
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/*.tfrec') NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES) print(f'GCS:...
Cassava Leaf Disease Classification
13,209,362
new_data=new_data.drop(['original_language'],axis=1 )<count_missing_values>
model_path_list = glob.glob('/kaggle/input/casavaleafclassificationdensenet201e20f3/*.h5') model_path_list.sort() print('Models to predict:') print(*model_path_list, sep=' ' )
Cassava Leaf Disease Classification
13,209,362
sum(new_data['geres_name'].isna() )<data_type_conversions>
models = [] i = 0 for model_path in model_path_list: print(model_path) K.clear_session() models.append(keras.models.load_model(model_path))
Cassava Leaf Disease Classification
13,209,362
new_data['geres_name']=new_data['geres_name'].fillna('Unknow' )<feature_engineering>
print(" TTA_STEPS = {} ".format(TTA_STEPS)) if TTA_STEPS > 0: for step in range(TTA_STEPS): test_ds = get_test_dataset(ordered=True, tta=True) print(f'TTA step {step+1}/{TTA_STEPS}') test_images_ds = test_ds.map(lambda image, image_name: image) probabilities = np.average([models[i].predict(test_images_ds)for i in ra...
Cassava Leaf Disease Classification
13,209,362
<groupby><EOS>
print('Generating submission.csv file...') test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch() test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U') np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='image_id,label', ...
Cassava Leaf Disease Classification
13,020,876
<SOS> metric: CategorizationAccuracy Kaggle data source: cassava-leaf-disease-classification<drop_column>
package_path = '.. /input/pytorch-image-models/pytorch-image-models-master'
Cassava Leaf Disease Classification
13,020,876
new_data=new_data.drop('homepage_end',axis=1 )<feature_engineering>
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,020,876
new_data['original_and_new']=new_data['original_and_new'].apply(lambda x: 1 if x else 0 )<define_variables>
CFG = { 'folder' : 'effnetb5512', 'fold_num': [0], 'seed': 719, 'model_arch': 'tf_efficientnet_b5_ns', 'img_size': 512, 'epochs': 21, 'train_bs': 16, 'valid_bs': 16, 'lr': 1e-4, 'num_workers': 4, 'accum_iter': 1, 'verbose_step': 1, 'device': 'cuda:0', 'tta': 5, 'used_epochs': [3,4,5], 'weights': [1,1,1] } CFG1 = { 'fol...
Cassava Leaf Disease Classification