{"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 install efficientnet -q","metadata":{"execution":{"iopub.status.busy":"2021-07-23T10:39:30.000867Z","iopub.execute_input":"2021-07-23T10:39:30.004065Z","iopub.status.idle":"2021-07-23T10:39:37.610407Z","shell.execute_reply.started":"2021-07-23T10:39:30.004016Z","shell.execute_reply":"2021-07-23T10:39:37.609238Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nimport random\nfrom kaggle_datasets import KaggleDatasets\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom sklearn.model_selection import GroupKFold\nimport efficientnet.tfkeras as efn\nimport matplotlib.pyplot as plt\nimport tensorflow_addons as tfa\nimport keras\nimport tensorflow.keras.backend as K\nimport glob\nimport numba\nfrom numba import jit","metadata":{"execution":{"iopub.status.busy":"2021-07-23T10:39:37.613866Z","iopub.execute_input":"2021-07-23T10:39:37.614135Z","iopub.status.idle":"2021-07-23T10:39:38.871784Z","shell.execute_reply.started":"2021-07-23T10:39:37.614106Z","shell.execute_reply":"2021-07-23T10:39:38.870943Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import average_precision_score\n\ndef check(model_path):\n    #model = tf.keras.models.load_model(model_path, custom_objects={'my': my})\n    model = tf.keras.models.load_model(model_path)\n\n    i = int(model_path.split(\"model\")[-1][0])\n    print(\"fold/model\", i)\n    COMPETITION_NAME = \"siimcovid19-512-img-png-600-study-png\"\n    BATCH_SIZE = 32\n    GCS_DS_PATH = KaggleDatasets().get_gcs_path(COMPETITION_NAME)\n    load_dir = f\"/kaggle/input/{COMPETITION_NAME}/\"\n    df = pd.read_csv('../input/siim-cov19-csv-2class/train.csv')\n    label_cols = df.columns[4]\n    gkf  = GroupKFold(n_splits = folds)\n    df['fold'] = -1\n    for fold, (train_idx, val_idx) in enumerate(gkf.split(df, groups = df.StudyInstanceUID.tolist())):\n        df.loc[val_idx, 'fold'] = fold\n    valid_paths = GCS_DS_PATH + '/image/' + df[df['fold'] == i]['id'] + '.png' #\"/train/\"\n    valid_labels = df[df['fold'] == i][label_cols].values\n    IMSIZE = (224, 240, 260, 300, 380, 456, 528, 600, 512)\n    IMS = 8\n    decoder = build_decoder(with_labels=True, target_size=(IMSIZE[IMS], IMSIZE[IMS]), ext='png')\n    test_decoder = build_decoder(with_labels=False, target_size=(IMSIZE[IMS], IMSIZE[IMS]),ext='png')\n    valid_dataset = build_dataset(\n        valid_paths, valid_labels, bsize = BATCH_SIZE, decode_fn = decoder,\n        repeat=False, shuffle=False, augment = False\n    )\n    dtest = build_dataset(valid_paths, bsize = BATCH_SIZE, repeat = False, \n                    shuffle=False, augment=False, cache=False,\n                    decode_fn = test_decoder)\n    try:\n        n_labels = train_labels.shape[1]\n    except:\n        n_labels = 1\n    y_pred = model.predict(dtest, verbose=1)  \n    ip2 = average_precision_score(valid_labels, y_pred) /3\n    ip2 = round(ip2, 3)\n    print(\"mAP\", ip2)\n\n    return [\"model\" + str(i), \"mAP \" + str(ip2)]","metadata":{"execution":{"iopub.status.busy":"2021-07-23T10:39:38.873541Z","iopub.execute_input":"2021-07-23T10:39:38.873893Z","iopub.status.idle":"2021-07-23T10:39:38.887123Z","shell.execute_reply.started":"2021-07-23T10:39:38.873856Z","shell.execute_reply":"2021-07-23T10:39:38.885250Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Config","metadata":{}},{"cell_type":"code","source":"ep = 23\nseed = 5\nfolds = 5  # remain 5","metadata":{"execution":{"iopub.status.busy":"2021-07-23T10:39:38.889114Z","iopub.execute_input":"2021-07-23T10:39:38.889819Z","iopub.status.idle":"2021-07-23T10:39:38.898764Z","shell.execute_reply.started":"2021-07-23T10:39:38.889774Z","shell.execute_reply":"2021-07-23T10:39:38.898032Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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    return strategy\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        img = tf.cast(img, tf.float32) / 255.0\n        img = tf.image.resize(img, target_size)\n        return img\n    def decode_with_labels(path, label):\n        return decode(path), label\n    return decode_with_labels if with_labels else decode\n    def decode_with_labels(path, label):\n        return decode(path), label\n    return decode_with_labels if with_labels else decode\ndef build_augmenter(with_labels=True):\n    def augment(img):\n        img = tf.image.random_flip_left_right(img) #  H Flip \n        img = tf.image.random_flip_up_down(img)  \n        return img    \n    def augment_with_labels(img, label):\n        return augment(img), label\n    return augment_with_labels if with_labels else augment\ndef build_dataset(paths, labels=None, bsize=128, 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    if decode_fn is None:\n        decode_fn = build_decoder(labels is not None)\n    if augment_fn is None:\n        augment_fn = build_augmenter(labels is not None)\n    AUTO = tf.data.experimental.AUTOTUNE\n    slices = paths if labels is None else (paths, labels)\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    if augment:\n        dset = dset.map(augment_fn, num_parallel_calls=AUTO)\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    return dset\ndef set_seed(seed = 0):\n    np.random.seed(seed)\n    random_state = np.random.RandomState(seed)\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    return random_state\nstrategy = auto_select_accelerator()\nrandom_state = set_seed(seed)","metadata":{"execution":{"iopub.status.busy":"2021-07-23T10:39:38.900308Z","iopub.execute_input":"2021-07-23T10:39:38.900808Z","iopub.status.idle":"2021-07-23T10:39:38.928519Z","shell.execute_reply.started":"2021-07-23T10:39:38.900751Z","shell.execute_reply":"2021-07-23T10:39:38.927570Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_path = '../input/723-2-class'","metadata":{"execution":{"iopub.status.busy":"2021-07-23T10:39:38.930139Z","iopub.execute_input":"2021-07-23T10:39:38.930556Z","iopub.status.idle":"2021-07-23T10:39:38.936799Z","shell.execute_reply.started":"2021-07-23T10:39:38.930514Z","shell.execute_reply":"2021-07-23T10:39:38.935766Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mapl = []\nfor i in glob.iglob(model_path + '/*.h5'):\n    mapl.append(check(i))\nmapl","metadata":{"execution":{"iopub.status.busy":"2021-07-23T10:39:38.938327Z","iopub.execute_input":"2021-07-23T10:39:38.938792Z","iopub.status.idle":"2021-07-23T10:50:32.406298Z","shell.execute_reply.started":"2021-07-23T10:39:38.938751Z","shell.execute_reply":"2021-07-23T10:50:32.405391Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# m5 = tf.keras.models.load_model('../input/722-2-class-2/model0.h5') # 'mAP 0.26'\n# m11 = tf.keras.models.load_model('../input/7-15-two-class-some-augmentor/model1.h5') # lb 0.588 mAP 0.265\n# m12 = tf.keras.models.load_model('../input/7-15-two-class-some-augmentor/model2.h5') # lb 0.587 mAP 0.259\n# m16 = tf.keras.models.load_model('../input/722-2-class/model3.h5') # mAP 0.255\n# m9 = tf.keras.models.load_model('../input/721-2-class/model4.h5') # mAP 0.264","metadata":{"execution":{"iopub.status.busy":"2021-07-23T10:50:32.408712Z","iopub.execute_input":"2021-07-23T10:50:32.409128Z","iopub.status.idle":"2021-07-23T10:50:32.414394Z","shell.execute_reply.started":"2021-07-23T10:50:32.409075Z","shell.execute_reply":"2021-07-23T10:50:32.413034Z"},"trusted":true},"execution_count":null,"outputs":[]}]}