{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import os\n\nimport pandas as pd\nimport tensorflow as tf\n\nfrom sklearn.model_selection import train_test_split\n\nimport cv2\nfrom google.cloud import storage\nfrom kaggle_datasets import KaggleDatasets\nfrom random import seed, randint, random, choice\nfrom PIL import Image\nimport tensorflow_addons as tfa","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"strategy = auto_select_accelerator()\nBATCH_SIZE = strategy.num_replicas_in_sync * 8\nGCS_PATH = KaggleDatasets().get_gcs_path('plant-pathology-2021-fgvc8')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def auto_select_accelerator():\n    try:\n        tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n        tf.config.experimental_connect_to_cluster(tpu)\n        tf.tpu.experimental.initialize_tpu_system(tpu)\n        strategy = tf.distribute.experimental.TPUStrategy(tpu)\n        print(\"Running on TPU:\", tpu.master())\n    except ValueError:\n        strategy = tf.distribute.get_strategy()\n    print(f\"Running on {strategy.num_replicas_in_sync} replicas\")\n    \n    return strategy\n\n\ndef build_decoder(with_labels=True, target_size=(256, 256), ext='jpg'):\n    def decode(path):\n        file_bytes = tf.io.read_file(path)\n        if ext == 'png':\n            img = tf.image.decode_png(file_bytes, channels=3)\n        elif ext in ['jpg', 'jpeg']:\n            img = tf.image.decode_jpeg(file_bytes, channels=3)\n        else:\n            raise ValueError(\"Image extension not supported\")\n\n        img = tf.cast(img, tf.float32) / 255.0\n        img = tf.image.resize(img, target_size)\n\n        return img\n    \n    def decode_with_labels(path, label):\n        return decode(path), label\n    \n    return decode_with_labels if with_labels else decode\n\n\ndef build_augmenter(with_labels=True):\n    def augment(img):\n        img = tf.image.random_flip_left_right(img)\n        img = tf.image.random_flip_up_down(img)\n        print(img.shape)\n\n        degrees = randint(-4, 4)\n        img = tfa.image.transform_ops.rotate(img, degrees * 10 * 3.14 / 180.0)\n        \n        csize = randint(int(image_size * 0.5), image_size)\n        img = tf.image.random_crop(img, [csize, csize, 3], seed = 16)\n        img = tf.image.resize(img, (image_size, image_size), method='nearest')\n        \n        return img\n    \n    def augment_with_labels(img, label):\n        return augment(img), label\n    \n    return augment_with_labels if with_labels else augment\n\n\ndef build_dataset(paths, labels=None, bsize=32, cache=True,\n                  decode_fn=None, augment_fn=None,\n                  augment=True, repeat=True, shuffle=18700, \n                  cache_dir=\"\"):\n    if cache_dir != \"\" and cache is True:\n        os.makedirs(cache_dir, exist_ok=True)\n    \n    if decode_fn is None:\n        decode_fn = build_decoder(labels is not None)\n    \n    if augment_fn is None:\n        augment_fn = build_augmenter(labels is not None)\n    \n    AUTO = tf.data.experimental.AUTOTUNE\n    slices = paths if labels is None else (paths, labels)\n    \n    dset = tf.data.Dataset.from_tensor_slices(slices)\n    dset = dset.map(decode_fn, num_parallel_calls=AUTO)\n    dset = dset.cache(cache_dir) if cache else dset\n    dset = dset.map(augment_fn, num_parallel_calls=AUTO) if augment else dset\n    dset = dset.repeat() if repeat else dset\n    dset = dset.shuffle(shuffle) if shuffle else dset\n    dset = dset.batch(bsize).prefetch(AUTO)\n    \n    return dset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"load_dir = \"/kaggle/input/plant-pathology-2021-fgvc8/\"\ndf = pd.read_csv(load_dir + 'train.csv')\n\nclass_name = df.labels.unique().tolist()\n\nprint(class_name)\nnum_classes = len(class_name)\nprint(num_classes)\n\ndf.labels = df.labels.astype(str)\nlabels = tf.keras.utils.to_categorical([class_name.index(x) for x in df.labels])\n\npaths = GCS_PATH+'/train_images/'+df['image']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_paths, valid_paths, train_labels, valid_labels = sklearn.model_selection.train_test_split(\n    paths, labels, train_size=0.8, shuffle=True, random_state=123)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_size = 224\n\ndecoder = build_decoder(with_labels=True, target_size=(image_size, image_size))\n\ntrain_dataset = build_dataset(\n    train_paths, train_labels, bsize=BATCH_SIZE, decode_fn=decoder, augment=True\n)\n\nvalid_dataset = build_dataset(\n    valid_paths, valid_labels, bsize=BATCH_SIZE, decode_fn=decoder,\n    repeat=False, shuffle=True, augment=True\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras import layers\n\ndef build_model():\n    base_model = tf.keras.applications.MobileNet(\n                        include_top=False,\n                        dropout=0.5,\n                        weights=\"imagenet\",\n                        input_shape=(image_size, image_size, 3))\n    for layer in base_model.layers:\n        layer.trainable = True\n\n    model = tf.keras.models.Sequential([\n            layers.BatchNormalization(input_shape=input_shape),\n            base_model,\n            layers.GlobalAveragePooling2D(),\n            layers.Dense(512, activation='relu'),\n            layers.Dropout(0.5),\n            layers.Dense(num_classes, activation=\"softmax\")\n    ])\n    return model    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"checkpoint = tf.keras.callbacks.ModelCheckpoint(\"bestmodel_tpu.h5\",\n                                                save_best_only=True,\n                                                save_weights_only=True,\n                                                monitor='val_loss',\n                                                mode='auto',\n                                                verbose=1)\n\nreduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss',\n                                                 factor=0.1,\n                                                 patience=3,\n                                                 min_lr=1e-12,\n                                                 mode='auto',\n                                                 verbose=1)\n\nearly_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', \n                                                  mode='min', \n                                                  verbose=1, \n                                                  patience=5)\n\noptimizer = tf.keras.optimizers.Nadam(lr=0.0001, \n                                      beta_1=0.9, beta_2=0.999, \n                                      epsilon=1e-7)\n\nsteps_per_epoch = train_paths.shape[0] // BATCH_SIZE\nvalidation_steps = valid_paths.shape[0] // BATCH_SIZE","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model = build_model()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 20\n\ncallbacks = [checkpoint, reduce_lr, early_stopping]\n\nmodel.compile(optimizer=optimizer, \n                loss='categorical_crossentropy', \n                metrics='accuracy')\n\nhistory = model.fit(train_dataset,\n                    epochs=epochs,\n                    verbose=1, callbacks=callbacks,\n                    validation_data=valid_dataset,\n                    steps_per_epoch=steps_per_epoch,\n                    validation_steps=validation_steps)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n# list all data in history\nprint(history.history.keys())\n# summarize history for accuracy\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n# summarize history for loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.load_weights('/kaggle/input/plant-pathology-e50/bestmodel_tpu.h5', by_name=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_dir = '/kaggle/input/plant-pathology-2021-fgvc8/test_images/'\n\ndef _parse_function(filename):\n    image = tf.keras.preprocessing.image.load_img(test_dir+filename)\n    image = tf.keras.preprocessing.image.img_to_array(image)\n    image = tf.keras.preprocessing.image.smart_resize(image, (image_size, image_size))\n    image = tf.reshape(image, (-1, image_size, image_size, 3))\n    image = tf.cast(image, tf.float32) / 255.\n    return image\n\nfilenames = tf.io.gfile.listdir(test_dir)\ndataset = list(map(_parse_function, filenames))\ndataset = tf.data.Dataset.from_tensor_slices(dataset)\nprediction = model.predict(dataset)\nprediction = tf.argmax(prediction, axis=1)\n\n\nsubmission_result = pd.DataFrame({'image' : filenames, 'labels' : prediction})\nsubmission_result['labels'] = submission_result['labels'].apply(lambda x: class_name[int(x)])\nsubmission_result.to_csv('submission.csv', index=False)\nsubmission_result.head()","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}