Kaggle competition: Gendered Pronoun Resolution
<SOS> metric: MulticlassLoss Kaggle data source: gendered-pronoun-resolution<save_to_csv>
!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
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities = model.predict(test_images_ds)
 predictions = np.argmax(probabilities, axis=-1)
 print(predictions)
 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='id,label', comments='')
 !head submission.csv<import_modules>
!pip install pytorch-pretrained-bert
!pip install https://github.com/ceshine/pytorch_helper_bot/archive/0.0.4.zip
import os 
<install_modules>
os.environ["SEED"] = "420"
!pip install -U --pre efficientnet<import_modules>
BERT_MODEL = 'bert-large-uncased'
CASED = False
print("Tensorflow version " + tf.__version__)
<set_options>
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], None
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
class Head(nn.Module):

 def __init__(self, bert_hidden_size: int, head_hidden_size:int = 3^6, num_blocks:int = 5):
super().__init__()
self.bert_hidden_size = bert_hidden_size
fca =([
nn.Linear(self.bert_hidden_size * 3, head_hidden_size),
nn.BatchNorm1d(head_hidden_size),
nn.ReLU() ,
])
 for block in range(num_blocks):
fca.append(nn.Linear(head_hidden_size, head_hidden_size))
fca.append(nn.BatchNorm1d(head_hidden_size))
fca.append(nn.ReLU())
 fca.append(nn.Linear(head_hidden_size, 3))
self.fc = nn.Sequential(*fca)
 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
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 = 'gs://kds-a44744780cb28b908f65e7fa3b4a473ef199bb9ffe8048dbbf29ffeb'
IMAGE_SIZE = [512, 512]
EPOCHS1=25
EPOCHS2=25
BATCH_SIZE = 1 * 16 * strategy.num_replicas_in_sync<randomize_order>
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("gap-development.tsv", delimiter="\t")
 sample_sub = pd.read_csv(".. /input/sample_submission_stage_1.csv")
 assert sample_sub.shape[0] == df_test.shape[0]
LR_START = 0.0001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 5
LR_EXP_DECAY =.8
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr = np.random.random_sample() * 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
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True )<groupby>
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 count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n )<define_variables>
train_ds = GAPDataset(df_train, tokenizer)
 val_ds = GAPDataset(df_val, tokenizer)
 test_ds = GAPDataset(df_test, tokenizer)
 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
)
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')
 SKIP_VALIDATION = False
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES<define_variables>
model = GAPModel(BERT_MODEL, torch.device("cuda:0"))
set_trainable(model.bert, False)
 set_trainable(model.head, True )
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>
lr=1e-4
weight_decay=5e-5
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
)
img_size=512
def random_blockout(img, sl=0.1, sh=0.2, rl=0.4):
h, w, c = img_size, img_size, 3
origin_area = tf.cast(h*w, tf.float32)
 e_size_l = tf.cast(tf.round(tf.sqrt(origin_area * sl * rl)) , tf.int32)
 e_size_h = tf.cast(tf.round(tf.sqrt(origin_area * sh / rl)) , tf.int32)
 e_height_h = tf.minimum(e_size_h, h)
 e_width_h = tf.minimum(e_size_h, w)
 erase_height = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_height_h, dtype=tf.int32)
 erase_width = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_width_h, dtype=tf.int32)
 erase_area = tf.zeros(shape=[erase_height, erase_width, c])
 erase_area = tf.cast(erase_area, tf.uint8)
 pad_h = h - erase_height
pad_top = tf.random.uniform(shape=[], minval=0, maxval=pad_h, dtype=tf.int32)
 pad_bottom = pad_h - pad_top
pad_w = w - erase_width
pad_left = tf.random.uniform(shape=[], minval=0, maxval=pad_w, dtype=tf.int32)
 pad_right = pad_w - pad_left
erase_mask = tf.pad([erase_area], [[0,0],[pad_top, pad_bottom], [pad_left, pad_right], [0,0]], constant_values=1)
 erase_mask = tf.squeeze(erase_mask, axis=0)
 erased_img = tf.multiply(tf.cast(img,tf.float32), tf.cast(erase_mask, tf.float32))
return tf.cast(erased_img, img.dtype )<categorify>
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=3, steps_per_cycle=n_steps)
 )
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)
 image= random_blockout(image)
 return image, label
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2345)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_training_dataset1() :
dataset = load_dataset(TRAINING_FILENAMES_1, labeled=True)
 dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2345)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_training_dataset2() :
dataset = load_dataset(TRAINING_FILENAMES_2, labeled=True)
 dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2345)
 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_validation_dataset1(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES_1, labeled=True, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset2(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES_2, 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 data_augment2(image, label):
image = tf.image.flip_left_right(image)
 return image, label
def get_test_dataset2(ordered=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)
 dataset = dataset.map(data_augment2, num_parallel_calls=AUTO)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset1a(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES_1, labeled=True, ordered=ordered)
 dataset = dataset.map(data_augment2, num_parallel_calls=AUTO)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset2a(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES_2, labeled=True, ordered=ordered)
 dataset = dataset.map(data_augment2, num_parallel_calls=AUTO)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset<choose_model_class>
bot.load_model(bot.best_performers[0][1] )
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(512, 512, 3),
weights=None,
include_top=False 
)
 model1 = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model1.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=[] 
)
 model1.load_weights('/kaggle/input/flower-class-tpu-efficientnet-training-v2/EfficientNetB7_validation2_35.h5')
<choose_model_class>
preds = bot.predict(test_loader )
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(512, 512, 3),
weights=None,
include_top=False 
)
 model1b = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model1b.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=[] 
)
 model1b.load_weights('/kaggle/input/flower-class-tpu-efficientnet-training-v3/EfficientNetB7_validation2_40.h5' )<choose_model_class>
from torch.autograd import Variable
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(512, 512, 3),
weights=None,
include_top=False 
)
 model11 = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model11.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=[] 
)
 model11.load_weights('/kaggle/input/flower-class-tpu-efficientnet-training-v2/EfficientNetB7_validation1_35.h5' )<choose_model_class>
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
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(512, 512, 3),
weights=None,
include_top=False 
)
 model11b = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model11b.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=[] 
)
 model11b.load_weights('/kaggle/input/flower-class-tpu-efficientnet-training-v3/EfficientNetB7_validation1_40.h5' )<choose_model_class>
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()