Kaggle competition: NFL Big Data Bowl
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
 batch = iter(dataset )<predict_on_test>
import matplotlib.pyplot as plt
import seaborn as sns
import pickle
from datetime import datetime as dt
images, labels = next(batch)
 probabilities = model.predict(images)
 predictions = np.argmax(probabilities, axis=-1)
 display_batch_of_images(( images, labels), predictions )<install_modules>
df_input = pd.read_csv("/kaggle/input/nfl-big-data-bowl-2020/train.csv" )
pip install -q efficientnet<set_options>
df_all = df_input.copy()
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE 
<set_options>
personal_columms = ['X', 'Y', 'S', 'A', 'Dis', 'Orientation', 'Dir',
'NflId', 'DisplayName', 'JerseyNumber',
'PlayerHeight', 'PlayerWeight', 'PlayerBirthDate','PlayerCollegeName', 'Position']
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>
pd.set_option("display.max_columns", 80 )
GCS_DS_PATH = KaggleDatasets().get_gcs_path()<define_variables>
import re
IMAGE_SIZE = [512, 512]
EPOCHS = 24
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
NUM_CHANNEL = 3
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']
SKIP_VALIDATION = True
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES<categorify>
def is_float(s):
try:
float(s)
 return True
except ValueError:
return False
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')
 if NUM_CHANNEL == 1:
plt.imshow(tf.reshape(image, [*IMAGE_SIZE]), cmap='gray')
 else:
plt.imshow(tf.reshape(image, [*IMAGE_SIZE, NUM_CHANNEL]))
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>
re.split('[-/ ]', 'From SSW north'.replace("From ", "")) [0]
def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=NUM_CHANNEL)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, NUM_CHANNEL])
 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 PCA_whitening(x):

 print("1: ", x.shape)
 x = tf.reshape(x, [512*512, 1])
 print("2: ", x.shape)
 x_trans = tf.transpose(x)
 sigma = tf.linalg.matmul(x, tf.transpose(x))
print("sigma: ", sigma.shape)
 s, u, v = tf.linalg.svd(sigma)
 print("s: ", s.shape)
 print("u: ", u.shape)
 print("v: ", v.shape)
 xTilde = tf.linalg.matmul(tf.transpose(u), x)
 print("xTilde: ", xTilde.shape)
 xPCA = tf.math.add(s, 0.00001)
 xPCA = 1./ tf.math.sqrt(xPCA)
 xPCA = tf.linalg.diag(xPCA)
 print("diag: ", xPCA.shape)
 xPCA = tf.linalg.matmul(xPCA, xTilde)
 print("return: ", xPCA.shape)
 xPCA = tf.reshape(xPCA, [512, 512])
 print("reshape: ", xPCA.shape)
 return xPCA
def RGB_whitening(image, label):

 r = PCA_whitening(image[:, :, 0])
 g = PCA_whitening(image[:, :, 1])
 b = PCA_whitening(image[:, :, 2])
 r = tf.expand_dims(r, axis=2)
 g = tf.expand_dims(g, axis=2)
 b = tf.expand_dims(b, axis=2)
 image = tf.concat([r, g, b], axis=2)
 print(image.shape)
 print(image.dtype)
 return image, label
def random_shift(image, seed=42):
shift = [randint(0, 20), randint(0, 20)]
image = tf.image.crop_to_bounding_box(image, offset_height=shift[0], offset_width=shift[1],
target_height=IMAGE_SIZE[0]-shift[0], target_width=IMAGE_SIZE[1]-shift[1])
 image = tf.image.pad_to_bounding_box(image, offset_height=0, offset_width=0, target_height=IMAGE_SIZE[0], target_width=IMAGE_SIZE[1])
 return image
def random_rotate(image, seed=42):
dice = randint(0, 10)
 if dice > 3:
dice = 0
return tf.image.rot90(image, dice)
 def data_augment(image, label):
image = tf.image.random_flip_left_right(image, seed=42)
 image = random_shift(image, seed=42)
 return image, label
