Kaggle competition: Gendered Pronoun Resolution
<SOS> metric: MulticlassLoss Kaggle data source: gendered-pronoun-resolution<install_modules>
!wget https://github.com/google-research-datasets/gap-coreference/raw/master/gap-development.tsv -q
!wget https://github.com/google-research-datasets/gap-coreference/raw/master/gap-test.tsv -q
!wget https://github.com/google-research-datasets/gap-coreference/raw/master/gap-validation.tsv -q
!pip install -q efficientnet<set_options>
!pip install pytorch-pretrained-bert
!pip install https://github.com/ceshine/pytorch_helper_bot/archive/0.0.4.zip
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<set_options>
os.environ["SEED"] = "420"
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 )<define_variables>
BERT_MODEL = 'bert-large-uncased'
CASED = False
GCS_DS_PATH = KaggleDatasets().get_gcs_path('flower-classification-with-tpus')
 MORE_IMAGES_GCS_DS_PATH = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec' )<define_variables>
def insert_tag(row):

 to_be_inserted = sorted([ 
(row["A-offset"], " [A] "), 
(row["B-offset"], " [B] "), 
(row["Pronoun-offset"], " [P] ")
 ], key=lambda x: x[0], reverse=True)
 text = row["Text"]
for offset, tag in to_be_inserted:
text = text[:offset] + tag + text[offset:]
return text
def tokenize(text, tokenizer):

 entries = {}
final_tokens = []
for token in tokenizer.tokenize(text):
if token in("[A]", "[B]", "[P]"):
entries[token] = len(final_tokens)
 continue
final_tokens.append(token)
 return final_tokens,(entries["[A]"], entries["[B]"], entries["[P]"])
 class GAPDataset(Dataset):

 def __init__(self, df, tokenizer, labeled=True):
self.labeled = labeled
if labeled:
tmp = df[["A-coref", "B-coref"]].copy()
tmp["Neither"] = ~(df["A-coref"] | df["B-coref"])
 self.y = tmp.values.astype("bool")
 self.offsets, self.tokens = [], []
for _, row in df.iterrows() :
text = insert_tag(row)
 tokens, offsets = tokenize(text, tokenizer)
 self.offsets.append(offsets)
 self.tokens.append(tokenizer.convert_tokens_to_ids(
 ["[CLS]"] + tokens + ["[SEP]"]))
def __len__(self):
return len(self.tokens)
 def __getitem__(self, idx):
if self.labeled:
return self.tokens[idx], self.offsets[idx], self.y[idx]
return self.tokens[idx], self.offsets[idx]
def collate_examples(batch, truncate_len=500):

 transposed = list(zip(*batch))
max_len = min(
 max(( len(x)for x in transposed[0])) ,
truncate_len 
)
 tokens = np.zeros(( len(batch), max_len), dtype=np.int64)
 for i, row in enumerate(transposed[0]):
row = np.array(row[:truncate_len])
 tokens[i, :len(row)] = row
token_tensor = torch.from_numpy(tokens)
 offsets = torch.stack([
torch.LongTensor(x)for x in transposed[1]
], dim=0)+ 1
if len(transposed)== 2:
return token_tensor, offsets, None
one_hot_labels = torch.stack([
torch.from_numpy(x.astype("uint8")) for x in transposed[2]
], dim=0)
 _, labels = one_hot_labels.max(dim=1)
 return token_tensor, offsets, labels
def collate_examples_no_labels(batch, truncate_len=500):

 transposed = list(zip(*batch))
print("transposed size is", transposed.size())
 max_len = min(
 max(( len(x)for x in transposed[0])) ,
truncate_len 
)
 tokens = np.zeros(( len(batch), max_len), dtype=np.int64)
 for i, row in enumerate(transposed[0]):
row = np.array(row[:truncate_len])
 tokens[i, :len(row)] = row
token_tensor = torch.from_numpy(tokens)
 offsets = torch.stack([
torch.LongTensor(x)for x in transposed[1]
], dim=0)+ 1
if len(transposed)== 2:
return token_tensor, offsets, None
one_hot_labels = torch.stack([
torch.from_numpy(x.astype("uint8")) for x in transposed[2]
], dim=0)
 _, labels = one_hot_labels.max(dim=1)
 return token_tensor, offsets, labels
