{"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":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-11-03T16:29:25.270948Z","iopub.execute_input":"2023-11-03T16:29:25.27136Z","iopub.status.idle":"2023-11-03T16:29:25.807767Z","shell.execute_reply.started":"2023-11-03T16:29:25.271324Z","shell.execute_reply":"2023-11-03T16:29:25.80665Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import math, re, os\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\n\nfrom keras import layers\nfrom keras.layers import RandomRotation,RandomZoom,RandomContrast,Conv2D,AveragePooling2D,MaxPooling2D,BatchNormalization,Input,Dense,Dropout,Flatten,GlobalAveragePooling2D\nfrom keras.models import Sequential,Model\nfrom keras.callbacks import EarlyStopping\n\nfrom sklearn.metrics import precision_score,recall_score\n\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"execution":{"iopub.status.busy":"2023-11-03T16:31:33.269978Z","iopub.execute_input":"2023-11-03T16:31:33.27067Z","iopub.status.idle":"2023-11-03T16:31:43.111625Z","shell.execute_reply.started":"2023-11-03T16:31:33.270632Z","shell.execute_reply":"2023-11-03T16:31:43.11036Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver() \n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\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() \n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2023-11-03T16:32:02.204207Z","iopub.execute_input":"2023-11-03T16:32:02.204635Z","iopub.status.idle":"2023-11-03T16:32:02.212623Z","shell.execute_reply.started":"2023-11-03T16:32:02.204604Z","shell.execute_reply":"2023-11-03T16:32:02.211392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from kaggle_datasets import KaggleDatasets\n\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\nprint(GCS_DS_PATH)","metadata":{"execution":{"iopub.status.busy":"2023-11-03T16:33:08.136103Z","iopub.execute_input":"2023-11-03T16:33:08.1369Z","iopub.status.idle":"2023-11-03T16:33:08.723506Z","shell.execute_reply.started":"2023-11-03T16:33:08.136859Z","shell.execute_reply":"2023-11-03T16:33:08.722416Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = [512, 512]\nGCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-512x512'\nAUTO = tf.data.experimental.AUTOTUNE\n\nTRAINING_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') \n\nCLASSES = ['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\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","metadata":{"execution":{"iopub.status.busy":"2023-11-03T16:33:40.131308Z","iopub.execute_input":"2023-11-03T16:33:40.131704Z","iopub.status.idle":"2023-11-03T16:33:40.376084Z","shell.execute_reply.started":"2023-11-03T16:33:40.131674Z","shell.execute_reply":"2023-11-03T16:33:40.375011Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def data_augment(image, label):\n    # Thanks to the dataset.prefetch(AUTO)\n    # statement in the next function (below), this happens essentially\n    # for free on TPU. Data pipeline code is executed on the \"CPU\"\n    # part of the TPU while the TPU itself is computing gradients.\n    image = tf.image.random_flip_left_right(image)\n    #image = tf.image.random_saturation(image, 0, 2)\n    return image, label   \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)\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)\n    return dataset\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec\n    # 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)\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","metadata":{"execution":{"iopub.status.busy":"2023-11-03T16:34:54.136433Z","iopub.execute_input":"2023-11-03T16:34:54.137351Z","iopub.status.idle":"2023-11-03T16:34:54.150752Z","shell.execute_reply.started":"2023-11-03T16:34:54.137307Z","shell.execute_reply":"2023-11-03T16:34:54.14965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nds_train = get_training_dataset()\nds_valid = get_validation_dataset()\nds_test = get_test_dataset()\n\nprint(\"Training:\", ds_train)\nprint (\"Validation:\", ds_valid)\nprint(\"Test:\", ds_test)","metadata":{"execution":{"iopub.status.busy":"2023-11-03T16:35:09.766818Z","iopub.execute_input":"2023-11-03T16:35:09.76723Z","iopub.status.idle":"2023-11-03T16:35:10.532686Z","shell.execute_reply.started":"2023-11-03T16:35:09.767196Z","shell.execute_reply":"2023-11-03T16:35:10.530362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.set_printoptions(threshold=15, linewidth=80)\n\nprint(\"Training data shapes:\")\nfor image, label in ds_train.take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Training data label examples:\", label.numpy())","metadata":{"execution":{"iopub.status.busy":"2023-11-03T16:35:26.724166Z","iopub.execute_input":"2023-11-03T16:35:26.724623Z","iopub.status.idle":"2023-11-03T16:35:36.160893Z","shell.execute_reply.started":"2023-11-03T16:35:26.724591Z","shell.execute_reply":"2023-11-03T16:35:36.159634Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Test data shapes:\")\nfor image, idnum in ds_test.take(3):\n    print(image.numpy().shape, idnum.numpy().shape)\nprint(\"Test data IDs:\", idnum.numpy().astype('U'))","metadata":{"execution":{"iopub.status.busy":"2023-11-03T16:35:50.851374Z","iopub.execute_input":"2023-11-03T16:35:50.85184Z","iopub.status.idle":"2023-11-03T16:35:52.569098Z","shell.execute_reply.started":"2023-11-03T16:35:50.851801Z","shell.execute_reply":"2023-11-03T16:35:52.561205Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shape=(512,512,3)\nepochs=1\nbatch_size=2\n\n#Our Callback\nmy_callback=EarlyStopping(\n    monitor=\"val_loss\", # value to be monitored\n    patience=5, # steps of waiting to take action\n    verbose=1, # shows action of callback\n    mode=\"min\", # if decreasing of value to be monitored stops, callback will take action \n)","metadata":{"execution":{"iopub.status.busy":"2023-11-03T16:36:17.850654Z","iopub.execute_input":"2023-11-03T16:36:17.851059Z","iopub.status.idle":"2023-11-03T16:36:17.858377Z","shell.execute_reply.started":"2023-11-03T16:36:17.851029Z","shell.execute_reply":"2023-11-03T16:36:17.856512Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"block1,block2,block3=Sequential(),Sequential(),Sequential()\n\nblock1.add(Input(shape))\nblock1.add(RandomRotation(factor=(-0.5,0.5),interpolation=\"nearest\"))\nblock1.add(RandomZoom(height_factor=(-0.3, 0.3)))\nblock1.add(RandomContrast(factor=.3))\nblock1.add(BatchNormalization())\n\nblock2.add(Conv2D(64, (3, 3), activation=\"relu\"))\nblock2.add(MaxPooling2D(2, 2))\nblock2.add(Dropout(.2))\nblock2.add(Conv2D(64, (3, 3), activation=\"relu\"))\nblock2.add(AveragePooling2D(2, 2))\n#block2.add(Dropout(.2))\nblock2.add(BatchNormalization())\n           \nblock3.add(Conv2D(64, (3, 3), activation='relu'))\nblock3.add(MaxPooling2D(2, 2))\nblock3.add(MaxPooling2D(2, 2))\n#block3.add(BatchNormalization())\nblock3.add(Flatten())\n#block3.add(GlobalAveragePooling2D())\nblock3.add(Dense(len(CLASSES),activation=\"softmax\"))\n\n# All models are callable ,treat like layers. To merge them by invoking a model on an Input layer we get an \n#output layer. This way is easy one rather than others\ninputs=Input(shape)\nx=block1(inputs)\nx=block2(x)\noutputs=block3(x)\nmodel=Model(inputs=inputs,outputs=outputs)\n\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'])\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-11-03T16:36:46.289067Z","iopub.execute_input":"2023-11-03T16:36:46.28947Z","iopub.status.idle":"2023-11-03T16:36:46.859267Z","shell.execute_reply.started":"2023-11-03T16:36:46.289439Z","shell.execute_reply":"2023-11-03T16:36:46.858305Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.evaluate(ds_test)","metadata":{"execution":{"iopub.status.busy":"2023-11-03T16:39:28.66694Z","iopub.status.idle":"2023-11-03T16:39:28.667651Z","shell.execute_reply.started":"2023-11-03T16:39:28.667425Z","shell.execute_reply":"2023-11-03T16:39:28.667447Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(ds_train,\n           validation_data=ds_valid,\n           epochs=1,\n           steps_per_epoch=NUM_TRAINING_IMAGES//batch_size,\n            callbacks=[my_callback],)","metadata":{"execution":{"iopub.status.busy":"2023-11-03T16:40:02.988137Z","iopub.execute_input":"2023-11-03T16:40:02.98858Z","iopub.status.idle":"2023-11-03T16:40:47.131879Z","shell.execute_reply.started":"2023-11-03T16:40:02.988549Z","shell.execute_reply":"2023-11-03T16:40:47.129932Z"},"trusted":true},"execution_count":null,"outputs":[]}]}