def data_standardization(image, label):
image = tf.image.per_image_standardization(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.map(data_standardization, 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.map(data_standardization, num_parallel_calls=AUTO)
 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.map(data_standardization, num_parallel_calls=AUTO)
 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>
def preprocess(df):
outdoor=['Outdoor', 'Outdoors','Open','Indoor, Open Roof','Outdoor Retr Roof-Open', 'Oudoor',
'Ourdoor','Retr.Roof-Open','Outdor',
'Retr.Roof - Open', 'Domed, Open', 'Domed, open', 'Outside','Heinz Field']
indoor=['Indoors', 'RetractableRoof', 'Indoor','Retr.Roof-Closed','Dome', 'Domed, closed',
'Indoor, Roof Closed', 'Retr.Roof Closed','Closed Dome','Dome, closed','Domed']
df.loc[df['StadiumType'].isin(outdoor), 'stadiumtype']=1
df.loc[df['StadiumType'].isin(indoor), 'stadiumtype']=0
df.loc[:, "stadiumtype"] = df.loc[:, "stadiumtype"].fillna(2 ).astype(int)
 weather_keywords = [['indoor', 'controlled'],
['snow'],
['clear', 'sun', 'fair'],
['cloudy', 'overcast'],
['hazy'],
['rain', 'shower'],
]
df["weather"] = df["GameWeather"].apply(
 lambda x : min([ n for n,weather_class in enumerate(weather_keywords)
 for word in weather_class if word in str(x ).lower() ]+[len(weather_keywords)]))
df.loc[ df['StadiumType'].isin(indoor), "weather" ] = 0
natural_turf = ['Grass', 'Natural Grass', 'Natural grass', 'grass', 'Natural', 'Naturall Grass', 'natural grass']
df["natural_turf"] = df["Turf"].isin(natural_turf)
 df['PlayerHeight'] = df['PlayerHeight'].apply(lambda x: 12*int(x.split('-')[0])+int(x.split('-')[1]))
df['GameClock']=[ pd.Timedelta(val ).total_seconds() for val in df['GameClock']]
df["TimeSnap"] = pd.to_datetime(df["TimeSnap"], format="%Y-%m-%dT%H:%M:%S.000Z")
 df = df.replace({'ARZ':'ARI', 'BLT':'BAL', 'CLV':'CLE', 'HST':'HOU'})
 df["WindSpeed"] = df["WindSpeed"].apply(lambda value :
np.mean([ float(oo)for oo in re.split('[^0-9.]+', str(value)) if is_float(oo)]))
df.loc[ df['StadiumType'].isin(indoor), "WindSpeed" ] = 0
df["yardsToTouchdown"] = df["YardLine"]
df.loc[ df["PossessionTeam"] == df["FieldPosition"], "yardsToTouchdown"] = 100-df["YardLine"]
return df
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>
df_all = preprocess(df_all )
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )<define_variables>
def preprocess_coord(df):
df.loc[df["Season"]==2017, "Orientation"] =(df["Orientation"] -90)%360
df.loc[df["PlayDirection"]=="left", "X"] = 120 - df["X"]
df.loc[df["PlayDirection"]=="left", "Y"] = 53.3 - df["Y"]
df.loc[df["PlayDirection"]=="left", "Dir"] =(df["Dir"]+180)%360
df.loc[df["PlayDirection"]=="left", "Orientation"] =(df["Orientation"]+180)%360
df["X"] = df["X"] -(110-df["yardsToTouchdown"])
 df["Sy"] =(df["Dir"]*np.pi/180 ).map(np.cos)* df["S"]
df["Sx"] =(df["Dir"]*np.pi/180 ).map(np.sin)* df["S"]
df.drop(["S", "Dir"], axis=1, inplace=True)
 df["Orientation"] =(df["Orientation"]*np.pi/180 ).map(np.cos)
 return df
display_batch_of_images(next(train_batch))<define_variables>
df_all = preprocess_coord(df_all )
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )<define_variables>
df_play = df_all[df_all["NflId"]==df_all["NflIdRusher"]].copy()
display_batch_of_images(next(test_batch))<choose_model_class>
df_play["Position"].value_counts()
def lrfn(epoch):
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
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
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>
def get_team_score(df_play):
df_play.loc[df_play["Team"]=="home", "rusherTeamScore"] = df_play["HomeScoreBeforePlay"]
df_play.loc[df_play["Team"]=="away", "rusherTeamScore"] = df_play["VisitorScoreBeforePlay"]
df_play.loc[df_play["Team"]=="home", "defenceTeamScore"] = df_play["VisitorScoreBeforePlay"]
df_play.loc[df_play["Team"]=="away", "defenceTeamScore"] = df_play["HomeScoreBeforePlay"]
df_play.loc[:, "diffScore"] = df_play["rusherTeamScore"] - df_play["defenceTeamScore"]
return df_play
lr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1 )<choose_model_class>
df_play = get_team_score(df_play )
es_callback = tf.keras.callbacks.EarlyStopping(min_delta=0, patience=10, verbose=1, mode='auto', restore_best_weights=True )<choose_model_class>
def player_team_name(df_play):
df_play.loc[:, "PlayerTeamAbbr"] = df_play["HomeTeamAbbr"]
df_play.loc[ df_play["Team"]=="away", "PlayerTeamAbbr"] = df_play["VisitorTeamAbbr"]
return df_play
def team_name(df_play):
df_play.loc[:, "PlayerTeamAbbr"] = df_play["HomeTeamAbbr"]
df_play.loc[ df_play["Team"]=="away", "PlayerTeamAbbr"] = df_play["VisitorTeamAbbr"]
df_play.loc[:, "DefenceTeamAbbr"] = df_play["HomeTeamAbbr"]
df_play.loc[ df_play["Team"]=="home", "DefenceTeamAbbr"] = df_play["VisitorTeamAbbr"]
return df_play
with strategy.scope() :
dense_net = tf.keras.applications.DenseNet201(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])
 dense_net.trainable = True
