{"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 math, re, os\nimport numpy as np\nimport tensorflow as tf\nimport pandas as pd\nimport plotly.graph_objects as go\nimport plotly.express as px\nfrom plotly.subplots import make_subplots\nfrom tensorflow.keras.applications.densenet import DenseNet201","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:43:42.331310Z","iopub.execute_input":"2022-06-01T17:43:42.331693Z","iopub.status.idle":"2022-06-01T17:43:50.562535Z","shell.execute_reply.started":"2022-06-01T17:43:42.331592Z","shell.execute_reply":"2022-06-01T17:43:50.561539Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"_template = dict(layout=go.Layout(font=dict(family='Times New Roman', size=13), height=400, width=400))","metadata":{"execution":{"iopub.status.busy":"2022-06-01T18:26:20.849984Z","iopub.execute_input":"2022-06-01T18:26:20.850415Z","iopub.status.idle":"2022-06-01T18:26:20.858285Z","shell.execute_reply.started":"2022-06-01T18:26:20.850367Z","shell.execute_reply":"2022-06-01T18:26:20.857334Z"},"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":"2022-06-01T17:44:05.381149Z","iopub.execute_input":"2022-06-01T17:44:05.381473Z","iopub.status.idle":"2022-06-01T17:44:11.374440Z","shell.execute_reply.started":"2022-06-01T17:44:05.381440Z","shell.execute_reply":"2022-06-01T17:44:11.373501Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from kaggle_datasets import KaggleDatasets\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\nprint(GCS_DS_PATH) ","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:43:51.175144Z","iopub.execute_input":"2022-06-01T17:43:51.175456Z","iopub.status.idle":"2022-06-01T17:43:51.633807Z","shell.execute_reply.started":"2022-06-01T17:43:51.175421Z","shell.execute_reply":"2022-06-01T17:43:51.632827Z"},"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 - 1\n\n","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:43:52.371250Z","iopub.execute_input":"2022-06-01T17:43:52.371561Z","iopub.status.idle":"2022-06-01T17:43:52.622395Z","shell.execute_reply.started":"2022-06-01T17:43:52.371532Z","shell.execute_reply":"2022-06-01T17:43:52.621682Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0  \n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) \n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), \n        \"class\": tf.io.FixedLenFeature([], tf.int64),  \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 \n\ndef read_unlabel_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        'image':tf.io.FixedLenFeature([], tf.string),\n        'id':tf.io.FixedLenFeature([], tf.string),\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\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    \n    ignore_order = tf.data.Options()\n    \n    if not ordered:\n        ignore_order.experimental_deterministic = False\n    \n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO )\n    dataset = dataset.with_options(ignore_order)\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabel_tfrecord, num_parallel_calls=AUTO)\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:43:55.585352Z","iopub.execute_input":"2022-06-01T17:43:55.585647Z","iopub.status.idle":"2022-06-01T17:43:55.597190Z","shell.execute_reply.started":"2022-06-01T17:43:55.585617Z","shell.execute_reply":"2022-06-01T17:43:55.596225Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def data_augment(image, label):\n    image = tf.image.random_flip_left_right(image)\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()\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)\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    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":"2022-06-01T17:43:56.040308Z","iopub.execute_input":"2022-06-01T17:43:56.040937Z","iopub.status.idle":"2022-06-01T17:43:56.056769Z","shell.execute_reply.started":"2022-06-01T17:43:56.040888Z","shell.execute_reply":"2022-06-01T17:43:56.055689Z"},"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 Data : ', ds_train)\nprint('Validaiton Data : ', ds_valid)\nprint('Test Data : ', ds_test)","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:44:12.675557Z","iopub.execute_input":"2022-06-01T17:44:12.675872Z","iopub.status.idle":"2022-06-01T17:44:13.008951Z","shell.execute_reply.started":"2022-06-01T17:44:12.675836Z","shell.execute_reply":"2022-06-01T17:44:13.007964Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import plotly.express as px\nfig = px.imshow(image[0])\nfig.update_xaxes(showticklabels=False)\nfig.update_yaxes(showticklabels=False)\nfig.update_layout(template = _template, hovermode=None, xaxis=dict(title=CLASSES[label[0]]))\nfig.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    base_model = DenseNet201(weights='imagenet', include_top=False, pooling='avg', input_shape=(512, 512, 3))\n    base_model.trainable=False\n    model = tf.keras.models.Sequential([\n        base_model, \n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:54:11.249016Z","iopub.execute_input":"2022-06-01T17:54:11.249319Z","iopub.status.idle":"2022-06-01T17:54:48.151544Z","shell.execute_reply.started":"2022-06-01T17:54:11.249290Z","shell.execute_reply":"2022-06-01T17:54:48.150648Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer='nadam', loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:56:13.155771Z","iopub.execute_input":"2022-06-01T17:56:13.156066Z","iopub.status.idle":"2022-06-01T17:56:13.217276Z","shell.execute_reply.started":"2022-06-01T17:56:13.156035Z","shell.execute_reply":"2022-06-01T17:56:13.216406Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EPOCHES = 60\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nhistory = model.fit(ds_train, validation_data=ds_valid, epochs=EPOCHES, steps_per_epoch = STEPS_PER_EPOCH)","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:56:14.114016Z","iopub.execute_input":"2022-06-01T17:56:14.114305Z","iopub.status.idle":"2022-06-01T18:25:45.234160Z","shell.execute_reply.started":"2022-06-01T17:56:14.114275Z","shell.execute_reply":"2022-06-01T18:25:45.233016Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history_df = pd.DataFrame(history.history)\nfig = px.line(history_df.iloc[:, [0, 2]])\nfig.update_layout(template=_template, width=800, xaxis1=dict(title='Epoches'), yaxis1=dict(title='Loss'))\nfig.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-01T18:26:27.484098Z","iopub.execute_input":"2022-06-01T18:26:27.484394Z","iopub.status.idle":"2022-06-01T18:26:27.602272Z","shell.execute_reply.started":"2022-06-01T18:26:27.484353Z","shell.execute_reply":"2022-06-01T18:26:27.601216Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = px.line(history_df.iloc[:, [1, 3]])\nfig.update_layout(template=_template, width=800, xaxis1=dict(title='Epoches'), yaxis1=dict(title='Loss'))\nfig.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-01T18:26:39.045040Z","iopub.execute_input":"2022-06-01T18:26:39.045333Z","iopub.status.idle":"2022-06-01T18:26:39.129345Z","shell.execute_reply.started":"2022-06-01T18:26:39.045306Z","shell.execute_reply":"2022-06-01T18:26:39.128305Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True)\ntest_ds_images = test_ds.map(lambda image, idnum:image)\nprobabilities = model.predict(test_ds_images)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)","metadata":{"execution":{"iopub.status.busy":"2022-06-01T18:26:45.165859Z","iopub.execute_input":"2022-06-01T18:26:45.166836Z","iopub.status.idle":"2022-06-01T18:27:29.320622Z","shell.execute_reply.started":"2022-06-01T18:26:45.166797Z","shell.execute_reply":"2022-06-01T18:27:29.319642Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ds_ids = test_ds.map(lambda image, idnum:idnum).unbatch()\ntest_ids = next(iter(test_ds_ids.batch(NUM_TEST_IMAGES))).numpy().astype('U')\n\nnp.savetxt(\n    'submission.csv',\n    np.rec.fromarrays([test_ids, predictions]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n    \n)","metadata":{"execution":{"iopub.status.busy":"2022-06-01T18:27:29.322814Z","iopub.execute_input":"2022-06-01T18:27:29.323188Z","iopub.status.idle":"2022-06-01T18:27:32.019341Z","shell.execute_reply.started":"2022-06-01T18:27:29.323146Z","shell.execute_reply":"2022-06-01T18:27:32.018403Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!head submission.csv","metadata":{"execution":{"iopub.status.busy":"2022-06-01T18:27:32.021181Z","iopub.execute_input":"2022-06-01T18:27:32.021519Z","iopub.status.idle":"2022-06-01T18:27:32.946799Z","shell.execute_reply.started":"2022-06-01T18:27:32.021466Z","shell.execute_reply":"2022-06-01T18:27:32.945640Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}