Kaggle competition: Gendered Pronoun Resolution
def sigmoid_np(x):
return 1.0/(1.0 + np.exp(-x))
def F1_soft(preds,targs,th=0.0,d=25.0):
preds = sigmoid_np(d*(preds - th))
targs = targs.astype(np.float)
 score = 2.0*(preds*targs ).sum(axis=0)/(( preds+targs ).sum(axis=0)+ 1e-6)
 return score
def fit_val(x,y):
params = np.zeros(len(name_label_dict))
wd = 1e-5
error = lambda p: np.concatenate(( F1_soft(x,y,p)- 1.0,
wd*p), axis=None)
 p, success = opt.leastsq(error, params)
 return p<compute_test_metric>
test_stage_1 = pd.read_csv(".. /input/test_stage_1.tsv", sep="\t")
 test_stage_2 = pd.read_csv(".. /input/test_stage_2.tsv", sep="\t" )
th = fit_val(pred,y)
 print('Thresholds: ',th)
 print('F1 macro: ',f1_score(y, pred>th, average='macro'))
print('F1 macro(th = 0.0): ',f1_score(y, pred>0.0, average='macro'))
print('F1 micro: ',f1_score(y, pred>th, average='micro'))<split>
gap_test = pd.read_csv("https://raw.githubusercontent.com/google-research-datasets/gap-coreference/master/gap-test.tsv", delimiter='\t')
 gap_valid = pd.read_csv("https://raw.githubusercontent.com/google-research-datasets/gap-coreference/master/gap-validation.tsv", delimiter='\t' )
th, score, cv = 0,0,10
for i in range(cv):
xt,xv,yt,yv = train_test_split(pred,y,test_size=0.5,random_state=i)
 th_i = fit_val(xt,yt)
 th += th_i
score += f1_score(yv, xv>th_i, average='macro')
 th/=cv
score/=cv
print('Thresholds: ',th)
 print('F1 macro avr:',score)
 print('F1 macro: ',f1_score(y, pred>th, average='macro'))
print('F1 micro: ',f1_score(y, pred>th, average='micro'))<feature_engineering>
def get_prior(df):
Neither_count = len(df)- sum(df["A-coref"] | df["B-coref"])
 A_count = sum(df["A-coref"])
 B_count = sum(df["B-coref"])
 test_total = len(df)
 Neither_prior = Neither_count/test_total
A_prior = A_count/test_total
B_prior = B_count/test_total
print("Prior probabilities:")
 print("Neither: "+str(Neither_prior),"A: "+str(A_prior),"B: "+str(B_prior))
assert Neither_count + A_count + B_count == test_total
return A_prior, B_prior, Neither_prior
A_prior,B_prior,Neither_prior = get_prior(gap_test)
preds_t,y_t = learner.TTA(n_aug=8,is_test=True)
 preds_t = np.stack(preds_t, axis=-1)
 pred_t = preds_t.mean(axis=-1 )<save_to_csv>
sample_submission = pd.read_csv(".. /input/sample_submission_stage_1.csv")
def save_pred(pred, th=0.0, fname='protein_classification.csv'):
pred_list = []
for line in pred:
s = ' '.join(list([str(i)for i in np.nonzero(line>th)[0]]))
pred_list.append(s)
 df = pd.DataFrame({'Id':learner.data.test_ds.fnames,'Predicted':pred_list})
 df.sort_values(by='Id' ).to_csv(fname, header=True, index=False )<save_to_csv>
def assign_prior(df):
sub = pd.DataFrame()
for index, row in df.iterrows() :
sub.loc[index, "ID"] = row["ID"]
sub.loc[index, "A"] = A_prior
sub.loc[index, "B"] = B_prior
sub.loc[index, "NEITHER"] = Neither_prior
return sub
save_pred(pred_t,th,'protein_classification_v.csv')
 save_pred(pred_t,0.0,'protein_classification_0.csv' )<define_variables>
train = assign_prior(gap_test)
 valid = assign_prior(gap_valid )
lb_prob = [
0.362397820,0.043841336,0.075268817,0.059322034,0.075268817,
0.075268817,0.043841336,0.075268817,0.010000000,0.010000000,
0.010000000,0.043841336,0.043841336,0.014198783,0.043841336,
0.010000000,0.028806584,0.014198783,0.028806584,0.059322034,
0.010000000,0.126126126,0.028806584,0.075268817,0.010000000,
0.222493880,0.028806584,0.010000000] 
<compute_test_metric>
def get_gold(df):
gold = []
for index, row in df.iterrows() :
if(row["A-coref"]):
gold.append("A")
 else:
if(row["B-coref"]):
gold.append("B")
 else:
gold.append("NEITHER")
 return gold
def Count_soft(preds,th=0.0,d=50.0):
preds = sigmoid_np(d*(preds - th))
return preds.mean(axis=0)
 def fit_test(x,y):
params = np.zeros(len(name_label_dict))
wd = 1e-5
error = lambda p: np.concatenate(( Count_soft(x,p)- y,
wd*p), axis=None)
 p, success = opt.leastsq(error, params)
 return p<train_model>
train_gold = get_gold(gap_test)
 valid_gold = get_gold(gap_valid )
th_t = fit_test(pred_t,lb_prob)
 print('Thresholds: ',th_t)
 print('Fractions: ',(pred_t > th_t ).mean(axis=0))