model1 = tf.keras.Sequential([
dense_net,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model1.compile(
 optimizer= tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model1.summary()<train_model>
history1 = model1.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS, callbacks=[lr_schedule],
validation_data=None if SKIP_VALIDATION else get_validation_dataset() )<choose_model_class>
df_all.loc[:, "offense"] =(df_all["PlayerTeamAbbr"]==df_all["PossessionTeam"])*1
with strategy.scope() :
efficient_net = efn.EfficientNetB7(input_shape=[*IMAGE_SIZE, 3], weights='imagenet',include_top=False)
 efficient_net.trainable = True
model2 = tf.keras.Sequential([
efficient_net,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model2.compile(
 optimizer= tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model2.summary()<train_model>
def count_position(df_play):
df_play.loc[:, "OffensePersonnel"] = df_play["OffensePersonnel"].apply(
 lambda x : { i.split(" ")[-1]:int(i.split(" ")[-2])for i in x.split(",")})
 df_play.loc[:, "DefensePersonnel"] = df_play["DefensePersonnel"].apply(
 lambda x : { i.split(" ")[-1]:int(i.split(" ")[-2])for i in x.split(",")})
 for position in ["LB", "DB"]:
df_play.loc[:, position] = [ d[position] for d in df_play["DefensePersonnel"]]
for position in ["RB", "TE", "WR"]:
df_play.loc[:, position] = [ d[position] for d in df_play["OffensePersonnel"]]
return df_play
history2 = model2.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS, callbacks=[lr_schedule, es_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset() )<choose_model_class>
df_play[df_play["Position"].isin(["CB", "DT", "DE"])][[ "PlayId", "DisplayName", "Position",
"Team", "PossessionTeam", "HomeTeamAbbr", "VisitorTeamAbbr"]]
with strategy.scope() :
res_net = tf.keras.applications.inception_resnet_v2.InceptionResNetV2(include_top=False, weights='imagenet', input_tensor=None, input_shape=[*IMAGE_SIZE, 3], pooling=None, classes=1000)
 res_net.trainable = True
model3 = tf.keras.Sequential([
res_net,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model3.compile(
 optimizer= tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model3.summary()<train_model>
df_all[df_all["PlayId"]==20181007081701][[ "PlayId", "DisplayName",
"Team", "PossessionTeam", "HomeTeamAbbr", "VisitorTeamAbbr", "Position"]]
history3 = model3.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS, callbacks=[lr_schedule],
validation_data=None if SKIP_VALIDATION else get_validation_dataset() )<predict_on_test>
team_yards_df, defence_yards_df, personal_yards = average_yards(df_play )
test_ds = get_test_dataset(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
 print('Computing predictions for model 1...... ')
 preds1 = model1.predict(test_images_ds)
 print('Computing predictions for model 2...... ')
 preds2 = model2.predict(test_images_ds)
 print('Computing predictions for model 3...... ')
 preds3 = model3.predict(test_images_ds )<save_to_csv>
position_rename = {
"SAF":"S", "FS":"S", "SS":"S", "S":"S", "DB":"S",
"CB":"CB",
"ILB":"MLB", "MLB":"MLB",
"OLB":"OLB", "LB":"OLB",
"NT":"DT", "DT":"DT",
"DE":"DE", "DL":"DE",
"C":"C",
"G":"OG", "OG":"OG",
"T":"OT", "OT":"OT",
"WR":"WR",
"TE":"TE",
"QB":"QB",
"FB":"FB",
"HB":"HB",
"RB":"RB",
}
probabilities =(preds1 + preds2 + preds3)/ 3
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>
df_all["position"] = df_all["Position"].map(position_rename)
 df_play["position"] = df_play["Position"].map(position_rename )
import numpy as np
import pandas as pd<set_options>
df_all.loc[df_all["offense"]==1, "position"] = df_all.loc[df_all["offense"]==1, "position"].apply(group_position_offense)
 df_all.loc[df_all["offense"]==0, "position"] = df_all.loc[df_all["offense"]==0, "position"].apply(group_position_defense)
!pip install -q efficientnet
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<set_options>
position_stats_columms=['X', 'Y', 'A', 'Dis','PlayerHeight', 'PlayerWeight', 'Sx', 'Sy', 'Orientation']
position_corrY_columms=['X', 'A', 'Dis','PlayerHeight', 'PlayerWeight', 'Sx', 'Sy', 'Orientation']
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>
def position_stats(df):
groups = df[(df["NflId"]!=df["NflIdRusher"])][
["PlayId", "position", *position_stats_columms]].groupby(["PlayId", "position"])
 position_mean = groups.agg(["count", "mean", "std", "skew"] ).unstack(level=1)
 position_mean.columns = [ col[2]+"_"+col[0]+"_"+col[1] for col in position_mean.columns]
cols = [col for col in position_mean.columns
if("X_count" in col)
 or("mean" in col)
 or("std" in col and re.findall("OL|WR|DL|LB|S_|CB", col))
or("skew" in col and re.findall("OL|DL", col)) ]
position_corr = groups.corr() ["Y"].unstack().drop("Y", axis=1 ).reset_index()
position_corr = position_corr.loc[position_corr["position"].isin(["OL", "DL", "LB", "WR"])]
position_corr = position_corr.pivot(index="PlayId", columns="position", values=position_corrY_columms)
 position_corr.columns = [ col[1]+"_"+col[0]+"_corrY" for col in position_corr.columns]
position_stats = position_mean[cols].join(position_corr)
 position_stats.fillna(0, inplace=True)
 return position_stats
GCS_DS_PATH = KaggleDatasets().get_gcs_path()<define_variables>
def average_personal_data(df_play, df_all):
offence_av = df_all.loc[df_all["offence"]==1, ["PlayerHeight", "PlayerWeight", "S", "A", "PlayId"]].groupby("PlayId" ).mean()
defence_av = df_all.loc[df_all["offence"]==0, ["PlayerHeight", "PlayerWeight", "S", "A", "PlayId"]].groupby("PlayId" ).mean()
offence_av.columns = ['PlayerHeight_offence', 'PlayerWeight_offence', 'S_offence', 'A_offence']
defence_av.columns = ['PlayerHeight_defence', 'PlayerWeight_defence', 'S_defence', 'A_defence']
df_play = df_play.merge(offence_av, on="PlayId", how="left" ).merge(defence_av, on="PlayId", how="left")
 return df_play
VALIDATION = False
if not VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES<categorify>
def map_position(df):
df = df.loc[df["NflId"]!=df["NflIdRusher"], ["Position", *position_stats_columms]]
df.loc[:,"offset"] =(df["Y"]-df["Y"].mean())**2 + df["X"]**2
OL = df[df["Position"]=="OL"].sort_values("offset")
 OB = df[df["Position"].isin(["QB", "RB", "TE", "WR"])].sort_values("offset")
 DL = df[df["Position"].isin(["DL", "LB"])].sort_values("offset")
 DB = df[df["Position"]=="DB"].sort_values("offset")
 if len(OL)>5:
OB = pd.concat([OB, OL.iloc[5:]])
 OL = OL.iloc[:5]
elif len(OB)>5:
OL = pd.concat([OL, OB.iloc[:-5]])
 OB = OL.iloc[-5:]
if len(DL)>7:
DB = pd.concat([DB, DL.iloc[7:]])
 DL = DL.iloc[:7]
elif len(DB)>4:
DL = pd.concat([DL, DB.iloc[:-4]])
 DB = DB.iloc[-4:]
OB, OL, DB, DL = OB.sort_values("Y"), OL.sort_values("Y"), DB.sort_values("Y"), DL.sort_values("Y")
 return pd.concat([OB, OL, DB, DL] ).drop("offset", axis=1 ).reset_index(drop=True)
 def process_positiondata(df_all):
map_position_df = df_all.groupby("PlayId" ).apply(map_position)
 positiondata_df = map_position_df.drop("Position",axis=1 ).unstack(level=1 ).fillna(0)
 positiondata_df.columns = [ col[0]+"_"+str(col[1])for col in positiondata_df.columns]
return positiondata_df
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>
df_play = df_play.merge(position_stats(df_all), on="PlayId", how="left")
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>
def merge_lastYearAv(df_play, team_yards_df, defence_yards_df, personal_yards, year):
last_year = year-1
df = team_yards_df[[last_year]]
df.columns = ["team_yards_av", "team_yards_std"]
df_year = df_play[df_play["Season"]==year].merge(df, on=["Team","PlayerTeamAbbr"], how="left")
 df = defence_yards_df[[last_year]]
df.columns = ["def_yards_av", "def_yards_std"]
df_year = df_year.merge(df, on=["Team","DefenceTeamAbbr"], how="left")
 df_year = df_year.merge(
 personal_yards[last_year].rename(columns={'mean': 'player_yards_av', 'std': 'player_yards_std',
'count': 'player_yards_count'}),
on="NflId", how="left")
 return df_year
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>
def merge_twoYearAv(df_play, team_yards_df, defence_yards_df, personal_yards):
df =(team_yards_df[2017]+team_yards_df[2018])/2
df.columns = ["team_yards_av", "team_yards_std"]
df_year = df_play.merge(df, on=["Team","PlayerTeamAbbr"], how="left")
 df =(defence_yards_df[2017]+defence_yards_df[2018])/2
df.columns = ["def_yards_av", "def_yards_std"]
df_year = df_year.merge(df, on=["Team","DefenceTeamAbbr"], how="left")
 df =(personal_yards[2017]+personal_yards[2018])/2
df_year = df_year.merge(
 df.rename(columns={'mean': 'player_yards_av', 'std': 'player_yards_std',
'count': 'player_yards_count'}),
on="NflId", how="left")
 return df_year
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )<define_variables>
def merge_anotherYearAv(df_play, team_yards_df, defence_yards_df, personal_yards):
df = team_yards_df[[2017]]
df.columns = ["team_yards_av", "team_yards_std"]
df_2018 = df_play[df_play["Season"]==2018].merge(df, on=["Team","PlayerTeamAbbr"], how="left")
 df = defence_yards_df[[2017]]
df.columns = ["def_yards_av", "def_yards_std"]
df_2018 = df_2018.merge(df, on=["Team","DefenceTeamAbbr"], how="left")
 df_2018 = df_2018.merge(
 personal_yards[2017].rename(columns={'mean': 'player_yards_av', 'std': 'player_yards_std',
'count': 'player_yards_count'}),
on="NflId", how="left")
 df = team_yards_df[[2018]]
df.columns = ["team_yards_av", "team_yards_std"]
df_2017 = df_play[df_play["Season"]==2017].merge(df, on=["Team","PlayerTeamAbbr"], how="left")
 df = defence_yards_df[[2018]]
df.columns = ["def_yards_av", "def_yards_std"]
df_2017 = df_2017.merge(df, on=["Team","DefenceTeamAbbr"], how="left")
 df_2017 = df_2017.merge(
 personal_yards[2018].rename(columns={'mean': 'player_yards_av', 'std': 'player_yards_std',
'count': 'player_yards_count'}),
on="NflId", how="left")
 return pd.concat([df_2017, df_2018] )
display_batch_of_images(next(train_batch))<define_variables>
import pickle
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )<define_variables>
df_year.to_pickle("df_year.pickle" )
display_batch_of_images(next(test_batch))<choose_model_class>
df_year.isnull().sum().sort_values().tail(15 )
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>
def select_columns(df):
df_u = df.drop(["FieldPosition", "StadiumType", "GameWeather", "WindDirection", "DefendersInTheBox"], axis=1)
 df_u = df_u.fillna(df_u.mean())
 df_X = df_u.drop([
"DisplayName", "PossessionTeam",
"OffensePersonnel", "DefensePersonnel", "PlayDirection",
"PlayerBirthDate", "PlayerCollegeName",
"HomeTeamAbbr", "VisitorTeamAbbr",
"Location", "Turf", "Position",
"OffenseFormation",
"GameClock", "TimeHandoff",
"GameId", "PlayId", "JerseyNumber", "NflIdRusher",
"YardLine", "VisitorScoreBeforePlay", "HomeScoreBeforePlay", "defenceTeamScore",
], axis=1)
 return df_X
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()<randomize_order>
df_X = select_columns(df_year)
 df_y = df_X["Yards"]
df_X = df_X.drop(["Yards"], axis=1 )
LR_START = 0.0001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 4
LR_SUSTAIN_EPOCHS = 6
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 )<choose_model_class>
cat_int = ['stadiumtype', 'weather', 'natural_turf',]
cat_num = ['NflId', 'Season', ]
cat_str = ['Team', 'position', "Stadium", "PlayerTeamAbbr", "DefenceTeamAbbr"]
categorical_features_indices = sorted([list(df_X.columns ).index(n)for n in cat_int+cat_num+cat_str] )
es_callback = tf.keras.callbacks.EarlyStopping(min_delta = 0,
patience = 10,
verbose = 1,
mode = 'auto',
restore_best_weights = True )<train_model>
df_ycopy = df_y.copy()
if VALIDATION:
history1 = model1.fit(get_training_dataset() ,
steps_per_epoch = STEPS_PER_EPOCH,
epochs = 40,
validation_data = get_validation_dataset() ,
callbacks = [lr_callback, es_callback])
 else:
history1 = model1.fit(get_training_dataset() ,
steps_per_epoch = STEPS_PER_EPOCH,
epochs = 30,
callbacks = [lr_callback] )<train_model>
max_yards = 20
min_yards = -5
if VALIDATION:
history2 = model2.fit(get_training_dataset() ,
steps_per_epoch = STEPS_PER_EPOCH,
epochs = 40,
validation_data = get_validation_dataset() ,
callbacks = [lr_callback, es_callback])
 else:
history2 = model2.fit(get_training_dataset() ,
steps_per_epoch = STEPS_PER_EPOCH,
epochs = 30,
callbacks = [lr_callback] )<predict_on_test>
print(len(df_y.loc[df_y>=max_yards]))
print(len(df_y.loc[df_y<=min_yards]))
if VALIDATION:
cmdataset = get_validation_dataset(ordered=True)
 images_ds = cmdataset.map(lambda image, label: image)
 labels_ds = cmdataset.map(lambda image, label: label ).unbatch()
cm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_probabilities =(model1.predict(images_ds)*0.3)+model2.predict(images_ds)*0.7
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions )<compute_test_metric>
df_count = df_ycopy.value_counts().sort_index()
if VALIDATION:
cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))
 score = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 precision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 recall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))<predict_on_test>
