{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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\n# import os\n# for 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 5GB 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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import tensorflow as tf\nimport tensorflow_addons as tfa\nfrom pathlib import Path","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"PROCESSOR = 'GPU'\nIMAGE_SIZE = 192\nNUM_TRAINING_IMAGES = 12753\npath_data = Path(f'/kaggle/input/tpu-getting-started/tfrecords-jpeg-{IMAGE_SIZE}x{IMAGE_SIZE}/')\nfiles_train = [str(path) for path in (path_data / 'train').glob('*')] \nfiles_validate = [str(path) for path in (path_data / 'val').glob('*')]\nfiles_test = [str(path) for path in (path_data / 'test').glob('*')]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.io.decode_jpeg(image_data, channels=3)\n    image = tf.image.convert_image_dtype(image, dtype=tf.float32, saturate=False)  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [IMAGE_SIZE, 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': image}, {'label': label}) # returns a named dataset of (image, label) pairs\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 24\ntrain = tf.data.Dataset.from_tensor_slices(files_train)\ntrain = (train.shuffle(16) ## shuffle files\n              .interleave(tf.data.TFRecordDataset, cycle_length=4, deterministic=False,\n                         num_parallel_calls=tf.data.experimental.AUTOTUNE)\n              .map(read_labeled_tfrecord, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n              .repeat()\n#               .shuffle(8) ## shuffle images\n              .batch(batch_size, drop_remainder=True)\n              .prefetch(tf.data.experimental.AUTOTUNE))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"validate = tf.data.Dataset.from_tensor_slices(files_validate)\nvalidate = (validate.interleave(tf.data.TFRecordDataset, cycle_length=4, deterministic=False,\n                                num_parallel_calls=tf.data.experimental.AUTOTUNE)\n                    .map(read_labeled_tfrecord, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n                    .cache()\n                    .batch(8, drop_remainder=True)\n                    .prefetch(tf.data.experimental.AUTOTUNE))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install  efficientnet","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import efficientnet.tfkeras as efn\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Dense, GlobalMaxPooling2D\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if PROCESSOR == 'TPU':\n    # Cluster Resolver for Google Cloud TPUs.\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Running on TPU ', tpu.master())\n\n    # Connects to the given cluster.\n    tf.config.experimental_connect_to_cluster(tpu)\n\n    # Initialize the TPU devices.\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n\n    # TPU distribution strategy implementation.\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\n    print(\"REPLICAS: \", strategy.num_replicas_in_sync)\nelif PROCESSOR == 'GPU':\n    # GPU distribution strategy implementation.\n    strategy = tf.distribute.MirroredStrategy()\n    print(\"REPLICAS: \", strategy.num_replicas_in_sync)\nelse:\n    tfa.options.TF_ADDONS_PY_OPS = True\n    # need a strategy for the next step even if it doesn't do anything.\n    strategy = tf.distribute.MirroredStrategy()\n    print(\"REPLICAS: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    enet = efn.EfficientNetB3(input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3),\n                              weights='imagenet',\n                              include_top=False)\n\n    enet.trainable = False\n    \n    image_input = Input(shape=(IMAGE_SIZE, IMAGE_SIZE, 3), name='image')\n    x = enet(image_input)\n    x = GlobalMaxPooling2D()(x)\n    label_output = Dense(104, activation='softmax', name='label')(x)\n    \n    model = Model(inputs=[image_input], outputs=[label_output])\n    optimizer = tf.keras.optimizers.Adam(lr=1e-3)\n    \nmodel.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy')\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(train,\n          validation_data=validate,\n          epochs=3,\n          steps_per_epoch=NUM_TRAINING_IMAGES//batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    optimizer = tf.keras.optimizers.Adam(lr=1e-3)\n    optimizer = tfa.optimizers.SWA(optimizer, start_averaging=0, average_period=20)\n    \nmodel.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy')\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(train,\n          validation_data=validate,\n          epochs=3,\n          steps_per_epoch=NUM_TRAINING_IMAGES//batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## replace weights with SWA weights\nprint(\"\\nEvaluate before changing weights\")\nmodel.evaluate(validate, verbose=2)\noptimizer.assign_average_vars(model.variables)\n## one forward pass with low learning rate to adjust batch normalization\nprint(\"\\nEvaluate before updating batch norm\")\nmodel.evaluate(validate, verbose=2)\noptimizer = tf.keras.optimizers.SGD(lr=1e-12)\nmodel.compile(optimizer=optimizer,\n              loss='sparse_categorical_crossentropy')\nmodel.fit(train,\n          epochs=1,\n          validation_data=validate,\n          verbose=2)\nprint(\"\\nEvaluate on the final version\")\nmodel.evaluate(validate, verbose=2)","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}