class Head(nn.Module):

 def __init__(self, bert_hidden_size: int):
super().__init__()
self.head_hidden_size = 1024
self.bert_hidden_size = bert_hidden_size
self.fc = nn.Sequential(
 nn.BatchNorm1d(bert_hidden_size * 3),
nn.Dropout(0.5),
nn.Linear(bert_hidden_size * 3, self.head_hidden_size),
nn.ReLU() ,
nn.BatchNorm1d(self.head_hidden_size),
nn.Dropout(0.5),
nn.Linear(self.head_hidden_size, self.head_hidden_size),
nn.ReLU() ,
nn.BatchNorm1d(self.head_hidden_size),
nn.Dropout(0.5),
nn.Linear(self.head_hidden_size, self.head_hidden_size),
nn.ReLU() ,
nn.BatchNorm1d(self.head_hidden_size),
nn.Dropout(0.5),
nn.Linear(self.head_hidden_size, 3)
)
 for i, module in enumerate(self.fc):
if isinstance(module,(nn.BatchNorm1d, nn.BatchNorm2d)) :
nn.init.constant_(module.weight, 1)
 nn.init.constant_(module.bias, 0)
 print("Initing batchnorm")
 elif isinstance(module, nn.Linear):
if getattr(module, "weight_v", None)is not None:
nn.init.uniform_(module.weight_g, 0, 1)
 nn.init.kaiming_normal_(module.weight_v)
 print("Initing linear with weight normalization")
 assert model[i].weight_g is not None
else:
nn.init.kaiming_normal_(module.weight)
 print("Initing linear")
 nn.init.constant_(module.bias, 0)
 def forward(self, bert_outputs, offsets):
assert bert_outputs.size(2)== self.bert_hidden_size
extracted_outputs = bert_outputs.gather(
 1, offsets.unsqueeze(2 ).expand(-1, -1, bert_outputs.size(2))
).view(bert_outputs.size(0), -1)
 return self.fc(extracted_outputs)
 class GAPModel(nn.Module):

 def __init__(self, bert_model: str, device: torch.device):
super().__init__()
self.device = device
if bert_model in("bert-base-uncased", "bert-base-cased"):
self.bert_hidden_size = 768
elif bert_model in("bert-large-uncased", "bert-large-cased"):
self.bert_hidden_size = 1024
else:
raise ValueError("Unsupported BERT model.")
 self.bert = BertModel.from_pretrained(bert_model ).to(device)
 self.head = Head(self.bert_hidden_size ).to(device)
 def forward(self, token_tensor, offsets):
token_tensor = token_tensor.to(self.device)
 bert_outputs, _ = self.bert(
 token_tensor, attention_mask=(token_tensor > 0 ).long() ,
token_type_ids=None, output_all_encoded_layers=False)
 head_outputs = self.head(bert_outputs, offsets.to(self.device))
return head_outputs
def children(m):
return m if isinstance(m,(list, tuple)) else list(m.children())
 def set_trainable_attr(m, b):
m.trainable = b
for p in m.parameters() :
p.requires_grad = b
def apply_leaf(m, f):
c = children(m)
 if isinstance(m, nn.Module):
f(m)
 if len(c)> 0:
for l in c:
apply_leaf(l, f)
 def set_trainable(l, b):
apply_leaf(l, lambda m: set_trainable_attr(m, b))
class GAPBot(BaseBot):
def __init__(self, model, train_loader, val_loader, *, optimizer, clip_grad=0,
avg_window=100, log_dir="./cache/logs/", log_level=logging.INFO,
checkpoint_dir="./cache/model_cache/", batch_idx=0, echo=False,
device="cuda:0", use_tensorboard=False):
super().__init__(
 model, train_loader, val_loader,
optimizer=optimizer, clip_grad=clip_grad,
log_dir=log_dir, checkpoint_dir=checkpoint_dir,
batch_idx=batch_idx, echo=echo,
device=device, use_tensorboard=use_tensorboard 
)
 self.criterion = torch.nn.CrossEntropyLoss()