from scipy.optimize import curve_fit
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities =(model1.predict(test_images_ds)+model2.predict(test_images_ds)) /2
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>
def linear_fit(x, a, b):
return a*x+b
array_x= df_count.loc[max_yards:37].index
array_y= np.log(df_count.loc[max_yards:37].values)
 param, cov = curve_fit(linear_fit, array_x, array_y)
 large_probs = pd.DataFrame(np.exp(np.array(range(max_yards,100)) *param[0]),
columns=["value"], index=np.array(range(max_yards,100)))
 large_probs = large_probs/large_probs.sum()
import numpy as np
import pandas as pd
import os 
<set_options>
df_y.loc[df_y>=max_yards] = max_yards
df_y.loc[df_y<=min_yards] = min_yards
!pip install -q efficientnet
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<set_options>
from tqdm import tqdm
from sklearn.model_selection import train_test_split
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>
from catboost import CatBoostClassifier, Pool
GCS_DS_PATH = KaggleDatasets().get_gcs_path()<define_variables>
train_X, test_X, train_y, test_y, train_ycopy, test_ycopy = train_test_split(df_X, df_y, df_ycopy, test_size=0.3 )
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]]
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>
df_y0 = df_y-min_yards
train_y0 = train_y-min_yards
test_y0 = test_y-min_yards
VALIDATION = False
if not VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES+VALIDATION_FILENAMES<categorify>
from sklearn.model_selection import KFold
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>
def calc_score(pred_y, test_y, yardsToTouchdown):
pred_df = pd.DataFrame(pred_y)
 pred_df.columns = [ "Yards"+str(n)for n in range(min_yards,max_yards+1)]
