Kaggle competition: Plant Pathology 2020 - FGVC7
<SOS> metric: MCAUC Kaggle data source: plant-pathology-2020-fgvc7<predict_on_test>
!pip install knockknock
!pip install -q efficientnet
c = model_con.predict(test)
 for i in range(len(c)) :
if c[i]<0:
c[i] = 0
c[i] = int(c[i])
 c[i] = int(c[i])
<feature_engineering>
user_secrets = UserSecretsClient()
token = user_secrets.get_secret("token")
 chat_id = user_secrets.get_secret("chat_id")
 warnings.filterwarnings('ignore' )
con_pred = np.around(c,decimals = 0 )<train_model>
AUTO = tf.data.experimental.AUTOTUNE
try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
print('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.distribute.get_strategy()
print("REPLICAS: ", strategy.num_replicas_in_sync)
 GCS_DS_PATH = KaggleDatasets().get_gcs_path()
model_fal = XGBRegressor(n_estimators = 3000 ,random_state = 0,max_depth = 20,learning_rate = 0.01
,objective = 'reg:squarederror',min_child_weight = 1,gamma = 0.7,n_thread = 4)
 model_fal.fit(train,fatalities )<predict_on_test>
SEED = 42
BATCH_SIZE = 8 * strategy.num_replicas_in_sync
SIZE = [800,800]
LR = 0.0008
WEIGHT_DECAY = 0
EPOCHS = 40
WARMUP = 15
TTA = 4
result_fal = model_fal.predict(test )<feature_engineering>
def seed_everything(SEED):
np.random.seed(SEED)
 tf.random.set_seed(SEED)
 seed_everything(SEED )
for i in range(len(result_fal)) :
if result_fal[i]<0:
result_fal[i] = 0
result_fal[i] = int(result_fal[i])
 result_fal[i] = int(result_fal[i] )<feature_engineering>
DIR_INPUT = '/kaggle/input/plant-pathology-2020-fgvc7'
train_df = pd.read_csv(DIR_INPUT + '/train.csv')
 test_df = pd.read_csv(DIR_INPUT + '/test.csv')
 cols = list(train_df.columns[1:] )
fal_pre = np.around(result_fal,decimals = 0 )<prepare_output>
train,valid = train_test_split(train_df,test_size = 0.2,random_state = SEED )
submission['ConfirmedCases'] = con_pred
submission['Fatalities'] = fal_pre<save_to_csv>
train_dataset =(tf.data.Dataset 
.from_tensor_slices(preprocess(train)) 
.map(decode_image, num_parallel_calls=AUTO)
.map(data_augment, num_parallel_calls=AUTO)
.shuffle(SEED)
.batch(BATCH_SIZE,drop_remainder=True)
.repeat() 
.prefetch(AUTO))
valid_dataset =(tf.data.Dataset 
.from_tensor_slices(preprocess(valid)) 
.map(decode_image, num_parallel_calls=AUTO)
.batch(BATCH_SIZE)
.cache() 
.prefetch(AUTO))
test_dataset =(tf.data.Dataset 
.from_tensor_slices(preprocess(test_df,test=True)) 
.map(decode_image, num_parallel_calls=AUTO)
.batch(BATCH_SIZE))
submission.to_csv("submission.csv" , index = False )<define_variables>
with strategy.scope() :
model = tf.keras.Sequential([
efn.EfficientNetB7(input_shape=(SIZE[0], SIZE[1], 3),weights='imagenet',pooling='avg',include_top=False),
Dense(4, activation='softmax')
 ])
 model.compile(
 optimizer='adam',
loss = 'categorical_crossentropy',
metrics=['categorical_accuracy'] )
embed_size = 300
max_features = 95000
maxlen = 70<import_modules>
def get_cosine_schedule_with_warmup(lr,num_warmup_steps, num_training_steps, num_cycles=0.5):

 def lrfn(epoch):
if epoch < num_warmup_steps:
return float(epoch)/ float(max(1, num_warmup_steps)) * lr
progress = float(epoch - num_warmup_steps)/ float(max(1, num_training_steps - num_warmup_steps))
return max(0.0, 0.5 *(1.0 + math.cos(math.pi * float(num_cycles)* 2.0 * progress)))* lr
return tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)
 lr_schedule= get_cosine_schedule_with_warmup(lr=LR,num_warmup_steps=WARMUP,num_training_steps=EPOCHS )