print('Fractions(th = 0.0): ',(pred_t > 0.0 ).mean(axis=0))<save_to_csv>
train_pred = train[["A","B","NEITHER"]]
log_loss(train_gold,train_pred )
save_pred(pred_t,th_t,'protein_classification_f.csv' )<prepare_output>
valid_pred = valid[["A","B","NEITHER"]]
log_loss(valid_gold,valid_pred )
class_list = [8,9,10,15,20,24,27]
for i in class_list:
th_t[i] = th[i]
save_pred(pred_t,th_t,'protein_classification_c.csv' )<data_type_conversions>
sub1 = assign_prior(test_stage_1 )
labels = pd.read_csv(LABELS ).set_index('Id')
 label_count = np.zeros(len(name_label_dict))
for label in labels['Target']:
l = [int(i)for i in label.split() ]
label_count += np.eye(len(name_label_dict)) [l].sum(axis=0)
 label_fraction = label_count.astype(np.float)/len(labels)
 label_count, label_fraction<train_model>
sub1.to_csv("submission_1.csv", index=False )
th_t = fit_test(pred_t,label_fraction)
 print('Thresholds: ',th_t)
 print('Fractions: ',(pred_t > th_t ).mean(axis=0))
save_pred(pred_t,th_t,'protein_classification_t.csv' )<import_modules>
set(gap_test["Pronoun"] ).union(set(gap_valid["Pronoun"])).union(set(test_stage_1["Pronoun"]))
!pip install -q efficientnet
!pip install -q pyyaml h5py
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<set_options>
female_pronouns = ['she','her','hers']
male_pronouns = ['he','him','his']
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>
female_gap_test = gap_test[gap_test["Pronoun"].str.lower().isin(female_pronouns)]
male_gap_test = gap_test[gap_test["Pronoun"].str.lower().isin(male_pronouns)]
female_gap_valid = gap_valid[gap_valid["Pronoun"].str.lower().isin(female_pronouns)]
male_gap_valid = gap_valid[gap_valid["Pronoun"].str.lower().isin(male_pronouns)]
GCS_DS_PATH = KaggleDatasets().get_gcs_path('flower-classification-with-tpus')
 IMAGE_SIZE = [512, 512]
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]]
print("Selected Image files", GCS_PATH)
 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']<define_variables>
train_female = assign_prior(female_gap_test)
 train_male = assign_prior(male_gap_test)
 valid_female = assign_prior(female_gap_valid)
 valid_male = assign_prior(male_gap_valid )
VALIDATION = False
if not VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES+VALIDATION_FILENAMES<categorify>
train_gold_female = get_gold(female_gap_test)
 train_gold_male = get_gold(male_gap_test )
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))<choose_model_class>
train_pred_female = train_female[["A","B","NEITHER"]]
log_loss(train_gold_female,train_pred_female )
with strategy.scope() :
dn201 = tf.keras.applications.DenseNet201(weights='imagenet',
include_top=False,
input_shape=[*IMAGE_SIZE, 3])
 dn201.trainable = True
model1 = tf.keras.Sequential([
dn201,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model1.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=['sparse_categorical_accuracy'] 
)
 model1.summary()<choose_model_class>
train_pred_male = train_male[["A","B","NEITHER"]]
log_loss(train_gold_male,train_pred_male )
with strategy.scope() :
enb7 = efn.EfficientNetB7(weights='noisy-student', include_top=False, input_shape=[*IMAGE_SIZE, 3])
 enb7.trainable = True
model2 = tf.keras.Sequential([
enb7,
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=['sparse_categorical_accuracy'] 
)
 model2.summary()<load_pretrained>
valid_gold_female = get_gold(female_gap_valid)
 valid_gold_male = get_gold(male_gap_valid )
model1.load_weights('/kaggle/input/pretrained-weights-01/densenet-201-ver5.h5')
 model2.load_weights('/kaggle/input/pretrained-weights-01/efficentnetb7-ver5.h5' )<predict_on_test>
valid_pred_female = valid_female[["A","B","NEITHER"]]
log_loss(valid_gold_female,valid_pred_female )
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities1 =(model1.predict(test_images_ds)+model2.predict(test_images_ds)) /2
model1.load_weights('/kaggle/input/pretrained-weights-02/densenet-201-ver6.h5')
 model2.load_weights('/kaggle/input/pretrained-weights-02/efficentnetb7-ver6.h5')
 probabilities2 =(model1.predict(test_images_ds)+model2.predict(test_images_ds)) /2
model1.load_weights('/kaggle/input/pretrained-weights-03/densenet-201-ver7.h5')
 model2.load_weights('/kaggle/input/pretrained-weights-03/efficentnetb7-ver7.h5')
 probabilities3 =(model1.predict(test_images_ds)+model2.predict(test_images_ds)) /2
model1.load_weights('/kaggle/input/pretrained-weights-04/densenet-201-ver8.h5')
 model2.load_weights('/kaggle/input/pretrained-weights-04/efficentnetb7-ver8.h5')
 probabilities4 =(model1.predict(test_images_ds)+model2.predict(test_images_ds)) /2
probabilities =(probabilities1 + probabilities2 + probabilities3 + probabilities4)/4
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>
valid_pred_male = valid_male[["A","B","NEITHER"]]
log_loss(valid_gold_male,valid_pred_male )
import re
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
import math
from sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix
from sklearn.model_selection import KFold<import_modules>
female_test_stage_2 = test_stage_2[test_stage_2["Pronoun"].str.lower().isin(female_pronouns)]
male_test_stage_2 = test_stage_2[test_stage_2["Pronoun"].str.lower().isin(male_pronouns)]
print("Tensorflow version " + tf.__version__)
<set_options>
sub2 = assign_prior(test_stage_2 )
<set_options><EOS> 
sub2.to_csv("submission.csv", index=False )