pred_df_all = pd.DataFrame(pred_df,columns=[ "Yards"+str(n)for n in range(-99,100)])
 pred_df_all.loc[:, "Yards"+str(max_yards):] = \ 
(pred_df_all.loc[:, ["Yards"+str(max_yards)]] ).dot(large_probs.values.T ).values
pred_df_all.loc[:, "Yards-14":"Yards"+str(min_yards)] = \ 
(pred_df_all.loc[:, ["Yards"+str(min_yards)]] ).dot(small_probs.values.T ).values
pred_df_all.fillna(0, inplace=True)
 pred_df_all = pred_df_all.cumsum(axis=1)
 for index, row in pred_df_all.iterrows() :
pred_df_all.loc[index, "Yards"+str(yardsToTouchdown[index]):] = 1
test_df = pd.DataFrame(np.array([(i >= test_y)*1 for i in range(-99,100)] ).T,
columns=pred_df_all.columns)
 CRPS=(( pred_df_all-test_df)**2 ).mean().mean()
return CRPS, pred_df_all, test_df
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>
from six.moves import xrange
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )<categorify>
import math
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.'] )<define_variables>
class CRPSMetric(object):
def get_final_error(self, error, weight):
return error /(weight + 1e-38)
 def is_max_optimal(self):
return True
def evaluate(self, approxes, target, weight):
n_class =(max_yards-min_yards+1)
 assert len(approxes)== n_class
