{"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 os\nimport time\nimport shutil\nimport random\nimport cv2\nimport pandas as pd\nimport seaborn as sn\nimport tensorflow as tf\nimport tensorflow_hub as hub\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import classification_report\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import EfficientNetB0\nfrom sklearn.preprocessing import MultiLabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.applications.efficientnet import preprocess_input\nfrom tensorflow.keras.models import *\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.optimizers import *\nfrom tensorflow.keras.utils import *\nfrom tensorflow.keras.callbacks import *\nfrom tensorflow.keras.initializers import *\nfrom kaggle_datasets import KaggleDatasets\nimport warnings\nwarnings.filterwarnings(\"ignore\")","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-11-21T16:06:12.659599Z","iopub.execute_input":"2021-11-21T16:06:12.660095Z","iopub.status.idle":"2021-11-21T16:06:19.611032Z","shell.execute_reply.started":"2021-11-21T16:06:12.659989Z","shell.execute_reply":"2021-11-21T16:06:19.610143Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nos.system('pip install /kaggle/input/kerasapplications -q')\nos.system('pip install /kaggle/input/efficientnet-keras-source-code/ -q --no-deps')\n\nimport efficientnet.tfkeras as efn","metadata":{"execution":{"iopub.status.busy":"2021-11-21T16:07:24.162182Z","iopub.execute_input":"2021-11-21T16:07:24.162590Z","iopub.status.idle":"2021-11-21T16:07:38.323960Z","shell.execute_reply.started":"2021-11-21T16:07:24.162561Z","shell.execute_reply":"2021-11-21T16:07:38.323109Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('TF version:', tf.__version__)\nprint('Hub version:', hub.__version__)\nprint('Physical devices:', tf.config.list_physical_devices())","metadata":{"execution":{"iopub.status.busy":"2021-11-21T16:06:19.612532Z","iopub.execute_input":"2021-11-21T16:06:19.612864Z","iopub.status.idle":"2021-11-21T16:06:19.625317Z","shell.execute_reply.started":"2021-11-21T16:06:19.612832Z","shell.execute_reply":"2021-11-21T16:06:19.624393Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE\n\ntry:\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":"2021-11-21T16:06:19.626572Z","iopub.execute_input":"2021-11-21T16:06:19.627259Z","iopub.status.idle":"2021-11-21T16:06:25.020657Z","shell.execute_reply.started":"2021-11-21T16:06:19.627228Z","shell.execute_reply":"2021-11-21T16:06:25.019461Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EPOCHS = 10\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nWIDTH = 480\nHEIGHT = 480\nCHANNELS = 3\nLEARNING_RATE = 0.001\nCLASSES = 6\nSEED = 32\ntop_dropout_rate = 0.2","metadata":{"execution":{"iopub.status.busy":"2021-11-21T16:07:38.325468Z","iopub.execute_input":"2021-11-21T16:07:38.325712Z","iopub.status.idle":"2021-11-21T16:07:38.331332Z","shell.execute_reply.started":"2021-11-21T16:07:38.325682Z","shell.execute_reply":"2021-11-21T16:07:38.330183Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path('plant-pathology-2021-fgvc8')\nTRAIN_PATH = GCS_DS_PATH + \"/train_images/\"\nprint(GCS_DS_PATH)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T16:07:38.332457Z","iopub.execute_input":"2021-11-21T16:07:38.332669Z","iopub.status.idle":"2021-11-21T16:07:38.762492Z","shell.execute_reply.started":"2021-11-21T16:07:38.332645Z","shell.execute_reply":"2021-11-21T16:07:38.761489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final_model = 'FGVC8-B0-raw.h5'\nhist_path = 'FGVC8-B0-raw.log'\ntrain_image = '../input/plant-pathology-2021-fgvc8/train_images'\ntrain_df = pd.read_csv('../input/plant-pathology-2021-fgvc8/train.csv', )","metadata":{"execution":{"iopub.status.busy":"2021-11-21T16:07:38.765082Z","iopub.execute_input":"2021-11-21T16:07:38.765430Z","iopub.status.idle":"2021-11-21T16:07:38.810935Z","shell.execute_reply.started":"2021-11-21T16:07:38.765389Z","shell.execute_reply":"2021-11-21T16:07:38.810249Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = train_df[[\"image\", \"labels\"]]\nmlb = MultiLabelBinarizer().fit(train_df.labels.apply(lambda x : x.split()))\nlabels = pd.DataFrame(mlb.transform(train_df.labels.apply(lambda x : x.split())), columns = mlb.classes_)\n\nlabels = pd.concat([train_df['image'], labels], axis=1)\nlabels.head()","metadata":{"execution":{"iopub.status.busy":"2021-11-21T16:07:38.813351Z","iopub.execute_input":"2021-11-21T16:07:38.813691Z","iopub.status.idle":"2021-11-21T16:07:38.898288Z","shell.execute_reply.started":"2021-11-21T16:07:38.813645Z","shell.execute_reply":"2021-11-21T16:07:38.897350Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def format_path(st):\n    return TRAIN_PATH + st\n\ntrain_paths = labels.image.apply(format_path).values\n\ntrain_labels = np.float32(labels.loc[:, 'complex':'scab'].values)\ntrain_paths, valid_paths, train_labels, valid_labels =\\\ntrain_test_split(train_paths, train_labels, test_size=0.15, random_state=2020)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T16:07:38.899804Z","iopub.execute_input":"2021-11-21T16:07:38.900325Z","iopub.status.idle":"2021-11-21T16:07:38.923656Z","shell.execute_reply.started":"2021-11-21T16:07:38.900285Z","shell.execute_reply":"2021-11-21T16:07:38.922983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def process_img(filepath,label):\n    image = tf.io.read_file(filepath)\n    image = tf.image.decode_jpeg(image, channels=CHANNELS)\n    image = tf.image.convert_image_dtype(image, tf.float32) \n    image = tf.image.resize(image, [HEIGHT,WIDTH])\n    return image,label","metadata":{"execution":{"iopub.status.busy":"2021-11-21T16:07:38.925080Z","iopub.execute_input":"2021-11-21T16:07:38.925561Z","iopub.status.idle":"2021-11-21T16:07:38.932437Z","shell.execute_reply.started":"2021-11-21T16:07:38.925520Z","shell.execute_reply":"2021-11-21T16:07:38.931576Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices((train_paths, train_labels))\n    .map(process_img, num_parallel_calls=AUTO)\n    .repeat()\n    .shuffle(512)\n    .batch(BATCH_SIZE)\n    .prefetch(AUTO)\n)\n\nvalid_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices((valid_paths, valid_labels))\n    .map(process_img, num_parallel_calls=AUTO)\n    .batch(BATCH_SIZE)\n    .cache()\n    .prefetch(AUTO)\n)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T16:07:38.933696Z","iopub.execute_input":"2021-11-21T16:07:38.934078Z","iopub.status.idle":"2021-11-21T16:07:39.076986Z","shell.execute_reply.started":"2021-11-21T16:07:38.934049Z","shell.execute_reply":"2021-11-21T16:07:39.075998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_model():\n    base_model = efn.EfficientNetB0(include_top=False, weights='imagenet')\n    base_model.trainabe = True\n\n    inputs = Input((HEIGHT, WIDTH, 3))\n    x = base_model(inputs, training=True)\n    x = GlobalAveragePooling2D()(x)\n    x = Dropout(top_dropout_rate)(x)\n    outputs = Dense(CLASSES, activation='sigmoid')(x)\n    \n    return Model(inputs, outputs)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T16:07:45.301336Z","iopub.execute_input":"2021-11-21T16:07:45.301604Z","iopub.status.idle":"2021-11-21T16:07:45.308794Z","shell.execute_reply.started":"2021-11-21T16:07:45.301579Z","shell.execute_reply":"2021-11-21T16:07:45.308122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    model = get_model()\n    optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)\n    model.compile(optimizer, \n              loss=tf.keras.losses.BinaryCrossentropy(), \n              metrics=['accuracy'])\n    model.summary()","metadata":{"execution":{"iopub.status.busy":"2021-11-21T16:07:47.021439Z","iopub.execute_input":"2021-11-21T16:07:47.021783Z","iopub.status.idle":"2021-11-21T16:08:02.211605Z","shell.execute_reply.started":"2021-11-21T16:07:47.021750Z","shell.execute_reply":"2021-11-21T16:08:02.210753Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"checkpoint = ModelCheckpoint(\n    final_model,\n    monitor = 'val_accuracy',\n    mode = 'max',\n    save_best_only = True,\n    save_weights_only= False ,\n    perior = 1,\n    verbose = 1\n)\n\nearly_stopping = EarlyStopping(\n    monitor = 'val_accuracy',\n    mode = 'auto',\n    min_delta = 0.0001,\n    patience = 5,\n    baseline = None,\n    restore_best_weights = True,\n    verbose = 1\n)\ndef build_lrfn(lr_start=0.00001, lr_max=0.00005, \n               lr_min=0.00001, lr_rampup_epochs=5, \n               lr_sustain_epochs=0, lr_exp_decay=.8):\n    lr_max = lr_max * strategy.num_replicas_in_sync\n\n    def lrfn(epoch):\n        if epoch < lr_rampup_epochs:\n            lr = (lr_max - lr_start) / lr_rampup_epochs * epoch + lr_start\n        elif epoch < lr_rampup_epochs + lr_sustain_epochs:\n            lr = lr_max\n        else:\n            lr = (lr_max - lr_min) *\\\n                 lr_exp_decay**(epoch - lr_rampup_epochs\\\n                                - lr_sustain_epochs) + lr_min\n        return lr\n    return lrfn","metadata":{"execution":{"iopub.status.busy":"2021-11-21T16:08:02.213099Z","iopub.execute_input":"2021-11-21T16:08:02.213348Z","iopub.status.idle":"2021-11-21T16:08:02.223107Z","shell.execute_reply.started":"2021-11-21T16:08:02.213319Z","shell.execute_reply":"2021-11-21T16:08:02.222207Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lrfn = build_lrfn()\nSTEPS_PER_EPOCH = train_labels.shape[0] // BATCH_SIZE\nlr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T16:08:02.224449Z","iopub.execute_input":"2021-11-21T16:08:02.224820Z","iopub.status.idle":"2021-11-21T16:08:02.237439Z","shell.execute_reply.started":"2021-11-21T16:08:02.224732Z","shell.execute_reply":"2021-11-21T16:08:02.236700Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"params = model.fit(\n    train_dataset, \n    validation_data = valid_dataset, \n    epochs = EPOCHS,\n    steps_per_epoch=STEPS_PER_EPOCH,\n    callbacks = [lr_schedule, early_stopping, checkpoint, CSVLogger(hist_path)]\n)","metadata":{"execution":{"iopub.status.busy":"2021-11-21T16:08:02.239519Z","iopub.execute_input":"2021-11-21T16:08:02.239845Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}