{"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":"markdown","source":"## Import thư viện","metadata":{}},{"cell_type":"code","source":"import os\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split","metadata":{"execution":{"iopub.status.busy":"2021-12-02T10:51:13.043608Z","iopub.execute_input":"2021-12-02T10:51:13.044480Z","iopub.status.idle":"2021-12-02T10:51:14.079790Z","shell.execute_reply.started":"2021-12-02T10:51:13.044350Z","shell.execute_reply":"2021-12-02T10:51:14.078869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from 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 *\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.models import Model\nfrom sklearn.preprocessing import MultiLabelBinarizer\nimport tensorflow_addons as tfa\nfrom kaggle_datasets import KaggleDatasets\nfrom tensorflow.keras.applications import EfficientNetB0","metadata":{"execution":{"iopub.status.busy":"2021-12-02T10:52:08.516234Z","iopub.execute_input":"2021-12-02T10:52:08.517045Z","iopub.status.idle":"2021-12-02T10:52:08.523353Z","shell.execute_reply.started":"2021-12-02T10:52:08.517003Z","shell.execute_reply":"2021-12-02T10:52:08.522701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load Data","metadata":{}},{"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE\n# Detect hardware, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\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() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2021-12-02T10:53:01.760464Z","iopub.execute_input":"2021-12-02T10:53:01.760744Z","iopub.status.idle":"2021-12-02T10:53:07.456766Z","shell.execute_reply.started":"2021-12-02T10:53:01.760717Z","shell.execute_reply":"2021-12-02T10:53:07.456087Z"},"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-12-02T10:53:07.459306Z","iopub.execute_input":"2021-12-02T10:53:07.459684Z","iopub.status.idle":"2021-12-02T10:53:07.466918Z","shell.execute_reply.started":"2021-12-02T10:53:07.459641Z","shell.execute_reply":"2021-12-02T10:53:07.465336Z"},"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-12-02T10:53:07.468131Z","iopub.execute_input":"2021-12-02T10:53:07.468876Z","iopub.status.idle":"2021-12-02T10:53:08.024302Z","shell.execute_reply.started":"2021-12-02T10:53:07.468836Z","shell.execute_reply":"2021-12-02T10:53:08.023344Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final_model = 'FGVC8-efn-b0.h5'\nhist_path = 'FGVC8-efn-b0.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-12-02T10:53:08.679569Z","iopub.execute_input":"2021-12-02T10:53:08.679861Z","iopub.status.idle":"2021-12-02T10:53:08.763699Z","shell.execute_reply.started":"2021-12-02T10:53:08.679834Z","shell.execute_reply":"2021-12-02T10:53:08.762709Z"},"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-12-02T10:53:11.662946Z","iopub.execute_input":"2021-12-02T10:53:11.663479Z","iopub.status.idle":"2021-12-02T10:53:11.978518Z","shell.execute_reply.started":"2021-12-02T10:53:11.663448Z","shell.execute_reply":"2021-12-02T10:53:11.977530Z"},"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-12-02T10:53:15.147339Z","iopub.execute_input":"2021-12-02T10:53:15.148083Z","iopub.status.idle":"2021-12-02T10:53:15.184787Z","shell.execute_reply.started":"2021-12-02T10:53:15.148047Z","shell.execute_reply":"2021-12-02T10:53:15.183866Z"},"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-12-02T10:53:18.451559Z","iopub.execute_input":"2021-12-02T10:53:18.452352Z","iopub.status.idle":"2021-12-02T10:53:18.458002Z","shell.execute_reply.started":"2021-12-02T10:53:18.452307Z","shell.execute_reply":"2021-12-02T10:53:18.457042Z"},"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-12-02T10:53:19.446855Z","iopub.execute_input":"2021-12-02T10:53:19.447169Z","iopub.status.idle":"2021-12-02T10:53:19.609463Z","shell.execute_reply.started":"2021-12-02T10:53:19.447139Z","shell.execute_reply":"2021-12-02T10:53:19.608137Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Get model","metadata":{}},{"cell_type":"code","source":"def get_model():\n    base_model = EfficientNetB0(include_top=False, weights='imagenet', input_shape=(HEIGHT, WIDTH, 3))\n\n    x = base_model.output\n    x = GlobalAveragePooling2D()(x)\n    x = Dropout(top_dropout_rate)(x)\n    outputs = Dense(CLASSES, activation='sigmoid')(x)\n    \n    return Model(base_model.input, outputs)","metadata":{"execution":{"iopub.status.busy":"2021-12-02T10:53:32.701861Z","iopub.execute_input":"2021-12-02T10:53:32.702155Z","iopub.status.idle":"2021-12-02T10:53:32.707897Z","shell.execute_reply.started":"2021-12-02T10:53:32.702127Z","shell.execute_reply":"2021-12-02T10:53:32.706881Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    model = get_model()\n\n    model.compile(tf.keras.optimizers.Adam(learning_rate=0.0005) , loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2021-12-02T10:53:51.348383Z","iopub.execute_input":"2021-12-02T10:53:51.348708Z","iopub.status.idle":"2021-12-02T10:54:03.944913Z","shell.execute_reply.started":"2021-12-02T10:53:51.348675Z","shell.execute_reply":"2021-12-02T10:54:03.944120Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2021-12-02T10:54:03.946332Z","iopub.execute_input":"2021-12-02T10:54:03.946686Z","iopub.status.idle":"2021-12-02T10:54:04.077875Z","shell.execute_reply.started":"2021-12-02T10:54:03.946652Z","shell.execute_reply":"2021-12-02T10:54:04.077007Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.keras.utils.plot_model(model, dpi=60)","metadata":{"execution":{"iopub.status.busy":"2021-12-02T10:54:33.108164Z","iopub.execute_input":"2021-12-02T10:54:33.108451Z","iopub.status.idle":"2021-12-02T10:54:34.998507Z","shell.execute_reply.started":"2021-12-02T10:54:33.108419Z","shell.execute_reply":"2021-12-02T10:54:34.995121Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Trainning","metadata":{}},{"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 = 3,\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-12-02T10:54:36.968149Z","iopub.execute_input":"2021-12-02T10:54:36.968437Z","iopub.status.idle":"2021-12-02T10:54:36.978592Z","shell.execute_reply.started":"2021-12-02T10:54:36.968406Z","shell.execute_reply":"2021-12-02T10:54:36.977119Z"},"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-12-02T10:54:39.055832Z","iopub.execute_input":"2021-12-02T10:54:39.056179Z","iopub.status.idle":"2021-12-02T10:54:39.061817Z","shell.execute_reply.started":"2021-12-02T10:54:39.056147Z","shell.execute_reply":"2021-12-02T10:54:39.060923Z"},"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-12-02T10:54:40.339223Z","iopub.execute_input":"2021-12-02T10:54:40.339524Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}