assert len(target)== len(approxes[0])
 error_sum = 0
weight_sum = 0
for i in xrange(len(target)) :
w = 1.0 if weight is None else weight[i]
weight_sum += w
for j in xrange(len(approxes)) :
target01 =(target[i]>=j)*1
prob = 1/(1+(1/math.exp(approxes[j][i])))
 error_sum +=(( prob - target01)**2)/n_class
return error_sum, len(target )
display_batch_of_images(next(train_batch))<define_variables>
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )<define_variables>
import optuna
display_batch_of_images(next(test_batch))<choose_model_class>
def objective(trial):
params = {
'iterations' : trial.suggest_int('iterations', 50, 300),
'depth' : trial.suggest_int('depth', 4, 12),
'learning_rate' : trial.suggest_loguniform('learning_rate', 0.003, 0.3),
'random_strength' :trial.suggest_loguniform('random_strength', 0.3, 30),
'bagging_temperature' :trial.suggest_loguniform('bagging_temperature', 0.1, 10.00),
'l2_leaf_reg': trial.suggest_loguniform('l2_leaf_reg', 0.3, 30.0),
}
model = CatBoostClassifier(**params, 
)
 model.fit(train_pool,
verbose=False, 
)
 preds = model.predict_proba(test_X)
 CRPS, pred_df_all, test_df = calc_score(preds, test_ycopy, test_X["yardsToTouchdown"].values)
 return CRPS
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>
def objective(trial):
params = {
'iterations' : trial.suggest_int('iterations', 200, 2000),
'depth' : trial.suggest_int('depth', 6, 10),
'learning_rate' : trial.suggest_loguniform('learning_rate', 0.003, 0.1),
'random_strength' :trial.suggest_loguniform('random_strength', 0.1, 1),
'bagging_temperature' :trial.suggest_loguniform('bagging_temperature', 0.1, 1.0),
'l2_leaf_reg': trial.suggest_loguniform('l2_leaf_reg', 1, 20.0),
'has_time':trial.suggest_categorical('has_time', [True, False])
 }