import os
import time
import numpy as np
import pandas as pd
from tqdm import tqdm
import math
from sklearn.model_selection import train_test_split
from sklearn import metrics
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Input, CuDNNLSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D
from keras.layers import Bidirectional, GlobalMaxPool1D, GlobalMaxPooling1D, GlobalAveragePooling1D
from keras.layers import Input, Embedding, Dense, Conv2D, MaxPool2D, concatenate, Lambda
from keras.layers import Reshape, Flatten, Concatenate, Dropout, SpatialDropout1D
from keras.optimizers import Adam
from keras.models import Model
from keras import backend as K
from keras.engine.topology import Layer
from keras import initializers, regularizers, constraints, optimizers, layers<load_from_csv>
STEPS_PER_EPOCH = train.shape[0] // BATCH_SIZE
@telegram_sender(token=token, chat_id=int(chat_id))
def train() :
history = model.fit(
 train_dataset,
epochs=EPOCHS,
callbacks=[lr_schedule],
steps_per_epoch=STEPS_PER_EPOCH,
validation_data=valid_dataset)
 string = 'Train acc:{:.4f} Train loss:{:.4f},Val acc:{:.4f} Val loss:{:.4f}'.format(\
model.history.history['categorical_accuracy'][-1],model.history.history['loss'][-1],\
model.history.history['val_categorical_accuracy'][-1],model.history.history['val_loss'][-1])
 return string
def load_and_prec() :
train_df = pd.read_csv(".. /input/train.csv")
 test_df = pd.read_csv(".. /input/test.csv")
 print("Train shape : ",train_df.shape)
 print("Test shape : ",test_df.shape)
 train_df, val_df = train_test_split(train_df, test_size=0.08, random_state=2018)
 train_X = train_df["question_text"].fillna("_
val_X = val_df["question_text"].fillna("_
test_X = test_df["question_text"].fillna("_
tokenizer = Tokenizer(num_words=max_features)
 tokenizer.fit_on_texts(list(train_X))
train_X = tokenizer.texts_to_sequences(train_X)
 val_X = tokenizer.texts_to_sequences(val_X)
 test_X = tokenizer.texts_to_sequences(test_X)
 train_X = pad_sequences(train_X, maxlen=maxlen)
 val_X = pad_sequences(val_X, maxlen=maxlen)
 test_X = pad_sequences(test_X, maxlen=maxlen)
 train_y = train_df['target'].values
val_y = val_df['target'].values
np.random.seed(2018)
 trn_idx = np.random.permutation(len(train_X))
val_idx = np.random.permutation(len(val_X))
train_X = train_X[trn_idx]
val_X = val_X[val_idx]
train_y = train_y[trn_idx]
val_y = val_y[val_idx]
return train_X, val_X, test_X, train_y, val_y, tokenizer.word_index<statistical_test>
train()
def load_glove(word_index):
EMBEDDING_FILE = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
 embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE))
all_embs = np.stack(embeddings_index.values())
 emb_mean,emb_std = all_embs.mean() , all_embs.std()
embed_size = all_embs.shape[1]
nb_words = min(max_features, len(word_index))
embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size))
for word, i in tqdm(word_index.items()):
if i >= max_features: continue
embedding_vector = embeddings_index.get(word)
 if embedding_vector is not None: embedding_matrix[i] = embedding_vector
return embedding_matrix
def load_fasttext(word_index):
EMBEDDING_FILE = '.. /input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
 embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)if len(o)>100)
 all_embs = np.stack(embeddings_index.values())
 emb_mean,emb_std = all_embs.mean() , all_embs.std()
embed_size = all_embs.shape[1]
nb_words = min(max_features, len(word_index))
embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size))
for word, i in tqdm(word_index.items()):
if i >= max_features: continue
embedding_vector = embeddings_index.get(word)
 if embedding_vector is not None: embedding_matrix[i] = embedding_vector
return embedding_matrix
def load_para(word_index):
EMBEDDING_FILE = '.. /input/embeddings/paragram_300_sl999/paragram_300_sl999.txt'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
 embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE, encoding="utf8", errors='ignore')if len(o)>100)
 all_embs = np.stack(embeddings_index.values())
 emb_mean,emb_std = all_embs.mean() , all_embs.std()
embed_size = all_embs.shape[1]
nb_words = min(max_features, len(word_index))
embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size))
for word, i in tqdm(word_index.items()):
if i >= max_features: continue
embedding_vector = embeddings_index.get(word)
 if embedding_vector is not None: embedding_matrix[i] = embedding_vector
return embedding_matrix<choose_model_class>
test_pred = model.predict(test_dataset, verbose=1)
 submission_df = pd.read_csv(DIR_INPUT + '/sample_submission.csv')
 submission_df[['healthy', 'multiple_diseases', 'rust', 'scab']] = test_pred
submission_df.to_csv('submission.csv', index=False)
 pd.Series(np.argmax(submission_df[cols].values,axis=1)).value_counts()
<choose_model_class><EOS> 
test_pred_tta = np.zeros(( len(test_df),4))
for i in range(TTA):
test_dataset_tta =(tf.data.Dataset 
.from_tensor_slices(preprocess(test_df,test=True)) 
.map(decode_image, num_parallel_calls=AUTO)
.map(data_augment, num_parallel_calls=AUTO)
.batch(BATCH_SIZE))
test_pred_tta += model.predict(test_dataset_tta, verbose=1)
 submission_df = pd.read_csv(DIR_INPUT + '/sample_submission.csv')
 submission_df[['healthy', 'multiple_diseases', 'rust', 'scab']] = test_pred_tta/TTA
submission_df.to_csv('submission_tta.csv', index=False)
 pd.Series(np.argmax(submission_df[cols].values,axis=1)).value_counts()