{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport tensorflow as tf\nimport math, re, os\nimport matplotlib.pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\nAUTO = tf.data.experimental.AUTOTUNE\nimport tensorflow.keras.backend as K","metadata":{"execution":{"iopub.status.busy":"2021-12-04T08:57:51.397106Z","iopub.execute_input":"2021-12-04T08:57:51.397526Z","iopub.status.idle":"2021-12-04T08:57:51.403984Z","shell.execute_reply.started":"2021-12-04T08:57:51.397488Z","shell.execute_reply":"2021-12-04T08:57:51.403160Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.__version__","metadata":{"execution":{"iopub.status.busy":"2021-12-04T08:57:52.540234Z","iopub.execute_input":"2021-12-04T08:57:52.540771Z","iopub.status.idle":"2021-12-04T08:57:52.546279Z","shell.execute_reply.started":"2021-12-04T08:57:52.540734Z","shell.execute_reply":"2021-12-04T08:57:52.545478Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy()","metadata":{"execution":{"iopub.status.busy":"2021-12-04T08:57:53.340372Z","iopub.execute_input":"2021-12-04T08:57:53.341053Z","iopub.status.idle":"2021-12-04T08:57:58.960560Z","shell.execute_reply.started":"2021-12-04T08:57:53.341020Z","shell.execute_reply":"2021-12-04T08:57:58.959861Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tpu.master(),strategy.num_replicas_in_sync\nGCS_DS_PATH = KaggleDatasets().get_gcs_path()","metadata":{"execution":{"iopub.status.busy":"2021-12-04T08:57:58.962199Z","iopub.execute_input":"2021-12-04T08:57:58.962469Z","iopub.status.idle":"2021-12-04T08:57:59.353583Z","shell.execute_reply.started":"2021-12-04T08:57:58.962442Z","shell.execute_reply":"2021-12-04T08:57:59.352855Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Image_size = [512,512]\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nGCS_PATH_SELECT = { \n    192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',\n    224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',\n    331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',\n    512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'\n}\nGCS_PATH = GCS_PATH_SELECT[Image_size[0]]","metadata":{"execution":{"iopub.status.busy":"2021-12-04T08:57:59.354840Z","iopub.execute_input":"2021-12-04T08:57:59.355048Z","iopub.status.idle":"2021-12-04T08:57:59.360073Z","shell.execute_reply.started":"2021-12-04T08:57:59.355024Z","shell.execute_reply":"2021-12-04T08:57:59.359264Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')","metadata":{"execution":{"iopub.status.busy":"2021-12-04T08:57:59.362776Z","iopub.execute_input":"2021-12-04T08:57:59.363480Z","iopub.status.idle":"2021-12-04T08:57:59.579374Z","shell.execute_reply.started":"2021-12-04T08:57:59.363386Z","shell.execute_reply":"2021-12-04T08:57:59.578585Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CLASSES = ['pink primrose',    'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea',     'wild geranium',     'tiger lily',           'moon orchid',              'bird of paradise', 'monkshood',        'globe thistle',         # 00 - 09\n           'snapdragon',       \"colt's foot\",               'king protea',      'spear thistle', 'yellow iris',       'globe-flower',         'purple coneflower',        'peruvian lily',    'balloon flower',   'giant white arum lily', # 10 - 19\n           'fire lily',        'pincushion flower',         'fritillary',       'red ginger',    'grape hyacinth',    'corn poppy',           'prince of wales feathers', 'stemless gentian', 'artichoke',        'sweet william',         # 20 - 29\n           'carnation',        'garden phlox',              'love in the mist', 'cosmos',        'alpine sea holly',  'ruby-lipped cattleya', 'cape flower',              'great masterwort', 'siam tulip',       'lenten rose',           # 30 - 39\n           'barberton daisy',  'daffodil',                  'sword lily',       'poinsettia',    'bolero deep blue',  'wallflower',           'marigold',                 'buttercup',        'daisy',            'common dandelion',      # 40 - 49\n           'petunia',          'wild pansy',                'primula',          'sunflower',     'lilac hibiscus',    'bishop of llandaff',   'gaura',                    'geranium',         'orange dahlia',    'pink-yellow dahlia',    # 50 - 59\n           'cautleya spicata', 'japanese anemone',          'black-eyed susan', 'silverbush',    'californian poppy', 'osteospermum',         'spring crocus',            'iris',             'windflower',       'tree poppy',            # 60 - 69\n           'gazania',          'azalea',                    'water lily',       'rose',          'thorn apple',       'morning glory',        'passion flower',           'lotus',            'toad lily',        'anthurium',             # 70 - 79\n           'frangipani',       'clematis',                  'hibiscus',         'columbine',     'desert-rose',       'tree mallow',          'magnolia',                 'cyclamen ',        'watercress',       'canna lily',            # 80 - 89\n           'hippeastrum ',     'bee balm',                  'pink quill',       'foxglove',      'bougainvillea',     'camellia',             'mallow',                   'mexican petunia',  'bromelia',         'blanket flower',        # 90 - 99\n           'trumpet creeper',  'blackberry lily',           'common tulip',     'wild rose']                                                                                                                                               # 100 - 102","metadata":{"execution":{"iopub.status.busy":"2021-12-04T08:57:59.580553Z","iopub.execute_input":"2021-12-04T08:57:59.581076Z","iopub.status.idle":"2021-12-04T08:57:59.589900Z","shell.execute_reply.started":"2021-12-04T08:57:59.581042Z","shell.execute_reply":"2021-12-04T08:57:59.589262Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import random\nheight = 512\nwidth = 512\nCHANNELS = 3","metadata":{"execution":{"iopub.status.busy":"2021-12-04T08:57:59.591280Z","iopub.execute_input":"2021-12-04T08:57:59.591920Z","iopub.status.idle":"2021-12-04T08:57:59.606393Z","shell.execute_reply.started":"2021-12-04T08:57:59.591887Z","shell.execute_reply":"2021-12-04T08:57:59.605607Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def transform_rotation(image,height,rotation):\n    dim = height\n    dim_ = dim%2\n    rotation = rotation * tf.random.uniform([1],dtype = 'float32')\n    rotation = math.pi *rotation /100\n    c1 = tf.math.cos(rotation)\n    c1 = tf.math.cos(rotation)\n    s1 = tf.math.sin(rotation)\n    one = tf.constant([1],dtype='float32')\n    zero = tf.constant([0],dtype='float32')\n    rotation_matrix = tf.reshape(tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3])\n    x = tf.repeat( tf.range(dim//2,-dim//2,-1),dim )\n    y = tf.tile( tf.range(-dim//2,dim//2),[dim] )\n    z = tf.ones([dim*dim],dtype='int32')\n    idx = tf.stack( [x,y,z] )\n    idx2 = tf.keras.backend.dot(rotation_matrix,tf.cast(idx,dtype='float32'))\n    idx2 = tf.keras.backend.cast(idx2,dtype='int32')\n    idx2 = tf.keras.backend.clip(idx2,-dim//2+dim_+1,dim//2)\n    idx3 = tf.stack( [dim//2-idx2[0,], dim//2-1+idx2[1,]] )\n    d = tf.gather_nd(image, tf.transpose(idx3))\n    return tf.reshape(d,[dim,dim,3])","metadata":{"execution":{"iopub.status.busy":"2021-12-04T08:57:59.607579Z","iopub.execute_input":"2021-12-04T08:57:59.607826Z","iopub.status.idle":"2021-12-04T08:57:59.619489Z","shell.execute_reply.started":"2021-12-04T08:57:59.607802Z","shell.execute_reply":"2021-12-04T08:57:59.618758Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def erase(img, max_height=80, max_width=80, min_height=40, min_width=40, img_size=512):\n    h, w, c = img_size, img_size, 3\n    erase_height = tf.random.uniform(shape=[], minval=min_height, maxval=max_height, dtype=tf.int32)\n    erase_width = tf.random.uniform(shape=[], minval=min_width, maxval=max_width, dtype=tf.int32)\n\n    erase_area = tf.zeros(shape=[erase_height, erase_width, c])\n    erase_area = tf.cast(erase_area, tf.uint8)\n\n    pad_h = h - erase_height\n    pad_top = tf.random.uniform(shape=[], minval=0, maxval=pad_h, dtype=tf.int32)\n    pad_bottom = pad_h - pad_top\n\n    pad_w = w - erase_width\n    pad_left = tf.random.uniform(shape=[], minval=0, maxval=pad_w, dtype=tf.int32)\n    pad_right = pad_w - pad_left\n\n    erase_mask = tf.pad([erase_area], [[0,0],[pad_top, pad_bottom], [pad_left, pad_right], [0,0]], constant_values=1)\n    erase_mask = tf.squeeze(erase_mask, axis=0)\n    erased_img = tf.multiply(tf.cast(img,tf.float32), tf.cast(erase_mask, tf.float32))\n    return tf.cast(erased_img, img.dtype)\ndef transform_shear(image, height, shear):\n    # input image - is one image of size [dim,dim,3] not a batch of [b,dim,dim,3]\n    # output - image randomly sheared\n    DIM = height\n    XDIM = DIM%2 #fix for size 331\n    \n    shear = shear * tf.random.uniform([1],dtype='float32')\n    shear = math.pi * shear / 180.\n        \n    # SHEAR MATRIX\n    one = tf.constant([1],dtype='float32')\n    zero = tf.constant([0],dtype='float32')\n    c2 = tf.math.cos(shear)\n    s2 = tf.math.sin(shear)\n    shear_matrix = tf.reshape(tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3])    \n\n    # LIST DESTINATION PIXEL INDICES\n    x = tf.repeat( tf.range(DIM//2,-DIM//2,-1), DIM )\n    y = tf.tile( tf.range(-DIM//2,DIM//2),[DIM] )\n    z = tf.ones([DIM*DIM],dtype='int32')\n    idx = tf.stack( [x,y,z] )\n    \n    # ROTATE DESTINATION PIXELS ONTO ORIGIN PIXELS\n    idx2 = K.dot(shear_matrix,tf.cast(idx,dtype='float32'))\n    idx2 = K.cast(idx2,dtype='int32')\n    idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2)\n    \n    # FIND ORIGIN PIXEL VALUES \n    idx3 = tf.stack( [DIM//2-idx2[0,], DIM//2-1+idx2[1,]] )\n    d = tf.gather_nd(image, tf.transpose(idx3))\n        \n    return tf.reshape(d,[DIM,DIM,3])\ndef random_blockout(img, max_holes=8, min_holes=4,\n                    p=0.75, img_size=512):\n    prob=random.random()\n    if prob<p:\n        h, w, c = img_size, img_size, 3\n        num_roles = random.randint(min_holes, max_holes)\n        \n        for n in range(num_roles):\n            img = erase(img)\n            \n        return img\n    else:\n        return tf.cast(img, img.dtype)\ndef transform_shift(image, height, h_shift, w_shift):\n    # input image - is one image of size [dim,dim,3] not a batch of [b,dim,dim,3]\n    # output - image randomly shifted\n    DIM = height\n    XDIM = DIM%2 #fix for size 331\n    \n    height_shift = h_shift * tf.random.uniform([1],dtype='float32') \n    width_shift = w_shift * tf.random.uniform([1],dtype='float32') \n    one = tf.constant([1],dtype='float32')\n    zero = tf.constant([0],dtype='float32')\n        \n    # SHIFT MATRIX\n    shift_matrix = tf.reshape(tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3])\n\n    # LIST DESTINATION PIXEL INDICES\n    x = tf.repeat( tf.range(DIM//2,-DIM//2,-1), DIM )\n    y = tf.tile( tf.range(-DIM//2,DIM//2),[DIM] )\n    z = tf.ones([DIM*DIM],dtype='int32')\n    idx = tf.stack( [x,y,z] )\n    \n    # ROTATE DESTINATION PIXELS ONTO ORIGIN PIXELS\n    idx2 = K.dot(shift_matrix,tf.cast(idx,dtype='float32'))\n    idx2 = K.cast(idx2,dtype='int32')\n    idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2)\n    \n    # FIND ORIGIN PIXEL VALUES \n    idx3 = tf.stack( [DIM//2-idx2[0,], DIM//2-1+idx2[1,]] )\n    d = tf.gather_nd(image, tf.transpose(idx3))\n        \n    return tf.reshape(d,[DIM,DIM,3])\n    \ndef data_augment(image, label):\n    seed = (0,0)\n    p_rotation = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    p_spatial = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    p_rotate = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    p_pixel = tf.random.uniform([], 0, 1.0, dtype=tf.float32)    \n    p_shear = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    p_shift = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    p_crop = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    p_blackout = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    \n    # Blackout\n    if p_blackout >=0.8:\n        image = random_blockout(image)\n    \n    # Flips\n    if p_spatial >= .2:\n        image = tf.image.stateless_random_flip_left_right(image, seed)\n        image = tf.image.stateless_random_flip_up_down(image, seed)\n        \n    # Rotates\n    if p_rotate > .75:\n        image = tf.image.rot90(image, k=3) # rotate 270º\n    elif p_rotate > .5:\n        image = tf.image.rot90(image, k=2) # rotate 180º\n    elif p_rotate > .25:\n        image = tf.image.rot90(image, k=1) # rotate 90º\n    \n    if p_rotation >= .3: # Rotation\n        image = transform_rotation(image, height=height, rotation=45.)\n    if p_shift >= .3: # Shift\n        image = transform_shift(image, height=height, h_shift=15., w_shift=15.)\n    if p_shear >= .3: # Shear\n        image = transform_shear(image, height=height, shear=20.)\n        \n    # Crops\n    if p_crop > .3:\n        crop_size = tf.random.uniform([], int(height*.7), height, dtype=tf.int32)\n        image = tf.image.random_crop(image, size=[crop_size, crop_size, CHANNELS])\n    elif p_crop > .7:\n        if p_crop > .9:\n            image = tf.image.central_crop(image, central_fraction=.7)\n        elif p_crop > .8:\n            image = tf.image.central_crop(image, central_fraction=.8)\n        else:\n            image = tf.image.central_crop(image, central_fraction=.9)\n            \n    image = tf.image.resize(image, size=[height, width])\n        \n    # Pixel-level transforms\n    if p_pixel >= .2:\n        if p_pixel >= .7:\n            image = tf.image.stateless_random_saturation(image, lower=0.2, upper=0.8, seed=seed)\n        elif p_pixel >= .5:\n            image = tf.image.stateless_random_contrast(image, lower=.3, upper=0.7, seed=seed)\n        elif p_pixel >= .3:\n            image = tf.image.stateless_random_brightness(image, max_delta=.7, seed=seed)\n        else:\n            image = tf.image.adjust_gamma(image, gamma=.6)\n\n    return image, label\n\n\ndef decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [*Image_size, 3]) # explicit size needed for TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"class\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    label = tf.cast(example['class'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"id\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['id']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\n\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_validation_dataset(ordered=False):\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))\nVALIDATION_STEPS = -(-NUM_VALIDATION_IMAGES // BATCH_SIZE)","metadata":{"execution":{"iopub.status.busy":"2021-12-04T08:57:59.620804Z","iopub.execute_input":"2021-12-04T08:57:59.621109Z","iopub.status.idle":"2021-12-04T08:57:59.682896Z","shell.execute_reply.started":"2021-12-04T08:57:59.621085Z","shell.execute_reply":"2021-12-04T08:57:59.681869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    pretrained_model = tf.keras.applications.InceptionV3(\n        weights='imagenet',\n        include_top=False ,\n        input_shape=[*Image_size, 3]\n    )\n    pretrained_model.trainable = True\n    \n    model1 = tf.keras.Sequential([\n        pretrained_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        #tf.keras.layers.BatchNormalization(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])","metadata":{"execution":{"iopub.status.busy":"2021-12-04T08:58:37.706813Z","iopub.execute_input":"2021-12-04T08:58:37.707399Z","iopub.status.idle":"2021-12-04T08:58:55.623470Z","shell.execute_reply.started":"2021-12-04T08:58:37.707356Z","shell.execute_reply":"2021-12-04T08:58:55.622695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model1.compile(\n    optimizer=tf.keras.optimizers.Adam(lr=0.0001),\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy'],\n)","metadata":{"execution":{"iopub.status.busy":"2021-12-04T08:59:18.759388Z","iopub.execute_input":"2021-12-04T08:59:18.759952Z","iopub.status.idle":"2021-12-04T08:59:18.804312Z","shell.execute_reply.started":"2021-12-04T08:59:18.759906Z","shell.execute_reply":"2021-12-04T08:59:18.803362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=4, restore_best_weights=True)","metadata":{"execution":{"iopub.status.busy":"2021-12-04T08:59:19.718154Z","iopub.execute_input":"2021-12-04T08:59:19.718414Z","iopub.status.idle":"2021-12-04T08:59:19.723200Z","shell.execute_reply.started":"2021-12-04T08:59:19.718389Z","shell.execute_reply":"2021-12-04T08:59:19.721957Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history1 = model1.fit(get_training_dataset(),\n                    validation_data=get_validation_dataset(),                                      \n                    epochs= 30, \n                    steps_per_epoch=STEPS_PER_EPOCH,use_multiprocessing=True,workers=4)","metadata":{"execution":{"iopub.status.busy":"2021-12-04T08:59:20.878350Z","iopub.execute_input":"2021-12-04T08:59:20.878851Z","iopub.status.idle":"2021-12-04T09:27:30.435356Z","shell.execute_reply.started":"2021-12-04T08:59:20.878817Z","shell.execute_reply":"2021-12-04T09:27:30.434365Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history1.history['loss'])\nplt.plot(history1.history['val_loss'])\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-12-04T09:28:10.347999Z","iopub.execute_input":"2021-12-04T09:28:10.348876Z","iopub.status.idle":"2021-12-04T09:28:10.579365Z","shell.execute_reply.started":"2021-12-04T09:28:10.348783Z","shell.execute_reply":"2021-12-04T09:28:10.578446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history1.history['sparse_categorical_accuracy'])\nplt.plot(history1.history['val_sparse_categorical_accuracy'])\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-12-04T09:28:40.327884Z","iopub.execute_input":"2021-12-04T09:28:40.328173Z","iopub.status.idle":"2021-12-04T09:28:40.525353Z","shell.execute_reply.started":"2021-12-04T09:28:40.328147Z","shell.execute_reply":"2021-12-04T09:28:40.524602Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# with strategy.scope():\n#     pretrained_model_2 = tf.keras.applications.DenseNet201(\n#         weights='imagenet',\n#         include_top=False ,\n#         input_shape=[*Image_size, 3]\n#     )\n#     pretrained_model_2.trainable = True\n    \n#     model2 = tf.keras.Sequential([\n#         # To a base pretrained on ImageNet to extract features from images...\n#         pretrained_model_2,\n#         tf.keras.layers.GlobalAveragePooling2D(),\n#         tf.keras.layers.BatchNormalization(),\n#         tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n#     ])\n# model2.compile(\n#     optimizer=tf.keras.optimizers.Adam(lr=0.0001),\n#     loss = 'sparse_categorical_crossentropy',\n#     metrics=['sparse_categorical_accuracy'],\n# )\n","metadata":{"execution":{"iopub.status.busy":"2021-08-25T05:12:17.627144Z","iopub.execute_input":"2021-08-25T05:12:17.627679Z","iopub.status.idle":"2021-08-25T05:12:52.698363Z","shell.execute_reply.started":"2021-08-25T05:12:17.627644Z","shell.execute_reply":"2021-08-25T05:12:52.697653Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# history2 = model2.fit(get_training_dataset(),\n#                     validation_data=get_validation_dataset(),                                      \n#                     epochs= 30, \n#                     steps_per_epoch=STEPS_PER_EPOCH)","metadata":{"execution":{"iopub.status.busy":"2021-08-25T05:12:56.352018Z","iopub.execute_input":"2021-08-25T05:12:56.352397Z","iopub.status.idle":"2021-08-25T05:56:15.174857Z","shell.execute_reply.started":"2021-08-25T05:12:56.352366Z","shell.execute_reply":"2021-08-25T05:56:15.174127Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True)\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities_1 = model1.predict(test_images_ds)\n#probabilities_2 = model2.predict(test_images_ds)\n#probabilities = (probabilities_1 + probabilities_2)/2\npredictions = np.argmax(probabilities_1, axis=-1)\nprint(predictions)\n","metadata":{"execution":{"iopub.status.busy":"2021-12-04T09:28:48.628306Z","iopub.execute_input":"2021-12-04T09:28:48.628826Z","iopub.status.idle":"2021-12-04T09:29:28.429629Z","shell.execute_reply.started":"2021-12-04T09:28:48.628784Z","shell.execute_reply":"2021-12-04T09:29:28.428768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')","metadata":{"execution":{"iopub.status.busy":"2021-12-04T09:29:28.431310Z","iopub.execute_input":"2021-12-04T09:29:28.431544Z","iopub.status.idle":"2021-12-04T09:29:31.077032Z","shell.execute_reply.started":"2021-12-04T09:29:28.431517Z","shell.execute_reply":"2021-12-04T09:29:31.076165Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.savetxt(\n    'submission.csv',\n    np.rec.fromarrays([test_ids, predictions]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n)","metadata":{"execution":{"iopub.status.busy":"2021-12-04T09:29:31.078520Z","iopub.execute_input":"2021-12-04T09:29:31.078848Z","iopub.status.idle":"2021-12-04T09:29:31.139917Z","shell.execute_reply.started":"2021-12-04T09:29:31.078809Z","shell.execute_reply":"2021-12-04T09:29:31.139165Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!head submission.csv","metadata":{"execution":{"iopub.status.busy":"2021-12-04T09:29:31.141484Z","iopub.execute_input":"2021-12-04T09:29:31.143875Z","iopub.status.idle":"2021-12-04T09:29:31.933818Z","shell.execute_reply.started":"2021-12-04T09:29:31.143831Z","shell.execute_reply":"2021-12-04T09:29:31.932970Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}