kfold = KFold(n_splits=3, random_state=23)
 scores = []
for train, test in kfold.split(df_X):
train_X = df_X.iloc[train]
train_y0 = df_y0.iloc[train]
test_X = df_X.iloc[test]
test_y0 = df_y0.iloc[test]
train_pool = Pool(train_X, train_y0, cat_features=categorical_features_indices)
 model = CatBoostClassifier(**params, 
)
 model.fit(train_pool,
verbose=False, 
)
 preds = model.predict_proba(test_X)
 CRPS, pred_df_all, test_df = calc_score(preds, df_ycopy.iloc[test], test_X["yardsToTouchdown"].values)
 scores.append(CRPS)
 return np.mean(scores)
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()<randomize_order>
LR_START = 0.0001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 4
LR_SUSTAIN_EPOCHS = 6
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 )<choose_model_class>
params = {'iterations': 1000, 'depth': 6,
'learning_rate': 0.037587603778015836, 'random_strength': 0.6401109404028098,
'bagging_temperature': 0.10845008746433943, 'l2_leaf_reg': 6.247622793136706,
'has_time': True}
es_callback = tf.keras.callbacks.EarlyStopping(min_delta=0, patience=10, verbose=1, mode='auto', restore_best_weights=True )<train_model>
train_pool = Pool(df_X, df_y0, cat_features=categorical_features_indices )
if VALIDATION:
history1 = model1.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=40, validation_data=get_validation_dataset() , callbacks = [lr_callback, es_callback])
 else:
history1 = model1.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=30, callbacks = [lr_callback] )<train_model>
model = CatBoostClassifier(**params, 
)
 model.fit(train_pool,
verbose=True,
)
if VALIDATION:
history2 = model2.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=40, validation_data=get_validation_dataset() , callbacks = [lr_callback, es_callback])
 else:
history2 = model2.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=30, callbacks = [lr_callback] )<predict_on_test>
importance = pd.DataFrame(model.feature_importances_, index=df_X.columns, columns=['importance'])
 importance.sort_values("importance", ascending=False ).head(50 )
if VALIDATION:
cmdataset = get_validation_dataset(ordered=True)
 images_ds = cmdataset.map(lambda image, label: image)
 labels_ds = cmdataset.map(lambda image, label: label ).unbatch()
cm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_probabilities =(model1.predict(images_ds)+model2.predict(images_ds)) /2
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions )<compute_test_metric>
from kaggle.competitions import nflrush
if VALIDATION:
cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))
 score = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 precision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 recall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))<save_to_csv>
warnings.simplefilter('ignore' )
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities =(model1.predict(test_images_ds)+model2.predict(test_images_ds)) /2
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<define_variables>
for(test_df, sample_prediction_df)in tqdm(env.iter_test()):
df_a = preprocess(test_df)
 df_a = preprocess_coord(df_a)
 df_ = df_a.loc[df_a["NflId"]==df_a["NflIdRusher"], :]
df_ = get_team_score(df_)
 df_a = player_team_name(df_a)
 df_ = team_name(df_)
 df_a.loc[:, "offense"] =(df_a["PlayerTeamAbbr"]==df_a["PossessionTeam"])*1
