{"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":"Thanks to https://www.kaggle.com/ofeksegev/how-to-apply-augmentations","metadata":{}},{"cell_type":"code","source":"import os\nimport datetime as dt\nimport random\nimport math\nimport pickle\n\nimport numpy as np\nimport pandas as pd\nfrom kaggle_datasets import KaggleDatasets\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom sklearn.model_selection import GroupKFold\nimport tensorflow.keras as K\nimport tensorflow_addons as tfa","metadata":{"execution":{"iopub.status.busy":"2021-07-14T07:48:52.146458Z","iopub.execute_input":"2021-07-14T07:48:52.146799Z","iopub.status.idle":"2021-07-14T07:48:52.151944Z","shell.execute_reply.started":"2021-07-14T07:48:52.146768Z","shell.execute_reply":"2021-07-14T07:48:52.150763Z"},"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    \n    return strategy\n\n\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\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\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(img):\n        img = tf.image.random_flip_left_right(img)\n        img = tf.image.random_flip_up_down(img)\n        \n        ###############################################\n        ########### Add Augmentations here: ###########\n        random_number = random.randint(0, 2)\n        if random_number == 1:    \n            img = tf.image.adjust_brightness(img, 0.2)\n        if random_number == 2:\n            img = tf.image.adjust_brightness(img, -0.2)\n        degrees = random.random()*60 - 30\n        tfa.image.rotate(img, degrees * math.pi / 180, interpolation='BILINEAR')\n        ###############################################\n        \n        return img\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=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    \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","metadata":{"execution":{"iopub.status.busy":"2021-07-14T07:48:56.14449Z","iopub.execute_input":"2021-07-14T07:48:56.144846Z","iopub.status.idle":"2021-07-14T07:48:56.159799Z","shell.execute_reply.started":"2021-07-14T07:48:56.144811Z","shell.execute_reply":"2021-07-14T07:48:56.158758Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"COMPETITION_NAME = \"siimcovid19-512-img-png-600-study-png\"\nstrategy = auto_select_accelerator()\nBATCH_SIZE = strategy.num_replicas_in_sync * 32\nGCS_DS_PATH = KaggleDatasets().get_gcs_path(COMPETITION_NAME)","metadata":{"execution":{"iopub.status.busy":"2021-07-14T07:48:56.349329Z","iopub.execute_input":"2021-07-14T07:48:56.349661Z","iopub.status.idle":"2021-07-14T07:49:06.6492Z","shell.execute_reply.started":"2021-07-14T07:48:56.34963Z","shell.execute_reply":"2021-07-14T07:49:06.648255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"load_dir = f\"/kaggle/input/{COMPETITION_NAME}/\"\ndf = pd.read_csv('../input/siim-covid19-detection/train_study_level.csv')\nlabel_cols = df.columns[1:5]","metadata":{"execution":{"iopub.status.busy":"2021-07-14T07:49:06.65066Z","iopub.execute_input":"2021-07-14T07:49:06.651048Z","iopub.status.idle":"2021-07-14T07:49:06.66573Z","shell.execute_reply.started":"2021-07-14T07:49:06.651008Z","shell.execute_reply":"2021-07-14T07:49:06.664745Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gkf  = GroupKFold(n_splits = 5)\ndf['fold'] = -1\nfor fold, (train_idx, val_idx) in enumerate(gkf.split(df, groups = df.id.tolist())):\n    df.loc[val_idx, 'fold'] = fold","metadata":{"execution":{"iopub.status.busy":"2021-07-14T07:49:06.66782Z","iopub.execute_input":"2021-07-14T07:49:06.668111Z","iopub.status.idle":"2021-07-14T07:49:06.697674Z","shell.execute_reply.started":"2021-07-14T07:49:06.668083Z","shell.execute_reply":"2021-07-14T07:49:06.696961Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in range(5):\n\n    valid_paths = GCS_DS_PATH + '/study/' + df[df['fold'] == i]['id'] + '.png' #\"/train/\"\n    train_paths = GCS_DS_PATH + '/study/' + df[df['fold'] != i]['id'] + '.png' #\"/train/\" \n    valid_labels = df[df['fold'] == i][label_cols].values\n    train_labels = df[df['fold'] != i][label_cols].values\n\n    IMSIZE = (224, 240, 260, 300, 380, 456, 528, 600)\n    IMS = 7\n\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\n    train_dataset = build_dataset(\n        train_paths, train_labels, bsize=BATCH_SIZE, decode_fn=decoder\n    )\n\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\n    try:\n        n_labels = train_labels.shape[1]\n    except:\n        n_labels = 1\n\n    with strategy.scope():\n        model = K.models.Sequential()\n\n        input_t = K.Input(shape=(IMSIZE[IMS], IMSIZE[IMS], 3))\n        res_model = K.applications.ResNet50(include_top=False,\n                                           weights=\"imagenet\",\n                                           input_tensor=input_t)\n        for layer in res_model.layers[:-1]:\n            layer.trainable = False\n\n        model.add(res_model)\n        model.add(K.layers.MaxPooling2D(pool_size=3, strides=2)) # reduce output dimensions of resnet\n        model.add(K.layers.Flatten())  # flatten the model to then attach a  FC layer\n        model.add(K.layers.BatchNormalization())\n        model.add(K.layers.Dropout(0.5))\n        model.add(K.layers.Dense(32, activation='relu'))\n        model.add(K.layers.Dropout(0.5))\n        model.add(K.layers.Dense(32, activation='relu'))\n        model.add(K.layers.Dropout(0.5))\n        model.add(K.layers.BatchNormalization())\n        model.add(K.layers.Dense(4, activation='softmax')) \n\n        model.compile(loss='categorical_crossentropy',\n                      optimizer=K.optimizers.RMSprop(lr=2e-5),\n                      metrics=['accuracy'])\n\n    now = dt.datetime.now()\n    name = f'resmodel_pooled_tpu_fold{i}'\n    model.summary()\n\n    steps_per_epoch = train_paths.shape[0] // BATCH_SIZE\n    checkpoint = tf.keras.callbacks.ModelCheckpoint(\n        f'{name}_ckp.h5', save_best_only=True, monitor='val_loss', mode='min')\n    lr_reducer = tf.keras.callbacks.ReduceLROnPlateau(\n        monitor=\"val_loss\", patience=3, min_lr=1e-6, mode='min')\n\n    history = model.fit(\n        train_dataset, \n        epochs=50,\n        verbose=1,\n        callbacks=[checkpoint, lr_reducer],\n        steps_per_epoch=steps_per_epoch,\n        validation_data=valid_dataset)\n\n    model.save(f\"/kaggle/working/{name}_weights_{now.strftime('%d_%m_%Y__%H_%M')}.h5\")\n    with open(f\"/kaggle/working/{name}_history_{now.strftime('%d_%m_%Y__%H_%M')}.pkl\", 'wb') as file_pi:\n            pickle.dump(history.history, file_pi)","metadata":{"execution":{"iopub.status.busy":"2021-07-14T07:49:06.698962Z","iopub.execute_input":"2021-07-14T07:49:06.699431Z"},"trusted":true},"execution_count":null,"outputs":[]}]}