Kaggle competition: Bengali.AI Handwritten Grapheme Classification
<SOS> metric: WeightedCategorizationAccuracy Kaggle data source: bengali.ai-handwritten-grapheme-classification<set_options>
!pip install /kaggle/input/efficientnet-pytorch
!pip install /kaggle/input/pytorchcv/pytorchcv-0.0.57-py2.py3-none-any.whl
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>
import glob
import os
import zipfile
import cv2
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from efficientnet_pytorch import EfficientNet
from pytorchcv.model_provider import get_model
from torch.utils.data import DataLoader, Dataset
image_size =(224, 224)
 data_gcs = KaggleDatasets().get_gcs_path('tpu-getting-started')
 ext_gcs = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec')
 data_dir_by_size = { 
(512, 512): '/tfrecords-jpeg-512x512', 
(331, 331): '/tfrecords-jpeg-331x331', 
(224, 224): '/tfrecords-jpeg-224x224', 
(192, 192): '/tfrecords-jpeg-192x192'
}
subdir = data_dir_by_size[image_size]
train_file_names = tf.io.gfile.glob(data_gcs + subdir + '/train' + '/*.tfrec')
 val_file_names = tf.io.gfile.glob(data_gcs + subdir + '/val' + '/*.tfrec')
 test_file_names = tf.io.gfile.glob(data_gcs + subdir + '/test' + '/*.tfrec')
 imagenet_files = tf.io.gfile.glob(ext_gcs + '/imagenet' + subdir + '/*.tfrec')
 inaturelist_files = tf.io.gfile.glob(ext_gcs + '/inaturalist' + subdir + '/*.tfrec')
 openimage_files = tf.io.gfile.glob(ext_gcs + '/openimage' + subdir + '/*.tfrec')
 oxford_files = tf.io.gfile.glob(ext_gcs + '/oxford_102' + subdir + '/*.tfrec')
 tensorflow_files = tf.io.gfile.glob(ext_gcs + '/tf_flowers' + subdir + '/*.tfrec')
 train_file_names = train_file_names + imagenet_files + inaturelist_files + \
openimage_files + oxford_files + tensorflow_files<define_variables>
INPUT_FILES = ["/kaggle/input/bengaliai-cv19/test_image_data_0.parquet",
"/kaggle/input/bengaliai-cv19/test_image_data_1.parquet",
"/kaggle/input/bengaliai-cv19/test_image_data_2.parquet",
"/kaggle/input/bengaliai-cv19/test_image_data_3.parquet"]
HEIGHT = 137
WIDTH = 236
BATCH_SIZE = 50
DEVICE = torch.device("cuda")
 DTYPE = torch.float
flower_categories = [
'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'
]
print('Number of flower categories:', len(flower_categories))<categorify>
def preprocess_images(input_files, output_file, size):
x_tot, x2_tot = [], []
with zipfile.ZipFile(output_file, "w")as img_out:
for fname in input_files:
df = pd.read_parquet(fname)
 data = 255 - df.iloc[:, 1:].values.reshape(-1, HEIGHT, WIDTH ).astype(np.uint8)
 for idx in range(len(df)) :
name = df.iloc[idx, 0]
img =(data[idx]*(255.0/data[idx].max())).astype(np.uint8)
 img = crop_resize(img, size)
 x_tot.append(( img/255.0 ).mean())
 x2_tot.append(((img/255.0)**2 ).mean())
 img = cv2.imencode(".png", img)[1]
img_out.writestr(name + ".png", img )
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):

 example = tf.io.parse_single_example(
 serialized=example,
features={
'image': tf.io.FixedLenFeature([], tf.string),
'class': tf.io.FixedLenFeature([], tf.int64),
} 
)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_unlabeled_tfrecord(example):

 example = tf.io.parse_single_example(
 serialized=example,
features={
'image': tf.io.FixedLenFeature([], tf.string),
'id': tf.io.FixedLenFeature([], tf.string),
} 
)
 image = decode_image(example['image'])
 idnum = example['id']