self.loss_format = "%.6f"
def extract_prediction(self, tensor):
return tensor
def snapshot(self):

 loss = self.eval(self.val_loader)
 loss_str = self.loss_format % loss
self.logger.info("Snapshot loss %s", loss_str)
 self.logger.tb_scalars(
 "losses", {"val": loss}, self.step)
 target_path =(
 self.checkpoint_dir / "best.pth")
 if not self.best_performers or(self.best_performers[0][0] > loss):
torch.save(self.model.state_dict() , target_path)
 self.best_performers = [(loss, target_path, self.step)]
self.logger.info("Saving checkpoint %s...", target_path)
 else:
new_loss_str = self.loss_format % self.best_performers[0][0]
self.logger.info("This performance:%s is not as a good as our previously saved:%s", loss_str,new_loss_str)
 assert Path(target_path ).exists()
return loss
IMAGE_SIZE = [512, 512]
EPOCHS = 100
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
GCS_PATH_SELECT = {
192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',
224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',
331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',
512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'
}
GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 MOREIMAGES_PATH_SELECT = {
192: '/tfrecords-jpeg-192x192',
224: '/tfrecords-jpeg-224x224',
331: '/tfrecords-jpeg-331x331',
512: '/tfrecords-jpeg-512x512'
}
MOREIMAGES_PATH = MOREIMAGES_PATH_SELECT[IMAGE_SIZE[0]]
IMAGENET_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/imagenet' + MOREIMAGES_PATH + '/*.tfrec')
 INATURELIST_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/inaturalist' + MOREIMAGES_PATH + '/*.tfrec')
 OPENIMAGE_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/openimage' + MOREIMAGES_PATH + '/*.tfrec')
 OXFORD_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/oxford_102' + MOREIMAGES_PATH + '/*.tfrec')
 TENSORFLOW_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/tf_flowers' + MOREIMAGES_PATH + '/*.tfrec')
 ADDITIONAL_TRAINING_FILENAMES = IMAGENET_FILES + INATURELIST_FILES + OPENIMAGE_FILES + OXFORD_FILES + TENSORFLOW_FILES
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES + ADDITIONAL_TRAINING_FILENAMES
CLASSES = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle',
'snapdragon', "colt's foot", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', 'balloon flower', 'giant white arum lily',
'fire lily', 'pincushion flower', 'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', 'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william',
'carnation', 'garden phlox', 'love in the mist', 'cosmos', 'alpine sea holly', 'ruby-lipped cattleya', 'cape flower', 'great masterwort', 'siam tulip', 'lenten rose',
'barberton daisy', 'daffodil', 'sword lily', 'poinsettia', 'bolero deep blue', 'wallflower', 'marigold', 'buttercup', 'daisy', 'common dandelion',
'petunia', 'wild pansy', 'primula', 'sunflower', 'lilac hibiscus', 'bishop of llandaff', 'gaura', 'geranium', 'orange dahlia', 'pink-yellow dahlia',
'cautleya spicata', 'japanese anemone', 'black-eyed susan', 'silverbush', 'californian poppy', 'osteospermum', 'spring crocus', 'iris', 'windflower', 'tree poppy',
'gazania', 'azalea', 'water lily', 'rose', 'thorn apple', 'morning glory', 'passion flower', 'lotus', 'toad lily', 'anthurium',
'frangipani', 'clematis', 'hibiscus', 'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', 'watercress', 'canna lily',
'hippeastrum ', 'bee balm', 'pink quill', 'foxglove', 'bougainvillea', 'camellia', 'mallow', 'mexican petunia', 'bromelia', 'blanket flower',
'trumpet creeper', 'blackberry lily', 'common tulip', 'wild rose']<categorify>
df_train = pd.read_csv("gap-test.tsv", delimiter="\t")
 df_val = pd.read_csv("gap-validation.tsv", delimiter="\t")
 df_test = pd.read_csv(".. /input/test_stage_2.tsv", delimiter="\t")
 sample_sub = pd.read_csv(".. /input/sample_submission_stage_2.csv")
 assert sample_sub.shape[0] == df_test.shape[0]
np.set_printoptions(threshold=15, linewidth=80)
 def batch_to_numpy_images_and_labels(data):
images, labels = data
numpy_images = images.numpy()
numpy_labels = labels.numpy()
if numpy_labels.dtype == object:
numpy_labels = [None for _ in enumerate(numpy_images)]
return numpy_images, numpy_labels
def title_from_label_and_target(label, correct_label):
if correct_label is None:
return CLASSES[label], True
correct =(label == correct_label)
 return "{} [{}{}{}]".format(CLASSES[label], 'OK' if correct else 'NO', u"\u2192" if not correct else '',
CLASSES[correct_label] if not correct else ''), correct
def display_one_flower(image, title, subplot, red=False, titlesize=16):
plt.subplot(*subplot)
 plt.axis('off')
 plt.imshow(image)
 if len(title)> 0:
plt.title(title, fontsize=int(titlesize)if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))
return(subplot[0], subplot[1], subplot[2]+1)
 def display_batch_of_images(databatch, predictions=None):

 images, labels = batch_to_numpy_images_and_labels(databatch)
 if labels is None:
labels = [None for _ in enumerate(images)]
rows = int(math.sqrt(len(images)))
 cols = len(images)//rows
FIGSIZE = 13.0
SPACING = 0.1
subplot=(rows,cols,1)
 if rows < cols:
plt.figure(figsize=(FIGSIZE,FIGSIZE/cols*rows))
else:
plt.figure(figsize=(FIGSIZE/rows*cols,FIGSIZE))
for i,(image, label)in enumerate(zip(images[:rows*cols], labels[:rows*cols])) :
title = '' if label is None else CLASSES[label]
correct = True
if predictions is not None:
title, correct = title_from_label_and_target(predictions[i], label)
 dynamic_titlesize = FIGSIZE*SPACING/max(rows,cols)*40+3
subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)
 plt.tight_layout()
if label is None and predictions is None:
plt.subplots_adjust(wspace=0, hspace=0)
 else:
plt.subplots_adjust(wspace=SPACING, hspace=SPACING)
 plt.show()
def display_confusion_matrix(cmat, score, precision, recall):
plt.figure(figsize=(15,15))
ax = plt.gca()
ax.matshow(cmat, cmap='Reds')
 ax.set_xticks(range(len(CLASSES)))
 ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7})
 plt.setp(ax.get_xticklabels() , rotation=45, ha="left", rotation_mode="anchor")
 ax.set_yticks(range(len(CLASSES)))
 ax.set_yticklabels(CLASSES, fontdict={'fontsize': 7})
 plt.setp(ax.get_yticklabels() , rotation=45, ha="right", rotation_mode="anchor")
 titlestring = ""
if score is not None:
titlestring += 'f1 = {:.3f} '.format(score)
 if precision is not None:
titlestring += '
precision = {:.3f} '.format(precision)
 if recall is not None:
titlestring += '
recall = {:.3f} '.format(recall)
 if len(titlestring)> 0:
ax.text(101, 1, titlestring, fontdict={'fontsize': 18, 'horizontalalignment':'right', 'verticalalignment':'top', 'color':'
plt.show()
def display_training_curves(training, validation, title, subplot):
if subplot%10==1:
plt.subplots(figsize=(10,10), facecolor='
plt.tight_layout()
ax = plt.subplot(subplot)
 ax.set_facecolor('
ax.plot(training)
 ax.plot(validation)
 ax.set_title('model '+ title)
 ax.set_ylabel(title)
 ax.set_xlabel('epoch')
 ax.legend(['train', 'valid.'] )<categorify>
tokenizer = BertTokenizer.from_pretrained(
 BERT_MODEL,
do_lower_case=CASED,
never_split =("[UNK]", "[SEP]", "[PAD]", "[CLS]", "[MASK]", "[A]", "[B]", "[P]")
)
 tokenizer.vocab["[A]"] = -1
tokenizer.vocab["[B]"] = -1
tokenizer.vocab["[P]"] = -1
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 read_labeled_tfrecord(example):
LABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_unlabeled_tfrecord(example):
UNLABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 idnum = example['id']
return image, idnum
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=AUTO)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 return image, label
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_test_dataset(ordered=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
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 = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))<train_model>
train_ds = GAPDataset(df_train, tokenizer)
 val_ds = GAPDataset(df_val, tokenizer)
 test_ds = GAPDataset(df_test, tokenizer, labeled=False)
 train_loader = DataLoader(
 train_ds,
collate_fn = collate_examples,
batch_size=20,
num_workers=2,
pin_memory=True,
shuffle=True,
drop_last=True 
)
 val_loader = DataLoader(
 val_ds,
collate_fn = collate_examples,
batch_size=128,
num_workers=2,
pin_memory=True,
shuffle=False 
)
 test_loader = DataLoader(
 test_ds,
collate_fn = collate_examples,
batch_size=128,
num_workers=2,
pin_memory=True,
shuffle=False
)
print("Training data shapes:")
 for image, label in get_training_dataset().take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Training data label examples:", label.numpy())
 print("Validation data shapes:")
 for image, label in get_validation_dataset().take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Validation data label examples:", label.numpy())
 print("Test data shapes:")
 for image, idnum in get_test_dataset().take(3):
print(image.numpy().shape, idnum.numpy().shape)
 print("Test data IDs:", idnum.numpy().astype('U'))<train_model>
model = GAPModel(BERT_MODEL, torch.device("cuda:0"))
set_trainable(model.bert, False)
 set_trainable(model.head, True )
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )<define_variables>
lr=1e-3
weight_decay=5e-3
optimizer = torch.optim.Adam(model.parameters() , lr=lr, weight_decay=weight_decay)
 bot = GAPBot(
 model, train_loader, val_loader,
optimizer=optimizer, echo=True,
avg_window=25
)
display_batch_of_images(next(train_batch))<define_variables>
steps_per_epoch = len(train_loader)
 n_steps = steps_per_epoch * 27
bot.train(
 n_steps,
log_interval=steps_per_epoch // 4,
snapshot_interval=steps_per_epoch,
scheduler=TriangularLR(
 optimizer, 20, ratio=2, steps_per_cycle=n_steps)
 )
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )<define_variables>
bot.load_model(bot.best_performers[0][1] )
display_batch_of_images(next(test_batch))<init_hyperparams>
def predict(loader, *, return_y=False):
model.eval()
outputs, y_global = [], []
with torch.set_grad_enabled(False):
for input_tensors in loader:
input_tensors = [x.to(model.device)for x in input_tensors if x is not None]
outputs.append(bot.predict_batch(input_tensors ).cpu())
 outputs = torch.cat(outputs, dim=0)
 return outputs
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY =.8
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr =(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS * epoch + LR_START
elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:
lr = LR_MAX
else:
lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr
def lrfn1(epoch):
return LR_START
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)
 rng = [i for i in range(25 if EPOCHS<25 else EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))<choose_model_class>
preds = predict(test_loader )
lr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn1, verbose=True)
 early_stop=tf.keras.callbacks.EarlyStopping(patience=4)
 check=tf.keras.callbacks.ModelCheckpoint(
 'model.{epoch:02d}-{val_loss:.2f}.h5',
monitor="val_loss",
verbose=0,
save_best_only=True,
save_weights_only=False,
mode="auto",
save_freq="epoch",
)<choose_model_class>
from torch.autograd import Variable
with strategy.scope() :
pretrained_model = tf.keras.applications.InceptionResNetV2(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])
 pretrained_model.trainable = True


model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.Dropout(0.2),
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 optimizer='adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model.summary()<train_model>
def exx(row):
if(row.A > row.B and row.A > row.NEITHER):
row.A = 1
row.B = 0
row.NEITHER = 0
elif(row.B > row.A and row.B > row.NEITHER):
row.A = 0
row.B = 1
row.NEITHER = 0
else:
row.A = 0
row.B = 0
row.NEITHER = 1
return row
<save_model><EOS> 
df_sub = pd.DataFrame(torch.softmax(preds, -1 ).cpu().numpy().clip(1e-3, 1-1e-3), columns=["A", "B", "NEITHER"])
 df_sub["ID"] = df_test.ID
df_sub.to_csv("submission.csv", index=False)
 df_sub.head()