{"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":"!pip --quiet install efficientnet -q","metadata":{"papermill":{"duration":9.65023,"end_time":"2021-09-05T12:40:56.869917","exception":false,"start_time":"2021-09-05T12:40:47.219687","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-10-09T18:44:53.433169Z","iopub.execute_input":"2022-10-09T18:44:53.434881Z","iopub.status.idle":"2022-10-09T18:45:05.930558Z","shell.execute_reply.started":"2022-10-09T18:44:53.434803Z","shell.execute_reply":"2022-10-09T18:45:05.929189Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os, sys\nfrom PIL import Image\nfrom tqdm import tqdm\nimport numpy as np\nimport pandas as pd\nfrom kaggle_datasets import KaggleDatasets\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nimport efficientnet.tfkeras as efn\nfrom tensorflow.keras.models import Model\nfrom sklearn.preprocessing import LabelEncoder\nimport cv2,random,math,warnings\nimport matplotlib.pyplot as plt\nimport tensorflow_hub as hub\nimport tensorflow_addons as tfa\nimport tensorflow.keras.backend as K\nimport random,glob\nwarnings.filterwarnings('ignore')","metadata":{"id":"mEEdv_6ThCKp","papermill":{"duration":8.214365,"end_time":"2021-09-05T12:41:05.102040","exception":false,"start_time":"2021-09-05T12:40:56.887675","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-10-09T18:45:05.937877Z","iopub.execute_input":"2022-10-09T18:45:05.938823Z","iopub.status.idle":"2022-10-09T18:45:11.744100Z","shell.execute_reply.started":"2022-10-09T18:45:05.938769Z","shell.execute_reply":"2022-10-09T18:45:11.742995Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"## Helper Functions\ndef build_decoder(with_labels=True, target_size=(256, 256), ext='png'):\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        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(image):\n        image = tf.image.random_flip_left_right(image)\n        image = tf.image.random_flip_up_down(image)\n        image = tf.image.random_brightness(image, max_delta = 0.1)\n        image = tf.image.rot90(image)\n        image = tf.image.transpose(image)\n        \n        return image\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=1024, \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\n\ndef get_model(name, im_size):\n    base_model = efn.EfficientNetB4(input_shape=(im_size, im_size, 3), weights='noisy-student', include_top = False)\n    model = tf.keras.Sequential([\n        base_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(16, activation='softmax')\n    ])\n    model.compile(\n        optimizer=tf.keras.optimizers.Adam(lr = 1e-4),\n        loss= tf.keras.losses.CategoricalCrossentropy(label_smoothing = 0.001) , #'sparse_categorical_crossentropy',\n        metrics=[\"accuracy\"])\n    return model","metadata":{"papermill":{"duration":0.041531,"end_time":"2021-09-05T12:41:05.402679","exception":false,"start_time":"2021-09-05T12:41:05.361148","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-10-09T18:45:11.748154Z","iopub.execute_input":"2022-10-09T18:45:11.748713Z","iopub.status.idle":"2022-10-09T18:45:11.773311Z","shell.execute_reply.started":"2022-10-09T18:45:11.748680Z","shell.execute_reply":"2022-10-09T18:45:11.771975Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"## test function\n\ndef test(path):    \n    os.mkdir('test')\n\n    for infile in tqdm(os.listdir(path)):\n        outfile = './test/'+infile[:-3] + \"jpeg\"\n        im = Image.open(path+infile)\n        out = im.convert(\"RGB\")\n        out.save(outfile, \"JPEG\", quality=300)\n        \n    im_size = 800\n    BATCH_SIZE = 8\n\n    test_paths = ['./test/'+x for x in os.listdir('./test/')]\n\n    test_decoder = build_decoder(with_labels=False, target_size=(im_size, im_size))\n    dtest = build_dataset(\n        test_paths, bsize=BATCH_SIZE, repeat=False, \n        shuffle=False, augment=False, cache=False,\n        decode_fn=test_decoder\n    )\n    \n    model_name = \"effnetb4\"\n    model = get_model(model_name, im_size)\n\n    model.load_weights('../input/datathon-best-model/effnetb4.h5')\n    preds = model.predict(dtest, verbose=1)\n    \n    sub = pd.DataFrame()\n    sub['id'] = test_paths\n    sub['id'] = sub['id'].apply(lambda x: int(x.split('.')[-2].split('/')[-1]))\n    sub['label'] = np.argmax(preds, axis=-1)\n    sub.to_csv('sub.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2022-10-09T18:45:11.777140Z","iopub.execute_input":"2022-10-09T18:45:11.777474Z","iopub.status.idle":"2022-10-09T18:45:11.792292Z","shell.execute_reply.started":"2022-10-09T18:45:11.777444Z","shell.execute_reply":"2022-10-09T18:45:11.791318Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path = '../input/datathonindoml-2022/validation/validation/'\ntest(path)","metadata":{"papermill":{"duration":0.535596,"end_time":"2021-09-05T12:41:12.702842","exception":false,"start_time":"2021-09-05T12:41:12.167246","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-10-09T18:45:11.795468Z","iopub.execute_input":"2022-10-09T18:45:11.795820Z","iopub.status.idle":"2022-10-09T18:46:30.044490Z","shell.execute_reply.started":"2022-10-09T18:45:11.795792Z","shell.execute_reply":"2022-10-09T18:46:30.043487Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}