Kaggle competition: Gendered Pronoun Resolution
with strategy.scope() :
rnet = DenseNet201(
 input_shape=(512, 512, 3),
weights=None,
include_top=False 
)
 model2 = tf.keras.Sequential([
rnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model2.compile(
 optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False),
loss = 'sparse_categorical_crossentropy',
metrics=[] 
)
 model2.load_weights('/kaggle/input/flower-class-tpu-densenet-training-v2/DenseNet201_validation2_35.h5')
<choose_model_class>
!wget https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip
with zipfile.ZipFile("uncased_L-12_H-768_A-12.zip","r")as zip_ref:
zip_ref.extractall()
!ls 'uncased_L-12_H-768_A-12'
with strategy.scope() :
rnet = DenseNet201(
 input_shape=(512, 512, 3),
weights=None,
include_top=False 
)
 model2b = tf.keras.Sequential([
rnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model2b.compile(
 optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False),
loss = 'sparse_categorical_crossentropy',
metrics=[] 
)
 model2b.load_weights('/kaggle/input/flower-class-tpu-densenet-training-v3/DenseNet201_validation2_50.h5' )<choose_model_class>
!wget https://raw.githubusercontent.com/google-research/bert/master/modeling.py
!wget https://raw.githubusercontent.com/google-research/bert/master/extract_features.py
!wget https://raw.githubusercontent.com/google-research/bert/master/tokenization.py
with strategy.scope() :
rnet = DenseNet201(
 input_shape=(512, 512, 3),
weights=None,
include_top=False 
)
 model22 = tf.keras.Sequential([
rnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model22.compile(
 optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False),
loss = 'sparse_categorical_crossentropy',
metrics=[] 
)
 model22.load_weights('/kaggle/input/flower-class-tpu-densenet-training-v2/DenseNet201_validation1_35.h5' )<choose_model_class>
nlp = spacy.load('en_core_web_lg' )
with strategy.scope() :
rnet = DenseNet201(
 input_shape=(512, 512, 3),
weights=None,
include_top=False 
)
 model22b = tf.keras.Sequential([
rnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model22b.compile(
 optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False),
loss = 'sparse_categorical_crossentropy',
metrics=[] 
)
 model22b.load_weights('/kaggle/input/flower-class-tpu-densenet-training-v3/DenseNet201_validation1_50.h5' )<import_modules>
test_df = pd.read_table('.. /input/gap-coreference/gap-development.tsv')
 train_df = pd.read_table('.. /input/gap-coreference/gap-test.tsv')
 val_df = pd.read_table('.. /input/gap-coreference/gap-validation.tsv')
 test_df.head()
from scipy.special import logit, expit
import pandas as pd<categorify>
test_dist_df = extract_dist_features(test_df)
 test_dist_df.to_csv('test_dist_df.csv', index=False)
 val_dist_df = extract_dist_features(val_df)
 val_dist_df.to_csv('val_dist_df.csv', index=False)
 train_dist_df = extract_dist_features(train_df)
 train_dist_df.to_csv('train_dist_df.csv', index=False )
SKIP_VALIDATION = False
if not SKIP_VALIDATION:
cmdataset1 = get_validation_dataset1(ordered=True)
 cmdataset2 = get_validation_dataset2(ordered=True)
 images_ds1 = cmdataset1.map(lambda image, label: image)
 images_ds2 = cmdataset2.map(lambda image, label: image)
 labels_ds1 = cmdataset1.map(lambda image, label: label ).unbatch()
labels_ds2 = cmdataset2.map(lambda image, label: label ).unbatch()
cm_correct_labels1 = next(iter(labels_ds1.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_correct_labels2 = next(iter(labels_ds2.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_correct_labels = np.concatenate(( cm_correct_labels1,cm_correct_labels2),axis=0)
 valid_1 = model11.predict(images_ds1)
 valid_2 = model1.predict(images_ds2)
 m = np.concatenate(( valid_1,valid_2),axis=0)
 valid_1 = model22.predict(images_ds1)
 valid_2 = model2.predict(images_ds2)
 m2 = np.concatenate(( valid_1,valid_2),axis=0)
 for i in range(104):
m[:,i] = np.nan_to_num(logit(m[:,i]))
m2[:,i] = np.nan_to_num(logit(m2[:,i]))
valid_1 = model11b.predict(images_ds1)
 valid_2 = model1b.predict(images_ds2)
 mb = np.concatenate(( valid_1,valid_2),axis=0)
 valid_1 = model22b.predict(images_ds1)
 valid_2 = model2b.predict(images_ds2)
 m2b = np.concatenate(( valid_1,valid_2),axis=0)
 for i in range(104):
mb[:,i] = np.nan_to_num(logit(mb[:,i]))
m2b[:,i] = np.nan_to_num(logit(m2b[:,i]))
m = 0.5*m+0.5*mb
m2 = 0.5*m2+0.5*m2b
del mb,m2b
alpha_best = 0
score_best = 0
for alpha in np.linspace(0,1,101):
alpha = np.round(alpha,2)
 cm_probabilities = alpha*m+(1-alpha)*m2
if alpha == 0:
probabilities = cm_probabilities
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 auxi = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 print('alpha:',alpha,'--- f1_score:',auxi)
 if auxi > score_best:
score_best = auxi
alpha_best = alpha
probabilities = cm_probabilities
best_score1 = score_best
best_alpha1 = alpha_best
cm_probabilities1 = probabilities
else:
best_alpha1 = 0.50<categorify>
def count_char(text, offset):
count = 0
for pos in range(offset):
if text[pos] != " ": count +=1
return count
def candidate_length(candidate):
count = 0
for i in range(len(candidate)) :
if candidate[i] != " ": count += 1
return count
def count_token_length_special(token):
count = 0
special_token = ["
for i in range(len(token)) :
if token[i] not in special_token: count+=1
return count
def embed_by_bert(df):
text = df['Text']
text.to_csv('input.txt', index=False, header=False)
 os.system("python3 extract_features.py \
--input_file=input.txt \
--output_file=output.jsonl \
--vocab_file=uncased_L-12_H-768_A-12/vocab.txt \
--bert_config_file=uncased_L-12_H-768_A-12/bert_config.json \
--init_checkpoint=uncased_L-12_H-768_A-12/bert_model.ckpt \
--layers=-1 \
--max_seq_length=256 \
--batch_size=8")
 bert_output = pd.read_json("output.jsonl", lines = True)
 bert_output.head()
os.system("rm input.txt")
 os.system("rm output.jsonl")
 index = df.index
columns = ["emb_A", "emb_B", "emb_P", "label"]
emb = pd.DataFrame(index = index, columns = columns)
 emb.index.name = "ID"
for i in tqdm(range(len(text))):
features = bert_output.loc[i, "features"]
P_char_start = count_char(df.loc[i, 'Text'], df.loc[i, 'Pronoun-offset'])
 A_char_start = count_char(df.loc[i, 'Text'], df.loc[i, 'A-offset'])
 B_char_start = count_char(df.loc[i, 'Text'], df.loc[i, 'B-offset'])
 A_length = candidate_length(df.loc[i, 'A'])
 B_length = candidate_length(df.loc[i, 'B'])
 emb_A = np.zeros(768)
 emb_B = np.zeros(768)
 emb_P = np.zeros(768)
 char_count = 0
cnt_A, cnt_B = 0, 0
for j in range(2, len(features)) :
token = features[j]["token"]
token_length = count_token_length_special(token)
 if char_count == P_char_start:
emb_P += np.asarray(features[j]["layers"][0]['values'])
 if char_count in range(A_char_start, A_char_start+A_length):
emb_A += np.asarray(features[j]["layers"][0]['values'])
 cnt_A += 1
if char_count in range(B_char_start, B_char_start+B_length):
emb_B += np.asarray(features[j]["layers"][0]['values'])
 cnt_B += 1
char_count += token_length
emb_A /= cnt_A
emb_B /= cnt_B
label = "Neither"
if(df.loc[i,"A-coref"] == True):
label = "A"
if(df.loc[i,"B-coref"] == True):
label = "B"
emb.iloc[i] = [emb_A, emb_B, emb_P, label]
return emb
if not SKIP_VALIDATION:
cmdataset1 = get_validation_dataset1a(ordered=True)
 cmdataset2 = get_validation_dataset2a(ordered=True)
 images_ds1 = cmdataset1.map(lambda image, label: image)
 images_ds2 = cmdataset2.map(lambda image, label: image)
 labels_ds1 = cmdataset1.map(lambda image, label: label ).unbatch()
labels_ds2 = cmdataset2.map(lambda image, label: label ).unbatch()
cm_correct_labels1 = next(iter(labels_ds1.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_correct_labels2 = next(iter(labels_ds2.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_correct_labels = np.concatenate(( cm_correct_labels1,cm_correct_labels2),axis=0)
 valid_1 = model11.predict(images_ds1)
 valid_2 = model1.predict(images_ds2)
 mm = np.concatenate(( valid_1,valid_2),axis=0)
 valid_1 = model22.predict(images_ds1)
 valid_2 = model2.predict(images_ds2)
 mm2 = np.concatenate(( valid_1,valid_2),axis=0)
 for i in range(104):
mm[:,i] = np.nan_to_num(logit(mm[:,i]))
mm2[:,i] = np.nan_to_num(logit(mm2[:,i]))
valid_1 = model11b.predict(images_ds1)
 valid_2 = model1b.predict(images_ds2)
 mmb = np.concatenate(( valid_1,valid_2),axis=0)
 valid_1 = model22b.predict(images_ds1)
 valid_2 = model2b.predict(images_ds2)
 mm2b = np.concatenate(( valid_1,valid_2),axis=0)
 for i in range(104):
mmb[:,i] = np.nan_to_num(logit(mmb[:,i]))
mm2b[:,i] = np.nan_to_num(logit(mm2b[:,i]))
mm = 0.5*mm+0.5*mmb
mm2 = 0.5*mm2+0.5*mm2b
del mmb,mm2b
alpha_best = 0
score_best = 0
for alpha in np.linspace(0,1,101):
alpha = np.round(alpha,2)
 cm_probabilities = alpha*mm+(1-alpha)*mm2
if alpha == 0:
probabilities = cm_probabilities
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 auxi = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 print('alpha:',alpha,'--- f1_score:',auxi)
 if auxi > score_best:
score_best = auxi
alpha_best = alpha
probabilities = cm_probabilities
best_score2 = score_best
best_alpha2 = alpha_best
cm_probabilities2 = probabilities
else:
best_alpha2 = 0.50<find_best_params>
test_emb = embed_by_bert(test_df)
 test_emb.to_json("contextual_embeddings_gap_test.json", orient = 'columns')
 validation_emb = embed_by_bert(val_df)
 validation_emb.to_json("contextual_embeddings_gap_validation.json", orient = 'columns')
 train_emb = embed_by_bert(train_df)
 train_emb.to_json("contextual_embeddings_gap_train.json", orient = 'columns' )
if not SKIP_VALIDATION:
alpha_best = 0
score_best = 0
for alpha in np.linspace(0,1,101):
alpha = np.round(alpha,2)
 cm_probabilities = alpha*cm_probabilities1+(1-alpha)*cm_probabilities2
if alpha == 0:
probabilities = cm_probabilities
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 auxi = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 print('alpha:',alpha,'--- f1_score:',auxi)
 if auxi > score_best:
score_best = auxi
alpha_best = alpha
probabilities = cm_probabilities
best_score3 = score_best
best_alpha3 = alpha_best
cm_probabilities3 = probabilities
else:
best_alpha3 = 0.5<predict_on_test>
class End2End_NCR() :
def __init__(self, word_input_shape, dist_shape, embed_dim=20):
self.word_input_shape = word_input_shape
self.dist_shape = dist_shape
self.embed_dim = embed_dim
self.buckets = [1, 2, 3, 4, 5, 8, 16, 32, 64]
self.hidden_dim = 150
def build(self):
A, B, P = Input(( self.word_input_shape,)) , Input(( self.word_input_shape,)) , Input(( self.word_input_shape,))
dist1, dist2 = Input(( self.dist_shape,)) , Input(( self.dist_shape,))
inputs = [A, B, P]
dist_inputs = [dist1, dist2]
self.dist_embed = Embedding(len(self.buckets)+1, self.embed_dim)
 self.ffnn = Sequential([Dense(self.hidden_dim, use_bias=True),
Activation('relu'),
Dropout(rate=0.2, seed = 7),
Dense(1, activation='linear')])
 dist_embeds = [self.dist_embed(dist)for dist in dist_inputs]
dist_embeds = [Flatten()(dist_embed)for dist_embed in dist_embeds]
PA = Multiply()([inputs[0], inputs[2]])
 PB = Multiply()([inputs[1], inputs[2]])
 PA = Concatenate(axis=-1 )([P, A, PA, dist_embeds[0]])
 PB = Concatenate(axis=-1 )([P, B, PB, dist_embeds[1]])
 PA_score = self.ffnn(PA)
 PB_score = self.ffnn(PB)
 score_e = Lambda(lambda x: K.zeros_like(x))(PB_score)
 output = Concatenate(axis=-1 )([PA_score, PB_score, score_e])
 output = Activation('softmax' )(output)
 model = Model(inputs+dist_inputs, output)
 return model
test_ds = get_test_dataset(ordered=True)
 test_ds2 = get_test_dataset2(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 test_images_ds2 = test_ds2.map(lambda image, idnum: image)
 m1 = model1.predict(test_images_ds)
 m11 = model11.predict(test_images_ds)
 m1b = model1b.predict(test_images_ds)
 m11b = model11b.predict(test_images_ds)
 m2 = model2.predict(test_images_ds)
 m22 = model22.predict(test_images_ds)
 m2b = model2b.predict(test_images_ds)
 m22b = model22b.predict(test_images_ds)
 for i in range(104):
m1[:,i] = np.nan_to_num(logit(m1[:,i]))
m11[:,i] = np.nan_to_num(logit(m11[:,i]))
m1b[:,i] = np.nan_to_num(logit(m1b[:,i]))
m11b[:,i] = np.nan_to_num(logit(m11b[:,i]))
m2[:,i] = np.nan_to_num(logit(m2[:,i]))
m22[:,i] = np.nan_to_num(logit(m22[:,i]))
m2b[:,i] = np.nan_to_num(logit(m2b[:,i]))
m22b[:,i] = np.nan_to_num(logit(m22b[:,i]))
m1 = 0.25*m1+0.25*m11+0.25*m1b+0.25*m11b
m2 = 0.25*m2+0.25*m22+0.25*m2b+0.25*m22b
del m11,m22,m1b,m2b,m11b,m22b
cm_probabilities1 = best_alpha1*m1+(1-best_alpha1)*m2
m1 = model1.predict(test_images_ds2)
 m11 = model11.predict(test_images_ds2)
 m1b = model1b.predict(test_images_ds2)
 m11b = model11b.predict(test_images_ds2)
 m2 = model2.predict(test_images_ds2)
 m22 = model22.predict(test_images_ds2)
 m2b = model2b.predict(test_images_ds2)
 m22b = model22b.predict(test_images_ds2)
 for i in range(104):
m1[:,i] = np.nan_to_num(logit(m1[:,i]))
m11[:,i] = np.nan_to_num(logit(m11[:,i]))
m1b[:,i] = np.nan_to_num(logit(m1b[:,i]))
m11b[:,i] = np.nan_to_num(logit(m11b[:,i]))
m2[:,i] = np.nan_to_num(logit(m2[:,i]))
m22[:,i] = np.nan_to_num(logit(m22[:,i]))
m2b[:,i] = np.nan_to_num(logit(m2b[:,i]))
m22b[:,i] = np.nan_to_num(logit(m22b[:,i]))
m1 = 0.25*m1+0.25*m11+0.25*m1b+0.25*m11b
m2 = 0.25*m2+0.25*m22+0.25*m2b+0.25*m22b
del m11,m22,m1b,m2b,m11b,m22b
cm_probabilities2 = best_alpha2*m1+(1-best_alpha2)*m2
cm_probabilities3 = best_alpha3*cm_probabilities1+(1-best_alpha3)*cm_probabilities2
predictions = np.argmax(cm_probabilities3, axis=-1)
 print(predictions)
 for i in range(104):
cm_probabilities3[:,i] = expit(cm_probabilities3[:,i])
 pd.DataFrame(cm_probabilities3 ).to_csv('probabilities.csv', index=False)
 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='' )<import_modules>
def create_input(embed_df, dist_df):
assert len(embed_df)== len(dist_df)
 all_P, all_A, all_B = [] ,[] ,[]
all_label = []
all_dist_PA, all_dist_PB = [], []
url_A, url_B = [], []
for i in tqdm(range(len(embed_df))):
all_P.append(embed_df.loc[i, "emb_P"])
 all_A.append(embed_df.loc[i, "emb_A"])
 all_B.append(embed_df.loc[i, "emb_B"])
 all_dist_PA.append(dist_df.loc[i, "D_PA"])
 all_dist_PB.append(dist_df.loc[i, "D_PB"])
 if dist_df.loc[i, "IN_URL"] == 0:
url_A.append(1)
 url_B.append(0)
 elif dist_df.loc[i, "IN_URL"] == 1:
url_A.append(0)
 url_B.append(1)
 else:
url_A.append(0)
 url_B.append(0)
 label = embed_df.loc[i, "label"]
if label == "A":
all_label.append(0)
 elif label == "B":
all_label.append(1)
 else:
all_label.append(2)
 return [np.asarray(all_A), np.asarray(all_B), np.asarray(all_P),
np.expand_dims(np.asarray(all_dist_PA),axis=1),
np.expand_dims(np.asarray(all_dist_PB),axis=1)],all_label
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<set_options>
new_emb_df = pd.concat([train_emb, validation_emb])
 new_emb_df = new_emb_df.reset_index(drop=True)
 new_dist_df = pd.concat([train_dist_df, val_dist_df])
 new_dist_df = new_dist_df.reset_index(drop=True)
 new_emb_df.head()
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>
X_train, y_train = create_input(new_emb_df, new_dist_df)
 X_test, y_test = create_input(test_emb, test_dist_df )
GCS_DS_PATH = KaggleDatasets().get_gcs_path()<define_variables>
model = End2End_NCR(word_input_shape=X_train[0].shape[1], dist_shape=X_train[3].shape[1] ).build()
model.summary()
IMAGE_SIZE = [512, 512]
EPOCHS = 20
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')
 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>
min_loss = 1.0
best_model = 0
n_fold = 5
kfold = KFold(n_splits=n_fold, shuffle=True, random_state=3)
 for fold_n,(train_index, valid_index)in enumerate(kfold.split(X_train[0])) :
X_tr = [inputs[train_index] for inputs in X_train]
X_val = [inputs[valid_index] for inputs in X_train]
y_tr = np.asarray(y_train)[train_index]
y_val = np.asarray(y_train)[valid_index]
model = End2End_NCR(word_input_shape=X_train[0].shape[1], dist_shape=X_train[3].shape[1] ).build()
model.compile(optimizer=optimizers.Adam(lr=0.001), loss="sparse_categorical_crossentropy")
 file_path = "best_model_{}.hdf5".format(fold_n+1)
 check_point = callbacks.ModelCheckpoint(file_path, monitor = "val_loss", verbose = 0, save_best_only = True, mode = "min")
 early_stop = callbacks.EarlyStopping(monitor = "val_loss", mode = "min", patience=100)
 hist = model.fit(X_tr, y_tr, batch_size=128, epochs=1000, validation_data=(X_val, y_val), verbose=0,
shuffle=True, callbacks = [check_point, early_stop])
 if min(hist.history['val_loss'])< min_loss:
min_loss = min(hist.history['val_loss'])
 best_model = fold_n + 1
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>
del model
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.one_hot(example['class'], 104)
 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 = tf.image.random_hue(image, 0.05)
 image = tf.image.random_contrast(image, 0.5, 1.5)
 image = tf.image.random_brightness(image, 0.25)
 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>
model = End2End_NCR(word_input_shape=X_train[0].shape[1], dist_shape=X_train[3].shape[1] ).build()
model.load_weights("./best_model_{}.hdf5".format(best_model))
pred = model.predict(x = X_test, verbose = 0)
 sub_df_path = os.path.join('.. /input/gendered-pronoun-resolution/', 'sample_submission_stage_1.csv')
 sub_df = pd.read_csv(sub_df_path)
 sub_df.loc[:, 'A'] = pd.Series(pred[:, 0])
 sub_df.loc[:, 'B'] = pd.Series(pred[:, 1])
 sub_df.loc[:, 'NEITHER'] = pd.Series(pred[:, 2])
 sub_df.head(20 )
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'))<define_variables>
y_one_hot = np.zeros(( 2000, 3))
for i in range(len(y_test)) :
y_one_hot[i, y_test[i]] = 1
log_loss(y_one_hot, pred )
<define_variables><EOS> 
sub_df.to_csv("submission.csv", index=False )