return image, idnum
def load_dataset(filenames, labeled=True, ordered=False):

 ignore_order = tf.data.Options()
ignore_order.experimental_deterministic = ordered
dataset = tf.data.TFRecordDataset(
 filenames, num_parallel_reads=tf.data.experimental.AUTOTUNE)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(
 read_labeled_tfrecord if labeled else read_unlabeled_tfrecord,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
 return dataset
def count_data_items(filenames):

 return np.sum([
int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1))
for filename in filenames])
 train_dataset = load_dataset(train_file_names, labeled=True, ordered=False)
 val_dataset = load_dataset(val_file_names, labeled=True, ordered=False)
 test_dataset = load_dataset(test_file_names, labeled=False, ordered=True)
 num_training_samples = count_data_items(train_file_names)
 num_validation_samples = count_data_items(val_file_names)
 num_testing_samples = count_data_items(test_file_names )<train_model>
class MyDataset(Dataset):
def __init__(self, img_dir, img_files):
self.img_dir = img_dir
self.img_files = img_files
def __len__(self):
return len(self.img_files)
 def __getitem__(self, idx):
img = cv2.imread(self.img_files[idx])
 img = img.transpose(( 2, 0, 1)) [0]
img = img / 255
return int(self.img_files[idx].replace(self.img_dir, "" ).replace(".png", "" ).replace("Test_", "")) , np.array([img] )
print('Train samples:', num_training_samples, end=', ')
 print('Val samples:', num_validation_samples, end=', ')
 print('Test samples:', num_testing_samples )<categorify>
preds = {}
transformer = ktu.TFImageTransform(
 image_size,
horizontal_flip=True,
vertical_flip=True,
brightness_adjustments=True,
rotation_range=15.,
shear_range=5.,
zoom_range=(0.1, 0.1),
shift_range=(16., 16.) 
)
 def augmentation(image, label):
return transformer.transform(image), label<define_variables>
if not os.path.isfile("test_images_128.zip"):
preprocess_images(INPUT_FILES, "test_images_128.zip", 128)
 with zipfile.ZipFile("test_images_128.zip")as img_zip:
img_zip.extractall("test_images_128")
 test_set = MyDataset("test_images_128/", glob.glob("test_images_128/*.png"))
test_loader = DataLoader(test_set, batch_size=BATCH_SIZE, shuffle=False, num_workers=4 )
batch_size = 16 * strategy.num_replicas_in_sync
epochs = 25
batched_train_dataset = train_dataset.map(augmentation)
 batched_train_dataset = batched_train_dataset.repeat()
batched_train_dataset = batched_train_dataset.shuffle(buffer_size=2048)
 batched_train_dataset = batched_train_dataset.batch(batch_size)
 batched_train_dataset = batched_train_dataset.prefetch(tf.data.experimental.AUTOTUNE)
 batched_val_dataset = val_dataset.batch(batch_size)
 batched_val_dataset = batched_val_dataset.cache()
batched_val_dataset = batched_val_dataset.prefetch(tf.data.experimental.AUTOTUNE)
 batched_test_dataset = test_dataset.batch(batch_size)
 batched_test_dataset = batched_test_dataset.prefetch(tf.data.experimental.AUTOTUNE)
 early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3)
 save_checkpoints = tf.keras.callbacks.ModelCheckpoint(
 '/kaggle/working/weights.{epoch:02d}-{val_loss:.2f}.hdf5',
save_freq='epoch', period=4)
 lr_callback = ktu.LRSchedulers.FineTuningLR(
 lr_start=1e-5, lr_max=5e-5 * strategy.num_replicas_in_sync, lr_min=1e-5,
lr_rampup_epochs=5, lr_sustain_epochs=0, lr_exp_decay=0.8, verbose=1 )<train_model>
model = EfficientNet.from_name_2("efficientnet-b5", num_classes=186, in_channels=1)
 model.load_state_dict(torch.load("/kaggle/input/bengaliai-trained-models/model_b5_28.pth"))
model = model.to(device=DEVICE, dtype=DTYPE)
 model = model.eval()