df_a["position"] = df_a["Position"].map(position_rename)
 df_["position"] = df_["Position"].map(position_rename)
 df_a.loc[df_a["offense"]==1, "position"] = df_a.loc[df_a["offense"]==1, "position"].apply(group_position_offense)
 df_a.loc[df_a["offense"]==0, "position"] = df_a.loc[df_a["offense"]==0, "position"].apply(group_position_defense)
 df_ = df_.merge(position_stats(df_a), on="PlayId", how="left")
 df_year = df_
test_X=pd.DataFrame(df_year,columns=df_X.columns)
 test_X.fillna(means)
 pred520 = model.predict_proba(test_X)[0]
pred100 = np.concatenate([ np.zeros(85), pred520[0]*small_probs["value"].values, pred520[1:-1], pred520[-1]*large_probs["value"].values ])
 sample_prediction_df.iloc[0] = pred100.cumsum()
sample_prediction_df.loc[:, "Yards"+str(test_X["yardsToTouchdown"][0]): ] = 1
sample_prediction_df[sample_prediction_df>1.0] = 1.0
env.predict(sample_prediction_df)
if VALIDATION:
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
 batch = iter(dataset )<predict_on_test>
env.write_submission_file()
if VALIDATION:
images, labels = next(batch)
 probabilities =(model1.predict(images)+model2.predict(images)) /2
predictions = np.argmax(probabilities, axis=-1)
 display_batch_of_images(( images, labels), predictions )<install_modules>
( test_df, sample_prediction_df)= next(env.iter_test() )
!pip install -q efficientnet<import_modules>
df_ = df_a.loc[df_a["NflId"]==df_a["NflIdRusher"], :]
df_ = get_team_score(df_)
 df_a = player_team_name(df_a)
 df_ = team_name(df_)
 df_a.loc[:, "offense"] =(df_a["PlayerTeamAbbr"]==df_a["PossessionTeam"])*1
df_a["position"] = df_a["Position"].map(position_rename)
 df_["position"] = df_["Position"].map(position_rename)
 df_a.loc[df_a["offense"]==1, "position"] = df_a.loc[df_a["offense"]==1, "position"].apply(group_position_offense)
 df_a.loc[df_a["offense"]==0, "position"] = df_a.loc[df_a["offense"]==0, "position"].apply(group_position_defense)
 df_ = df_.merge(position_stats(df_a), on="PlayId", how="left")
 df_year = df_play
test_X=pd.DataFrame(df_year,columns=df_X.columns)
 test_X.fillna(means)
 pred520 = model.predict_proba(test_X)[0]
pred100 = np.concatenate([ np.zeros(85), pred520[0]*small_probs["value"].values, pred520[1:-1], pred520[-1]*large_probs["value"].values ])
 sample_prediction_df.iloc[0] = pred100.cumsum()
sample_prediction_df.loc[:, "Yards"+str(test_X["yardsToTouchdown"][0]): ] = 1
sample_prediction_df[sample_prediction_df>1.0] = 1.0
print("Tensorflow version " + tf.__version__)
<set_options>
sample_prediction_df.loc[:, "Yards-17":]
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)
<define_variables>
df_all = preprocess(test_df )
AUTO = tf.data.experimental.AUTOTUNE
IMAGE_SIZE = [512, 512]
EPOCHS = 40
SEED = 777
BATCH_SIZE = 16 * strategy.num_replicas_in_sync<set_options>
df_ = df_all[df_all["NflId"]==df_all["NflIdRusher"]]
MIXED_PRECISION = True
XLA_ACCELERATE = True
if MIXED_PRECISION:
if tpu:
policy = tf.keras.mixed_precision.experimental.Policy('mixed_bfloat16')
 else:
policy = tf.keras.mixed_precision.experimental.Policy('mixed_float16')
 mixed_precision.set_policy(policy)
 print('Mixed precision enabled')
 if XLA_ACCELERATE:
tf.config.optimizer.set_jit(True)
 print('Accelerated Linear Algebra enabled' )<define_variables>
GCS_DS_PATH = KaggleDatasets().get_gcs_path()
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 = True
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES<define_variables>
df_ = get_team_score(df_)
 df_ = average_personal_data(df_, df_all)
 df_ = add_last_yards(df_ )
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']<init_hyperparams>
df_year = merge_lastYearAv(df_, team_yards_df, defence_yards_df, personal_yards, 2019 )
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 10
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY =.9
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
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)
 rng = [i for i in range(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]))<categorify>
test_X=pd.concat([train_df,test_X],sort=False)
 test_X = test_X.fillna(0 )
<normalization><EOS> 
pred_df = pd.DataFrame(clf.predict_proba(test_X), columns=[ "Yards"+str(i)for i in clf.classes_])
 pred_df = pred_df.cumsum(axis=1 )