{"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 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-22T08:14:46.334251Z","iopub.execute_input":"2021-11-22T08:14:46.334529Z","iopub.status.idle":"2021-11-22T08:14:52.49405Z","shell.execute_reply.started":"2021-11-22T08:14:46.334502Z","shell.execute_reply":"2021-11-22T08:14:52.493087Z"},"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-22T08:14:52.49563Z","iopub.execute_input":"2021-11-22T08:14:52.495863Z","iopub.status.idle":"2021-11-22T08:15:04.134403Z","shell.execute_reply.started":"2021-11-22T08:14:52.495835Z","shell.execute_reply":"2021-11-22T08:15:04.133527Z"},"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-22T08:15:04.135779Z","iopub.execute_input":"2021-11-22T08:15:04.136014Z","iopub.status.idle":"2021-11-22T08:15:04.148757Z","shell.execute_reply.started":"2021-11-22T08:15:04.135984Z","shell.execute_reply":"2021-11-22T08:15:04.148156Z"},"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-22T08:15:04.150227Z","iopub.execute_input":"2021-11-22T08:15:04.150624Z","iopub.status.idle":"2021-11-22T08:15:10.254047Z","shell.execute_reply.started":"2021-11-22T08:15:04.150582Z","shell.execute_reply":"2021-11-22T08:15:10.253228Z"},"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-22T08:15:10.255312Z","iopub.execute_input":"2021-11-22T08:15:10.255554Z","iopub.status.idle":"2021-11-22T08:15:10.260192Z","shell.execute_reply.started":"2021-11-22T08:15:10.255526Z","shell.execute_reply":"2021-11-22T08:15:10.259324Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path('fgvc8aug')\nTRAIN_PATH = GCS_DS_PATH + \"/data_full_augmentation_images/data_full_augmentation/images/\"\nprint(GCS_DS_PATH)","metadata":{"execution":{"iopub.status.busy":"2021-11-22T08:15:10.261273Z","iopub.execute_input":"2021-11-22T08:15:10.261586Z","iopub.status.idle":"2021-11-22T08:15:10.639206Z","shell.execute_reply.started":"2021-11-22T08:15:10.261549Z","shell.execute_reply":"2021-11-22T08:15:10.638311Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final_model = 'FGVC8-B0-full-aug.h5'\nhist_path = 'FGVC8-B0-full-aug.log'\ntrain_image = '../input/fgvc8aug/data_full_augmentation_images/data_full_augmentation/images'\ntrain_df = pd.read_csv('../input/fgvc8aug/data.csv', )","metadata":{"execution":{"iopub.status.busy":"2021-11-22T08:15:10.640335Z","iopub.execute_input":"2021-11-22T08:15:10.640574Z","iopub.status.idle":"2021-11-22T08:15:10.71509Z","shell.execute_reply.started":"2021-11-22T08:15:10.640546Z","shell.execute_reply":"2021-11-22T08:15:10.714227Z"},"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-22T08:15:10.71655Z","iopub.execute_input":"2021-11-22T08:15:10.716826Z","iopub.status.idle":"2021-11-22T08:15:10.81729Z","shell.execute_reply.started":"2021-11-22T08:15:10.71679Z","shell.execute_reply":"2021-11-22T08:15:10.816375Z"},"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-22T08:15:10.818651Z","iopub.execute_input":"2021-11-22T08:15:10.818901Z","iopub.status.idle":"2021-11-22T08:15:10.850116Z","shell.execute_reply.started":"2021-11-22T08:15:10.818875Z","shell.execute_reply":"2021-11-22T08:15:10.849085Z"},"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-22T08:15:10.852341Z","iopub.execute_input":"2021-11-22T08:15:10.852725Z","iopub.status.idle":"2021-11-22T08:15:10.859956Z","shell.execute_reply.started":"2021-11-22T08:15:10.852694Z","shell.execute_reply":"2021-11-22T08:15:10.858458Z"},"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-22T08:15:10.861521Z","iopub.execute_input":"2021-11-22T08:15:10.86194Z","iopub.status.idle":"2021-11-22T08:15:10.98957Z","shell.execute_reply.started":"2021-11-22T08:15:10.861913Z","shell.execute_reply":"2021-11-22T08:15:10.988725Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_model():\n    base_model = efn.EfficientNetB0(include_top=False, weights=None)\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-22T08:15:10.990546Z","iopub.execute_input":"2021-11-22T08:15:10.991233Z","iopub.status.idle":"2021-11-22T08:15:10.997704Z","shell.execute_reply.started":"2021-11-22T08:15:10.991191Z","shell.execute_reply":"2021-11-22T08:15:10.996863Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    model = get_model()\n    model.load_weights(\"../input/fgvc8b0fullaug/FGVC8-B0-full-aug.h5\")\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-22T08:15:14.709931Z","iopub.execute_input":"2021-11-22T08:15:14.71022Z","iopub.status.idle":"2021-11-22T08:15:29.0594Z","shell.execute_reply.started":"2021-11-22T08:15:14.710189Z","shell.execute_reply":"2021-11-22T08:15:29.058525Z"},"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-22T08:15:29.060901Z","iopub.execute_input":"2021-11-22T08:15:29.06113Z","iopub.status.idle":"2021-11-22T08:15:29.068825Z","shell.execute_reply.started":"2021-11-22T08:15:29.061103Z","shell.execute_reply":"2021-11-22T08:15:29.067936Z"},"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-22T08:15:29.070052Z","iopub.execute_input":"2021-11-22T08:15:29.070248Z","iopub.status.idle":"2021-11-22T08:15:29.084589Z","shell.execute_reply.started":"2021-11-22T08:15:29.070226Z","shell.execute_reply":"2021-11-22T08:15:29.083717Z"},"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-22T08:15:29.087753Z","iopub.execute_input":"2021-11-22T08:15:29.08806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}