with torch.no_grad() :
for test_id, X in test_loader:
test_id = test_id.numpy()
X = X.to(device=DEVICE, dtype=DTYPE)
 y_pred = model(X)
 y_pred = torch.sigmoid(y_pred ).cpu().detach().numpy() * 0.9638
for i, pred in list(zip(test_id, y_pred)) :
if i in preds:
preds[i] += pred
else:
preds[i] = pred
plt.figure(figsize=(8, 5))
lr_callback.visualize(steps_per_epoch=num_training_samples // batch_size, epochs=epochs )<choose_model_class>
model = EfficientNet.from_name_2("efficientnet-b2", num_classes=186, in_channels=1)
 model.load_state_dict(torch.load("/kaggle/input/bengaliai-trained-models/model_b2_20.pth"))
model = model.to(device=DEVICE, dtype=DTYPE)
 model = model.eval()
with torch.no_grad() :
for test_id, X in test_loader:
test_id = test_id.numpy()
X = X.to(device=DEVICE, dtype=DTYPE)
 y_pred = model(X)
 y_pred = torch.sigmoid(y_pred ).cpu().detach().numpy() * 0.9629
for i, pred in list(zip(test_id, y_pred)) :
if i in preds:
preds[i] += pred
else:
preds[i] = pred
def get_model() :
with strategy.scope() :
feature_extractor= efficientnet.EfficientNetB7(
 weights='noisy-student', include_top=False, input_shape=[*image_size, 3])
 feature_extractor.trainable = True
model = tf.keras.Sequential([
feature_extractor,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(flower_categories), activation='softmax', dtype='float32')
 ])
 model.compile(
 optimizer='adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'])
 return model
model = get_model()
model.summary()
history = model.fit(
 batched_train_dataset,
steps_per_epoch=num_training_samples // batch_size,
epochs=epochs,
callbacks=[lr_callback, early_stopping, save_checkpoints],
validation_data=batched_val_dataset,
verbose=2 )<save_to_csv>
!rm -rf test_images_128 test_images_128.zip
print('Generating Submission file...', end=' ')
 test_images_dataset = batched_test_dataset.map(lambda image, idnum: image)
 predictions = np.argmax(model.predict(test_images_dataset), axis=-1)
 test_ids_dataset = batched_test_dataset.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_dataset.batch(num_testing_samples)) ).numpy().astype('U')
 np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')
 print('Done!' )<install_modules>
if not os.path.isfile("test_images_224.zip"):
preprocess_images(INPUT_FILES, "test_images_224.zip", 224)
 with zipfile.ZipFile("test_images_224.zip")as img_zip:
img_zip.extractall("test_images_224")
 test_set = MyDataset("test_images_224/", glob.glob("test_images_224/*.png"))
test_loader = DataLoader(test_set, batch_size=BATCH_SIZE, shuffle=False, num_workers=4 )
!pip install -q efficientnet<set_options>
model = get_model("seresnext50_32x4d", pretrained=False)
 model.features.init_block.conv.conv = nn.Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
 model.output = nn.Linear(in_features=2048, out_features=186, bias=True)
 model.load_state_dict(torch.load("/kaggle/input/bengaliai-trained-models/model_seresnext50_32x4d_16.pth"))
model = model.to(device=DEVICE, dtype=DTYPE)
 model = model.eval()
with torch.no_grad() :
for test_id, X in test_loader:
test_id = test_id.numpy()
X = X.to(device=DEVICE, dtype=DTYPE)
 y_pred = model(X)
 y_pred = torch.sigmoid(y_pred ).cpu().detach().numpy() * 0.9630
for i, pred in list(zip(test_id, y_pred)) :
if i in preds:
preds[i] += pred
else:
preds[i] = pred
print('TensorFlow version', tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<define_variables>
!rm -rf test_images_224 test_images_224.zip
start_time = datetime.now()
print('Time now is', start_time)
 end_training_by_tdelta = timedelta(seconds=8400)
 this_run_file_prefix = start_time.strftime('%Y%m%d_%H%M_')
 print(this_run_file_prefix)
 IMAGE_SIZE = [224, 224]
EPOCHS = 12
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
GCS_PATH_SELECT = {
192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',
224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',
331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',
512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'
}
GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 MOREIMAGES_PATH_SELECT = {
192: '/tfrecords-jpeg-192x192',
224: '/tfrecords-jpeg-224x224',
331: '/tfrecords-jpeg-331x331',
512: '/tfrecords-jpeg-512x512'
}
MOREIMAGES_PATH = MOREIMAGES_PATH_SELECT[IMAGE_SIZE[0]]
IMAGENET_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/imagenet' + MOREIMAGES_PATH + '/*.tfrec')
 INATURELIST_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/inaturalist' + MOREIMAGES_PATH + '/*.tfrec')
 OPENIMAGE_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/openimage' + MOREIMAGES_PATH + '/*.tfrec')
 OXFORD_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/oxford_102' + MOREIMAGES_PATH + '/*.tfrec')
 TENSORFLOW_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/tf_flowers' + MOREIMAGES_PATH + '/*.tfrec')
 ADDITIONAL_TRAINING_FILENAMES = IMAGENET_FILES + INATURELIST_FILES + OPENIMAGE_FILES + OXFORD_FILES + TENSORFLOW_FILES
print('----')
 TRAINING_FILENAMES = TRAINING_FILENAMES + ADDITIONAL_TRAINING_FILENAMES + VALIDATION_FILENAMES
CLASSES = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle',
'snapdragon', "colt's foot", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', 'balloon flower', 'giant white arum lily',
'fire lily', 'pincushion flower', 'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', 'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william',
'carnation', 'garden phlox', 'love in the mist', 'cosmos', 'alpine sea holly', 'ruby-lipped cattleya', 'cape flower', 'great masterwort', 'siam tulip', 'lenten rose',
'barberton daisy', 'daffodil', 'sword lily', 'poinsettia', 'bolero deep blue', 'wallflower', 'marigold', 'buttercup', 'daisy', 'common dandelion',
'petunia', 'wild pansy', 'primula', 'sunflower', 'lilac hibiscus', 'bishop of llandaff', 'gaura', 'geranium', 'orange dahlia', 'pink-yellow dahlia',
'cautleya spicata', 'japanese anemone', 'black-eyed susan', 'silverbush', 'californian poppy', 'osteospermum', 'spring crocus', 'iris', 'windflower', 'tree poppy',
'gazania', 'azalea', 'water lily', 'rose', 'thorn apple', 'morning glory', 'passion flower', 'lotus', 'toad lily', 'anthurium',
'frangipani', 'clematis', 'hibiscus', 'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', 'watercress', 'canna lily',
'hippeastrum ', 'bee balm', 'pink quill', 'foxglove', 'bougainvillea', 'camellia', 'mallow', 'mexican petunia', 'bromelia', 'blanket flower',
'trumpet creeper', 'blackberry lily', 'common tulip', 'wild rose']<init_hyperparams>
submission = []
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = LR_START
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY = 0.80
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr = LR_START +(epoch *(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS)
 elif epoch <(LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS):
lr = LR_MAX
else:
lr = LR_MIN +(LR_MAX - LR_MIN)* LR_EXP_DECAY **(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)
 return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)
 rng = [i for i in range(30)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print(y )<categorify>
for i, pred in preds.items() :
y1 = np.argmax(pred[:168])
 y2 = np.argmax(pred[168:179])
 y3 = np.argmax(pred[179:])
 submission.append(( i, "Test_" + str(i)+ "_grapheme_root", y1))
submission.append(( i, "Test_" + str(i)+ "_vowel_diacritic", y2))
submission.append(( i, "Test_" + str(i)+ "_consonant_diacritic", y3))
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>
submission = pd.DataFrame(submission, columns=["id", "row_id", "target"] ).sort_values(by=["id", "row_id"] ).reset_index() [["row_id", "target"]]
submission.to_csv("submission.csv", index=False )