{"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":"# References:\n\n### [CQT G2Net EfficientNetB1[TPU Training] ](https://www.kaggle.com/miklgr500/cqt-g2net-efficientnetb7-tpu-training-w-b?scriptVersionId=67485043) by [Welf Crozzo](https://www.kaggle.com/miklgr500)\n### [Keras_efficientnet_v2](https://github.com/leondgarse/Keras_efficientnet_v2) by [leondgarse](https://github.com/leondgarse)","metadata":{"papermill":{"duration":0.019436,"end_time":"2021-08-10T05:17:50.318675","exception":false,"start_time":"2021-08-10T05:17:50.299239","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# Asthetics\nimport warnings\nimport sklearn.exceptions\nwarnings.filterwarnings('ignore', category=DeprecationWarning)\nwarnings.filterwarnings('ignore', category=FutureWarning)\nwarnings.filterwarnings(\"ignore\", category=sklearn.exceptions.UndefinedMetricWarning)\n\n# General\nfrom kaggle_datasets import KaggleDatasets\nfrom glob import glob\nimport pandas as pd\nimport numpy as np\nimport os\nimport time\nimport cv2\nimport random\nimport shutil\nimport math\nimport re\npd.set_option('display.max_columns', None)\n\n# Visualizations\nfrom PIL import Image\nfrom plotly.subplots import make_subplots\nfrom plotly.offline import iplot\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport cv2\nimport plotly.graph_objs as go\nimport plotly.figure_factory as ff\nimport plotly.express as px\n%matplotlib inline\nsns.set(style=\"whitegrid\")\n\n# Machine Learning\n# Pre Procesing\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\n# Models\nfrom sklearn.model_selection import train_test_split, KFold\n# Deep Learning\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\n#import efficientnet.tfkeras as efn\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import EfficientNetB4\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, BatchNormalization, GlobalAveragePooling2D\nfrom tensorflow.keras.callbacks import TensorBoard, EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.losses import CategoricalCrossentropy\nimport tensorflow_addons as tfa\nfrom tensorflow_addons.metrics import F1Score, FBetaScore\nfrom tensorflow_addons.callbacks import TQDMProgressBar\nfrom tensorflow.keras.utils import plot_model\n\n#Metrics\nfrom sklearn.metrics import confusion_matrix, classification_report, roc_auc_score\n\nprint('TF',tf.__version__)\n\n# Random Seed Fixing\nRANDOM_SEED = 42\n\ndef seed_everything(seed=RANDOM_SEED):\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    random.seed(seed)\n    tf.random.set_seed(seed)\n\nseed_everything()","metadata":{"papermill":{"duration":9.853892,"end_time":"2021-08-10T05:18:00.197034","exception":false,"start_time":"2021-08-10T05:17:50.343142","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-08-10T08:33:03.348521Z","iopub.execute_input":"2021-08-10T08:33:03.349004Z","iopub.status.idle":"2021-08-10T08:33:03.375669Z","shell.execute_reply.started":"2021-08-10T08:33:03.348954Z","shell.execute_reply":"2021-08-10T08:33:03.374472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# From https://www.kaggle.com/xhlulu/ranzcr-efficientnet-tpu-training\ndef auto_select_accelerator():\n    TPU_DETECTED = False\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        TPU_DETECTED =True\n    except ValueError:\n        strategy = tf.distribute.get_strategy()\n    print(f\"Running on {strategy.num_replicas_in_sync} replicas\")\n    \n    return strategy, TPU_DETECTED","metadata":{"papermill":{"duration":0.027147,"end_time":"2021-08-10T05:18:00.242215","exception":false,"start_time":"2021-08-10T05:18:00.215068","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-08-10T08:33:03.378108Z","iopub.execute_input":"2021-08-10T08:33:03.378549Z","iopub.status.idle":"2021-08-10T08:33:03.391411Z","shell.execute_reply.started":"2021-08-10T08:33:03.378503Z","shell.execute_reply":"2021-08-10T08:33:03.390461Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# CFG","metadata":{"papermill":{"duration":0.017648,"end_time":"2021-08-10T05:18:00.277304","exception":false,"start_time":"2021-08-10T05:18:00.259656","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# Model Params\nKFOLDS = 4\nIMG_SIZES = [256]*KFOLDS\nBATCH_SIZES = [64]*KFOLDS\nEPOCHS = [20]*KFOLDS\nEFF_NETS = [0]*KFOLDS # WHICH EFFICIENTNET B? TO USE\n\nAUG = True\nMIX_UP_P = 0.1\nS_SHIFT = 0.0\nT_SHIFT = 0.0\nR_ANGLE = 0 / 180 * np.pi\nLABEL_POSITIVE_SHIFT = 0.99\n\n# Model Eval Params\nDISPLAY_PLOT = True\n\n# Inference Params\nWGTS = [1/KFOLDS]*KFOLDS","metadata":{"papermill":{"duration":0.027406,"end_time":"2021-08-10T05:18:00.322309","exception":false,"start_time":"2021-08-10T05:18:00.294903","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-08-10T08:33:03.393030Z","iopub.execute_input":"2021-08-10T08:33:03.393324Z","iopub.status.idle":"2021-08-10T08:33:03.403878Z","shell.execute_reply.started":"2021-08-10T08:33:03.393290Z","shell.execute_reply":"2021-08-10T08:33:03.402711Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"strategy, TPU_DETECTED = auto_select_accelerator()\nAUTO = tf.data.experimental.AUTOTUNE\nREPLICAS = strategy.num_replicas_in_sync","metadata":{"papermill":{"duration":5.611913,"end_time":"2021-08-10T05:18:05.951866","exception":false,"start_time":"2021-08-10T05:18:00.339953","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-08-10T08:33:03.405330Z","iopub.execute_input":"2021-08-10T08:33:03.405703Z","iopub.status.idle":"2021-08-10T08:33:03.420345Z","shell.execute_reply.started":"2021-08-10T08:33:03.405663Z","shell.execute_reply":"2021-08-10T08:33:03.419612Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tqdm.notebook import tqdm\n\nfiles_train_g = []\nfor i,k in tqdm([(0, 1), (2, 3), (4,5), (6, 7), (8, 9) ,(10,11), (12, 13), (14, 15)]):\n    GCS_PATH = KaggleDatasets().get_gcs_path(f'cqt-g2net-v2-{i}-{k}')\n    files_train_g.extend(np.sort(np.array(tf.io.gfile.glob(GCS_PATH + '/train*.tfrec'))).tolist())\nnum_train_files = len(files_train_g)\nprint('train_files:',num_train_files)","metadata":{"papermill":{"duration":4.888024,"end_time":"2021-08-10T05:18:10.857813","exception":false,"start_time":"2021-08-10T05:18:05.969789","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-08-10T08:33:03.465713Z","iopub.execute_input":"2021-08-10T08:33:03.466232Z","iopub.status.idle":"2021-08-10T08:33:08.338340Z","shell.execute_reply.started":"2021-08-10T08:33:03.466199Z","shell.execute_reply":"2021-08-10T08:33:08.337217Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Reading Tfrecords","metadata":{"papermill":{"duration":0.018269,"end_time":"2021-08-10T05:18:10.895490","exception":false,"start_time":"2021-08-10T05:18:10.877221","status":"completed"},"tags":[]}},{"cell_type":"code","source":"\ndef mixup(image, label, PROBABILITY = 1.0, AUG_BATCH=BATCH_SIZES[0] * REPLICAS):\n    # input image - is a batch of images of size [n,dim,dim,3] not a single image of [dim,dim,3]\n    # output - a batch of images with mixup applied\n    DIM = IMG_SIZES[0]\n    \n    imgs = []; labs = []\n    for j in range(AUG_BATCH):\n        # DO MIXUP WITH PROBABILITY DEFINED ABOVE\n        P = tf.cast( tf.random.uniform([],0,1)<=PROBABILITY, tf.float32)\n        # CHOOSE RANDOM\n        k = tf.cast( tf.random.uniform([],0,AUG_BATCH),tf.int32)\n        a = tf.random.uniform([],0,1)*P # this is beta dist with alpha=1.0\n        # MAKE MIXUP IMAGE\n        img1 = image[j,]\n        img2 = image[k,]\n        imgs.append((1-a)*img1 + a*img2)\n        # MAKE CUTMIX LABEL\n        lab1 = label[j,]\n        lab2 = label[k,]\n        labs.append((1-a)*lab1 + a*lab2)\n            \n    # RESHAPE HACK SO TPU COMPILER KNOWS SHAPE OF OUTPUT TENSOR (maybe use Python typing instead?)\n    image2 = tf.reshape(tf.stack(imgs),(AUG_BATCH,DIM,DIM,3))\n    label2 = tf.reshape(tf.stack(labs),(AUG_BATCH,))\n    return image2,label2\n\ndef time_shift(img, shift=T_SHIFT):\n    if shift > 0:\n        T = IMG_SIZES[0]\n        P = tf.random.uniform([],0,1)\n        SHIFT = tf.cast(T * P, tf.int32)\n        return tf.concat([img[-SHIFT:], img[:-SHIFT]], axis=0)\n    return img\n\n\ndef spector_shift(img, shift=S_SHIFT):\n    if shift > 0:\n        T = IMG_SIZES[1]\n        P = tf.random.uniform([],0,1)\n        SHIFT = tf.cast(T * P, tf.int32)\n        return tf.concat([img[:, -SHIFT:], img[:, :-SHIFT]], axis=1)\n    return img\n\ndef rotate(img, angle=R_ANGLE):\n    if angle > 0:\n        P = tf.random.uniform([],0,1)\n        A = tf.cast(angle * P, tf.float32)\n        return tfa.image.rotate(img, A)\n    return img\n    \ndef img_aug_f(img):\n    img = time_shift(img)\n    img = spector_shift(img)\n    img = rotate(img)\n    return img\n\ndef imgs_aug_f(imgs, batch_size):\n    _imgs = []\n    DIM = IMG_SIZES[0]\n    for j in range(batch_size):\n        _imgs.append(img_aug_f(imgs[j]))\n    return tf.reshape(tf.stack(_imgs),(batch_size,DIM,DIM,3))\n\n\ndef label_positive_shift(labels):\n    return labels * LABEL_POSITIVE_SHIFT\n\ndef aug_f(imgs, labels, batch_size):\n    imgs, label = mixup(imgs, labels, MIX_UP_P, batch_size)\n    imgs = imgs_aug_f(imgs, batch_size)\n    return imgs, label_positive_shift(label)\n\ndef read_labeled_tfrecord(example):\n    tfrec_format = {\n        'image'                        : tf.io.FixedLenFeature([], tf.string),\n        'image_id'                     : tf.io.FixedLenFeature([], tf.string),\n        'target'                       : tf.io.FixedLenFeature([], tf.int64)\n    }           \n    example = tf.io.parse_single_example(example, tfrec_format)\n    return prepare_image(example['image']), tf.reshape(tf.cast(example['target'], tf.float32), [1])\n\n\ndef read_unlabeled_tfrecord(example, return_image_id):\n    tfrec_format = {\n        'image'                        : tf.io.FixedLenFeature([], tf.string),\n        'image_id'                     : tf.io.FixedLenFeature([], tf.string),\n    }\n    example = tf.io.parse_single_example(example, tfrec_format)\n    return prepare_image(example['image']), example['image_id'] if return_image_id else 0\n\n \ndef prepare_image(img, dim=IMG_SIZES[0]):    \n    img = tf.image.resize(tf.image.decode_png(img, channels=3), size=(dim, dim))\n    img = tf.cast(img, tf.float32) / 255.0\n    img = tf.reshape(img, [dim,dim, 3])\n            \n    return img\n\ndef count_data_items(fileids):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(fileid).group(1)) \n         for fileid in fileids]\n    return np.sum(n)","metadata":{"papermill":{"duration":0.048507,"end_time":"2021-08-10T05:18:10.963071","exception":false,"start_time":"2021-08-10T05:18:10.914564","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-08-10T08:33:08.339885Z","iopub.execute_input":"2021-08-10T08:33:08.340190Z","iopub.status.idle":"2021-08-10T08:33:08.577287Z","shell.execute_reply.started":"2021-08-10T08:33:08.340154Z","shell.execute_reply":"2021-08-10T08:33:08.576139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Dataset Creation","metadata":{"papermill":{"duration":0.018864,"end_time":"2021-08-10T05:18:11.001178","exception":false,"start_time":"2021-08-10T05:18:10.982314","status":"completed"},"tags":[]}},{"cell_type":"code","source":"def get_dataset(files, shuffle = False, repeat = False, \n                labeled=True, return_image_ids=True, batch_size=16, dim=IMG_SIZES[0], aug=False):\n    \n    ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO)\n    ds = ds.cache()\n    \n    if repeat:\n        ds = ds.repeat()\n    \n    if shuffle: \n        ds = ds.shuffle(1024*2)\n        opt = tf.data.Options()\n        opt.experimental_deterministic = False\n        ds = ds.with_options(opt)\n        \n    if labeled: \n        ds = ds.map(read_labeled_tfrecord, num_parallel_calls=AUTO)\n    else:\n        ds = ds.map(lambda example: read_unlabeled_tfrecord(example, return_image_ids), \n                    num_parallel_calls=AUTO)      \n    \n    ds = ds.batch(batch_size * REPLICAS)\n    if aug:\n        ds = ds.map(lambda x, y: aug_f(x, y, batch_size * REPLICAS), num_parallel_calls=AUTO)\n    ds = ds.prefetch(AUTO)\n    return ds","metadata":{"papermill":{"duration":0.030994,"end_time":"2021-08-10T05:18:11.051027","exception":false,"start_time":"2021-08-10T05:18:11.020033","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-08-10T08:33:08.579268Z","iopub.execute_input":"2021-08-10T08:33:08.579549Z","iopub.status.idle":"2021-08-10T08:33:08.593981Z","shell.execute_reply.started":"2021-08-10T08:33:08.579522Z","shell.execute_reply":"2021-08-10T08:33:08.592990Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Build Model","metadata":{"papermill":{"duration":0.019892,"end_time":"2021-08-10T05:18:11.090305","exception":false,"start_time":"2021-08-10T05:18:11.070413","status":"completed"},"tags":[]}},{"cell_type":"code","source":"\"\"\"\nCreates a EfficientNetV2 Model as defined in:\nMingxing Tan, Quoc V. Le. (2021).\nEfficientNetV2: Smaller Models and Faster Training\narXiv preprint arXiv:2104.00298.\n\"\"\"\nimport os\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import (\n    Activation,\n    Add,\n    BatchNormalization,\n    Conv2D,\n    Dense,\n    DepthwiseConv2D,\n    Dropout,\n    GlobalAveragePooling2D,\n    Input,\n    PReLU,\n    Reshape,\n    Multiply,\n)\n\nBATCH_NORM_DECAY = 0.9\nBATCH_NORM_EPSILON = 0.001\nCONV_KERNEL_INITIALIZER = keras.initializers.VarianceScaling(scale=2.0, mode=\"fan_out\", distribution=\"truncated_normal\")\n# CONV_KERNEL_INITIALIZER = 'glorot_uniform'\n\nBLOCK_CONFIGS = {\n    \"b0\": {  # width 1.0, depth 1.0\n        \"first_conv_filter\": 32,\n        \"expands\": [1, 4, 4, 4, 6, 6],\n        \"out_channels\": [16, 32, 48, 96, 112, 192],\n        \"depthes\": [1, 2, 2, 3, 5, 8],\n        \"strides\": [1, 2, 2, 2, 1, 2],\n        \"use_ses\": [0, 0, 0, 1, 1, 1],\n    },\n    \"b1\": {  # width 1.0, depth 1.1\n        \"first_conv_filter\": 32,\n        \"expands\": [1, 4, 4, 4, 6, 6],\n        \"out_channels\": [16, 32, 48, 96, 112, 192],\n        \"depthes\": [2, 3, 3, 4, 6, 9],\n        \"strides\": [1, 2, 2, 2, 1, 2],\n        \"use_ses\": [0, 0, 0, 1, 1, 1],\n    },\n    \"b2\": {  # width 1.1, depth 1.2\n        \"first_conv_filter\": 32,\n        \"output_conv_filter\": 1408,\n        \"expands\": [1, 4, 4, 4, 6, 6],\n        \"out_channels\": [16, 32, 56, 104, 120, 208],\n        \"depthes\": [2, 3, 3, 4, 6, 10],\n        \"strides\": [1, 2, 2, 2, 1, 2],\n        \"use_ses\": [0, 0, 0, 1, 1, 1],\n    },\n    \"b3\": {  # width 1.2, depth 1.4\n        \"first_conv_filter\": 40,\n        \"output_conv_filter\": 1536,\n        \"expands\": [1, 4, 4, 4, 6, 6],\n        \"out_channels\": [16, 40, 56, 112, 136, 232],\n        \"depthes\": [2, 3, 3, 5, 7, 12],\n        \"strides\": [1, 2, 2, 2, 1, 2],\n        \"use_ses\": [0, 0, 0, 1, 1, 1],\n    },\n    \"s\": {  # width 1.4, depth 1.8\n        \"first_conv_filter\": 24,\n        \"output_conv_filter\": 1280,\n        \"expands\": [1, 4, 4, 4, 6, 6],\n        \"out_channels\": [24, 48, 64, 128, 160, 256],\n        \"depthes\": [2, 4, 4, 6, 9, 15],\n        \"strides\": [1, 2, 2, 2, 1, 2],\n        \"use_ses\": [0, 0, 0, 1, 1, 1],\n    },\n    \"m\": {  # width 1.6, depth 2.2\n        \"first_conv_filter\": 24,\n        \"output_conv_filter\": 1280,\n        \"expands\": [1, 4, 4, 4, 6, 6, 6],\n        \"out_channels\": [24, 48, 80, 160, 176, 304, 512],\n        \"depthes\": [3, 5, 5, 7, 14, 18, 5],\n        \"strides\": [1, 2, 2, 2, 1, 2, 1],\n        \"use_ses\": [0, 0, 0, 1, 1, 1, 1],\n    },\n    \"l\": {  # width 2.0, depth 3.1\n        \"first_conv_filter\": 32,\n        \"output_conv_filter\": 1280,\n        \"expands\": [1, 4, 4, 4, 6, 6, 6],\n        \"out_channels\": [32, 64, 96, 192, 224, 384, 640],\n        \"depthes\": [4, 7, 7, 10, 19, 25, 7],\n        \"strides\": [1, 2, 2, 2, 1, 2, 1],\n        \"use_ses\": [0, 0, 0, 1, 1, 1, 1],\n    },\n    \"xl\": {\n        \"first_conv_filter\": 32,\n        \"output_conv_filter\": 1280,\n        \"expands\": [1, 4, 4, 4, 6, 6, 6],\n        \"out_channels\": [32, 64, 96, 192, 256, 512, 640],\n        \"depthes\": [4, 8, 8, 16, 24, 32, 8],\n        \"strides\": [1, 2, 2, 2, 1, 2, 1],\n        \"use_ses\": [0, 0, 0, 1, 1, 1, 1],\n    },\n}\n\n\ndef _make_divisible(v, divisor=4, min_value=None):\n    \"\"\"\n    This function is taken from the original tf repo.\n    It ensures that all layers have a channel number that is divisible by 8\n    It can be seen here:\n    https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py\n    \"\"\"\n    if min_value is None:\n        min_value = divisor\n    new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)\n    # Make sure that round down does not go down by more than 10%.\n    if new_v < 0.9 * v:\n        new_v += divisor\n    return new_v\n\n\ndef conv2d_no_bias(inputs, filters, kernel_size, strides=1, padding=\"VALID\", name=\"\"):\n    return Conv2D(\n        filters, kernel_size, strides=strides, padding=padding, use_bias=False, kernel_initializer=CONV_KERNEL_INITIALIZER, name=name + \"conv\"\n    )(inputs)\n\ndef batchnorm_with_activation(inputs, activation=\"swish\", name=\"\"):\n    \"\"\"Performs a batch normalization followed by an activation. \"\"\"\n    bn_axis = 1 if K.image_data_format() == \"channels_first\" else -1\n    nn = BatchNormalization(\n        axis=bn_axis,\n        momentum=BATCH_NORM_DECAY,\n        epsilon=BATCH_NORM_EPSILON,\n        name=name + \"bn\",\n    )(inputs)\n    if activation:\n        nn = Activation(activation=activation, name=name + activation)(nn)\n        # nn = PReLU(shared_axes=[1, 2], alpha_initializer=tf.initializers.Constant(0.25), name=name + \"PReLU\")(nn)\n    return nn\n\ndef se_module(inputs, se_ratio=4, name=\"\"):\n    channel_axis = 1 if K.image_data_format() == \"channels_first\" else -1\n    h_axis, w_axis = [2, 3] if K.image_data_format() == \"channels_first\" else [1, 2]\n\n    filters = inputs.shape[channel_axis]\n    # reduction = _make_divisible(filters // se_ratio, 8)\n    reduction = filters // se_ratio\n    # se = GlobalAveragePooling2D()(inputs)\n    # se = Reshape((1, 1, filters))(se)\n    se = tf.reduce_mean(inputs, [h_axis, w_axis], keepdims=True)\n    se = Conv2D(reduction, kernel_size=1, use_bias=True, kernel_initializer=CONV_KERNEL_INITIALIZER, name=name + \"1_conv\")(se)\n    # se = PReLU(shared_axes=[1, 2])(se)\n    se = Activation(\"swish\")(se)\n    se = Conv2D(filters, kernel_size=1, use_bias=True, kernel_initializer=CONV_KERNEL_INITIALIZER, name=name + \"2_conv\")(se)\n    se = Activation(\"sigmoid\")(se)\n    return Multiply()([inputs, se])\n\n\ndef MBConv(inputs, output_channel, stride, expand_ratio, shortcut, survival=None, use_se=0, is_fused=False, name=\"\"):\n    channel_axis = 1 if K.image_data_format() == \"channels_first\" else -1\n    input_channel = inputs.shape[channel_axis]\n\n    if is_fused and expand_ratio != 1:\n        nn = conv2d_no_bias(inputs, input_channel * expand_ratio, (3, 3), strides=stride, padding=\"same\", name=name + \"sortcut_\")\n        nn = batchnorm_with_activation(nn, name=name + \"sortcut_\")\n    elif expand_ratio != 1:\n        nn = conv2d_no_bias(inputs, input_channel * expand_ratio, (1, 1), strides=(1, 1), padding=\"same\", name=name + \"sortcut_\")\n        nn = batchnorm_with_activation(nn, name=name + \"sortcut_\")\n    else:\n        nn = inputs\n\n    if not is_fused:\n        nn = DepthwiseConv2D(\n            (3, 3), padding=\"same\", strides=stride, use_bias=False, depthwise_initializer=CONV_KERNEL_INITIALIZER, name=name + \"MB_dw_\"\n        )(nn)\n        nn = batchnorm_with_activation(nn, name=name + \"MB_dw_\")\n\n    if use_se:\n        nn = se_module(nn, se_ratio=4 * expand_ratio, name=name + \"se_\")\n\n    # pw-linear\n    if is_fused and expand_ratio == 1:\n        nn = conv2d_no_bias(nn, output_channel, (3, 3), strides=stride, padding=\"same\", name=name + \"fu_\")\n        nn = batchnorm_with_activation(nn, name=name + \"fu_\")\n    else:\n        nn = conv2d_no_bias(nn, output_channel, (1, 1), strides=(1, 1), padding=\"same\", name=name + \"MB_pw_\")\n        nn = batchnorm_with_activation(nn, activation=None, name=name + \"MB_pw_\")\n\n    if shortcut:\n        if survival is not None and survival < 1:\n            from tensorflow_addons.layers import StochasticDepth\n\n            return StochasticDepth(float(survival))([inputs, nn])\n        else:\n            return Add()([inputs, nn])\n    else:\n        return nn\n\n\ndef EfficientNetV2(\n    model_type,\n    input_shape=(None, None, 3),\n    classes=1000,\n    dropout=0.2,\n    first_strides=2,\n    survivals=None,\n    classifier_activation=\"softmax\",\n    pretrained=\"imagenet21k-ft1k\",\n    name=\"EfficientNetV2\",\n):\n    \"\"\"\n    model_type: is the pre-defined model, value in [\"s\", \"m\", \"l\", \"b0\", \"b1\", \"b2\", \"b3\"].\n    classes: Output classes number, 0 to exclude top layers.\n    first_strides: is used in the first Conv2D layer.\n    survivals: is used for [Deep Networks with Stochastic Depth](https://arxiv.org/abs/1603.09382).\n        Can be a constant value like `0.5` or `0.8`,\n        or a tuple value like `(1, 0.8)` indicates the survival probability linearly changes from `1 --> 0.8` for `top --> bottom` layers.\n        A higher value means a higher probability will keep the conv branch.\n        or `None` to disable.\n    pretrained: value in [None, \"imagenet\", \"imagenet21k\", \"imagenet21k-ft1k\"]. Save path is `~/.keras/models/efficientnetv2/`.\n    \"\"\"\n    blocks_config = BLOCK_CONFIGS.get(model_type.lower(), BLOCK_CONFIGS[\"s\"])\n    expands = blocks_config[\"expands\"]\n    out_channels = blocks_config[\"out_channels\"]\n    depthes = blocks_config[\"depthes\"]\n    strides = blocks_config[\"strides\"]\n    use_ses = blocks_config[\"use_ses\"]\n    first_conv_filter = blocks_config.get(\"first_conv_filter\", out_channels[0])\n    output_conv_filter = blocks_config.get(\"output_conv_filter\", 1280)\n\n    inputs = Input(shape=input_shape)\n    out_channel = _make_divisible(first_conv_filter, 8)\n    nn = conv2d_no_bias(inputs, out_channel, (3, 3), strides=first_strides, padding=\"same\", name=\"stem_\")\n    nn = batchnorm_with_activation(nn, name=\"stem_\")\n\n    # StochasticDepth survival_probability values\n    total_layers = sum(depthes)\n    if isinstance(survivals, float):\n        survivals = [survivals] * total_layers\n    elif isinstance(survivals, (list, tuple)) and len(survivals) == 2:\n        start, end = survivals\n        survivals = [start - (1 - end) * float(ii) / total_layers for ii in range(total_layers)]\n    else:\n        survivals = [None] * total_layers\n    survivals = [survivals[int(sum(depthes[:id])) : sum(depthes[: id + 1])] for id in range(len(depthes))]\n\n    pre_out = out_channel\n    for id, (expand, out_channel, depth, survival, stride, se) in enumerate(zip(expands, out_channels, depthes, survivals, strides, use_ses)):\n        out = _make_divisible(out_channel, 8)\n        is_fused = True if se == 0 else False\n        for block_id in range(depth):\n            stride = stride if block_id == 0 else 1\n            shortcut = True if out == pre_out and stride == 1 else False\n            name = \"stack_{}_block{}_\".format(id, block_id)\n            nn = MBConv(nn, out, stride, expand, shortcut, survival[block_id], se, is_fused, name=name)\n            pre_out = out\n\n    output_conv_filter = _make_divisible(output_conv_filter, 8)\n    nn = conv2d_no_bias(nn, output_conv_filter, (1, 1), strides=(1, 1), padding=\"valid\", name=\"post_\")\n    nn = batchnorm_with_activation(nn, name=\"post_\")\n\n    if classes > 0:\n        nn = GlobalAveragePooling2D(name=\"avg_pool\")(nn)\n        if dropout > 0 and dropout < 1:\n            nn = Dropout(dropout)(nn)\n        nn = Dense(classes, activation=classifier_activation, name=\"predictions\")(nn)\n    model = Model(inputs=inputs, outputs=nn, name=name)\n\n    pretrained_dd = {\"imagenet\": \"imagenet\", \"imagenet21k\": \"21k\", \"imagenet21k-ft1k\": \"21k-ft1k\"}\n    if pretrained in pretrained_dd:\n        pre_url = \"https://github.com/leondgarse/Keras_efficientnet_v2/releases/download/v1.0.0/efficientnetv2-{}-{}.h5\"\n        url = pre_url.format(model_type, pretrained_dd[pretrained])\n        file_name = os.path.basename(url)\n        pretrained_model = keras.utils.get_file(file_name, url, cache_subdir=\"models/efficientnetv2\")\n        model.load_weights(pretrained_model, by_name=True, skip_mismatch=True)\n    return model\n\ndef EfficientNetV2B0(\n    input_shape=(None, None, 3),\n    classes=1000,\n    dropout=0.2,\n    first_strides=2,\n    survivals=None,\n    classifier_activation=\"softmax\",\n    pretrained=\"imagenet21k\",\n    name=\"EfficientNetV2B0\",\n):\n    return EfficientNetV2(model_type=\"b0\", **locals())\n\ndef EfficientNetV2B1(\n    input_shape=(None, None, 3),\n    classes=1000,\n    dropout=0.2,\n    first_strides=2,\n    survivals=None,\n    classifier_activation=\"softmax\",\n    pretrained=\"imagenet21k\",\n    name=\"EfficientNetV2B1\",\n):\n    return EfficientNetV2(model_type=\"b1\", **locals())\n\ndef EfficientNetV2B2(\n    input_shape=(None, None, 3),\n    classes=1000,\n    dropout=0.2,\n    first_strides=2,\n    survivals=None,\n    classifier_activation=\"softmax\",\n    pretrained=\"imagenet21k\",\n    name=\"EfficientNetV2B2\",\n):\n    return EfficientNetV2(model_type=\"b2\", **locals())\n\ndef EfficientNetV2B3(\n    input_shape=(None, None, 3),\n    classes=1000,\n    dropout=0.2,\n    first_strides=2,\n    survivals=None,\n    classifier_activation=\"softmax\",\n    pretrained=\"imagenet21k\",\n    name=\"EfficientNetV2B3\",\n):\n    return EfficientNetV2(model_type=\"b3\", **locals())\n\ndef EfficientNetV2S(\n    input_shape=(None, None, 3),\n    classes=1000,\n    dropout=0.2,\n    first_strides=2,\n    survivals=None,\n    classifier_activation=\"softmax\",\n    pretrained=\"imagenet21k\",\n    name=\"EfficientNetV2S\",\n):\n    return EfficientNetV2(model_type=\"s\", **locals())\n\n\ndef EfficientNetV2M(\n    input_shape=(None, None, 3),\n    classes=1000,\n    dropout=0.3,\n    first_strides=2,\n    survivals=None,\n    classifier_activation=\"softmax\",\n    pretrained=\"imagenet21k\",\n    name=\"EfficientNetV2M\",\n):\n    return EfficientNetV2(model_type=\"m\", **locals())\n\n\ndef EfficientNetV2L(\n    input_shape=(None, None, 3),\n    classes=1000,\n    dropout=0.4,\n    first_strides=2,\n    survivals=None,\n    classifier_activation=\"softmax\",\n    pretrained=\"imagenet21k\",\n    name=\"EfficientNetV2L\",\n):\n    return EfficientNetV2(model_type=\"l\", **locals())\n\n\ndef EfficientNetV2XL(\n    input_shape=(None, None, 3),\n    classes=1000,\n    dropout=0.4,\n    first_strides=2,\n    survivals=None,\n    classifier_activation=\"softmax\",\n    pretrained=\"imagenet21k\",\n    name=\"EfficientNetV2XL\",\n):\n    return EfficientNetV2(model_type=\"xl\", **locals())\n\ndef get_actual_survival_probabilities(model):\n    from tensorflow_addons.layers import StochasticDepth\n    return [ii.survival_probability for ii in model.layers if isinstance(ii, StochasticDepth)]\n","metadata":{"papermill":{"duration":0.094355,"end_time":"2021-08-10T05:18:11.205432","exception":false,"start_time":"2021-08-10T05:18:11.111077","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-08-10T08:33:08.596094Z","iopub.execute_input":"2021-08-10T08:33:08.596465Z","iopub.status.idle":"2021-08-10T08:33:08.672095Z","shell.execute_reply.started":"2021-08-10T08:33:08.596434Z","shell.execute_reply":"2021-08-10T08:33:08.671015Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EFNS = [EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, \n        EfficientNetV2S, EfficientNetV2M, EfficientNetV2L, EfficientNetV2XL]\n\ndef build_model(size, ef=0, count=820):\n    inp = tf.keras.layers.Input(shape=(size, size,3))\n    base = EFNS[ef](input_shape=(size, size, 3), survivals=None, dropout=0.5, classes=0, pretrained=None)\n    base.load_weights(\"../input/efficientnetv2-pretrained-weights/efficientnetv2-b0-21k-notop.h5\")\n    \n    x = base(inp)\n    \n    x = tf.keras.layers.GlobalAvgPool2D()(x)\n    \n    x = tf.keras.layers.Dropout(0.2)(x)\n    x = tf.keras.layers.Dense(1,activation='sigmoid')(x)\n    model = tf.keras.Model(inputs=inp, outputs=x)\n    lr_decayed_fn = tf.keras.experimental.CosineDecay(\n                              1e-3,\n                              count,\n    )\n\n    opt = tfa.optimizers.AdamW(lr_decayed_fn, learning_rate=1e-4)\n    loss = tf.keras.losses.BinaryCrossentropy() \n    model.compile(optimizer=opt,loss=loss,metrics=['AUC'])\n    return model","metadata":{"papermill":{"duration":0.031166,"end_time":"2021-08-10T05:18:11.255488","exception":false,"start_time":"2021-08-10T05:18:11.224322","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-08-10T08:33:08.673799Z","iopub.execute_input":"2021-08-10T08:33:08.674450Z","iopub.status.idle":"2021-08-10T08:33:08.685816Z","shell.execute_reply.started":"2021-08-10T08:33:08.674415Z","shell.execute_reply":"2021-08-10T08:33:08.684446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training","metadata":{"papermill":{"duration":0.018036,"end_time":"2021-08-10T05:18:11.292132","exception":false,"start_time":"2021-08-10T05:18:11.274096","status":"completed"},"tags":[]}},{"cell_type":"code","source":"def vis_lr_callback(batch_size=8):\n    lr_start   = 1e-4\n    lr_max     = 0.000015 * REPLICAS * batch_size\n    lr_min     = 1e-7\n    lr_ramp_ep = 3\n    lr_sus_ep  = 0\n    lr_decay   = 0.7\n   \n    def lrfn(epoch):\n        if epoch < lr_ramp_ep:\n            lr = (lr_max - lr_start) / lr_ramp_ep * epoch + lr_start\n            \n        elif epoch < lr_ramp_ep + lr_sus_ep:\n            lr = lr_max\n            \n        else:\n            lr = (lr_max - lr_min) * lr_decay**(epoch - lr_ramp_ep - lr_sus_ep) + lr_min\n            \n        return lr\n    plt.figure(figsize=(10, 7))\n    plt.plot([lrfn(i) for i in range(EPOCHS[0])])\n    plt.show()","metadata":{"papermill":{"duration":0.030728,"end_time":"2021-08-10T05:18:11.341257","exception":false,"start_time":"2021-08-10T05:18:11.310529","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-08-10T08:33:08.687533Z","iopub.execute_input":"2021-08-10T08:33:08.687955Z","iopub.status.idle":"2021-08-10T08:33:08.701375Z","shell.execute_reply.started":"2021-08-10T08:33:08.687917Z","shell.execute_reply":"2021-08-10T08:33:08.700170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_lr_callback(batch_size=8):\n    lr_start   = 1e-4\n    lr_max     = 0.000015 * REPLICAS * batch_size\n    lr_min     = 1e-7\n    lr_ramp_ep = 3\n    lr_sus_ep  = 0\n    lr_decay   = 0.7\n   \n    def lrfn(epoch):\n        if epoch < lr_ramp_ep:\n            lr = (lr_max - lr_start) / lr_ramp_ep * epoch + lr_start\n            \n        elif epoch < lr_ramp_ep + lr_sus_ep:\n            lr = lr_max\n            \n        else:\n            lr = (lr_max - lr_min) * lr_decay**(epoch - lr_ramp_ep - lr_sus_ep) + lr_min\n            \n        return lr\n\n    lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=False)\n    return lr_callback","metadata":{"papermill":{"duration":0.02854,"end_time":"2021-08-10T05:18:11.388154","exception":false,"start_time":"2021-08-10T05:18:11.359614","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-08-10T08:33:08.702882Z","iopub.execute_input":"2021-08-10T08:33:08.703202Z","iopub.status.idle":"2021-08-10T08:33:08.714293Z","shell.execute_reply.started":"2021-08-10T08:33:08.703171Z","shell.execute_reply":"2021-08-10T08:33:08.713323Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"vis_lr_callback(BATCH_SIZES[0])","metadata":{"papermill":{"duration":0.277693,"end_time":"2021-08-10T05:18:11.684493","exception":false,"start_time":"2021-08-10T05:18:11.406800","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-08-10T08:33:08.715986Z","iopub.execute_input":"2021-08-10T08:33:08.716262Z","iopub.status.idle":"2021-08-10T08:33:08.930170Z","shell.execute_reply.started":"2021-08-10T08:33:08.716235Z","shell.execute_reply":"2021-08-10T08:33:08.929177Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"skf = KFold(n_splits=KFOLDS,shuffle=True,random_state=RANDOM_SEED)\noof_pred = []; oof_tar = []; oof_val = []; oof_f1 = []; oof_ids = []; oof_folds = [] \n\nfiles_train_g = np.array(files_train_g)\n\nfor fold,(idxT,idxV) in enumerate(skf.split(files_train_g)):\n    # CREATE TRAIN AND VALIDATION SUBSETS\n    files_train = files_train_g[idxT]\n    np.random.shuffle(files_train);\n    files_valid = files_train_g[idxV]\n    \n    print('#'*25); print('#### FOLD',fold+1)\n    print('#### Image Size: %i | model: %s | batch_size %i'%\n          (IMG_SIZES[fold],EFNS[EFF_NETS[fold]].__name__,BATCH_SIZES[fold]*REPLICAS))\n    train_images = count_data_items(files_train)\n    val_images   = count_data_items(files_valid)\n    print('#### Training: %i | Validation: %i'%(train_images, val_images))\n    \n    # BUILD MODEL\n    K.clear_session()\n    with strategy.scope():\n        model = build_model(IMG_SIZES[fold], ef=EFF_NETS[fold], \n                            count=count_data_items(files_train)/BATCH_SIZES[fold]//REPLICAS//4)\n    print('#'*25)\n    if fold==0:\n        model.summary()\n    print('#'*25)\n    # SAVE BEST MODEL EACH FOLD\n    sv = tf.keras.callbacks.ModelCheckpoint(\n        'fold-%i.h5'%fold, monitor='val_auc', verbose=0, save_best_only=True,\n        save_weights_only=True, mode='max', save_freq='epoch')\n   \n    # TRAIN\n    print('Training...')\n    history = model.fit(\n        get_dataset(files_train, shuffle=True, repeat=True,\n                dim=IMG_SIZES[fold], batch_size = BATCH_SIZES[fold], aug=AUG), \n        epochs=EPOCHS[fold], \n        callbacks = [sv, get_lr_callback(BATCH_SIZES[fold])], \n        steps_per_epoch=count_data_items(files_train)/BATCH_SIZES[fold]//REPLICAS//4,\n        validation_data=get_dataset(files_valid, shuffle=False,\n                repeat=False,dim=IMG_SIZES[fold]),\n        verbose=1\n    )\n    \n    # Loading best model for inference\n    print('Loading best model...')\n    model.load_weights('fold-%i.h5'%fold)  \n    \n    ds_valid = get_dataset(files_valid,labeled=False,return_image_ids=False,\n            repeat=True,shuffle=False,dim=IMG_SIZES[fold],batch_size=BATCH_SIZES[fold]*2)\n    ct_valid = count_data_items(files_valid); STEPS = ct_valid/BATCH_SIZES[fold]/2/REPLICAS\n    pred = model.predict(ds_valid,steps=STEPS,verbose=0)[:ct_valid,] \n    oof_pred.append( np.mean(pred.reshape((ct_valid,1),order='F'),axis=1) )                 \n    \n    # GET OOF TARGETS AND idS\n    ds_valid = get_dataset(files_valid, repeat=False, dim=IMG_SIZES[fold],\n            labeled=True, return_image_ids=True)\n    oof_tar.append( np.array([target.numpy() for img, target in iter(ds_valid.unbatch())]) )\n    \n    # PLOT TRAINING\n    if DISPLAY_PLOT:\n        plt.figure(figsize=(8, 6))\n        sns.distplot(oof_pred[-1])\n        plt.show()\n        \n        plt.figure(figsize=(15,5))\n        plt.plot(np.arange(len(history.history['auc'])),history.history['auc'],'-o',label='Train auc',color='#ff7f0e')\n        plt.plot(np.arange(len(history.history['auc'])),history.history['val_auc'],'-o',label='Val auc',color='#1f77b4')\n        x = np.argmax( history.history['val_auc'] ); y = np.max( history.history['val_auc'] )\n        xdist = plt.xlim()[1] - plt.xlim()[0]; ydist = plt.ylim()[1] - plt.ylim()[0]\n        plt.scatter(x,y,s=200,color='#1f77b4'); plt.text(x-0.03*xdist,y-0.13*ydist,'max auc\\n%.2f'%y,size=14)\n        plt.ylabel('auc',size=14); plt.xlabel('Epoch',size=14)\n        plt.legend(loc=2)\n        plt2 = plt.gca().twinx()\n        plt2.plot(np.arange(len(history.history['auc'])),history.history['loss'],'-o',label='Train Loss',color='#2ca02c')\n        plt2.plot(np.arange(len(history.history['auc'])),history.history['val_loss'],'-o',label='Val Loss',color='#d62728')\n        x = np.argmin( history.history['val_loss'] ); y = np.min( history.history['val_loss'] )\n        ydist = plt.ylim()[1] - plt.ylim()[0]\n        plt.scatter(x,y,s=200,color='#d62728'); plt.text(x-0.03*xdist,y+0.05*ydist,'min loss',size=14)\n        plt.ylabel('Loss',size=14)\n        plt.title('FOLD %i - Image Size %i, %s'%\n                (fold+1,IMG_SIZES[fold],EFNS[EFF_NETS[fold]].__name__),size=18)\n        plt.legend(loc=3)\n        plt.savefig(f'fig{fold}.png')\n        plt.show()","metadata":{"papermill":{"duration":6523.361957,"end_time":"2021-08-10T07:06:55.066472","exception":false,"start_time":"2021-08-10T05:18:11.704515","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-08-10T08:33:08.932049Z","iopub.execute_input":"2021-08-10T08:33:08.932456Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"oof = np.concatenate(oof_pred); true = np.concatenate(oof_tar);\nauc = roc_auc_score(true,oof)\nprint('Overall OOF AUC= %.3f'%auc)","metadata":{"papermill":{"duration":5.462633,"end_time":"2021-08-10T07:07:05.854767","exception":false,"start_time":"2021-08-10T07:07:00.392134","status":"completed"},"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Datasets\n* [Q-Transform TFRecords](https://www.kaggle.com/miklgr500/q-transform-tfrecords)\n    * [CQT G2Net V2 [0 - 1]](https://www.kaggle.com/miklgr500/cqt-g2net-v2-0-1)\n    * [CQT G2Net V2 [2 - 3]](https://www.kaggle.com/miklgr500/cqt-g2net-v2-2-3)\n    * [CQT G2Net V2 [4 - 5]](https://www.kaggle.com/miklgr500/cqt-g2net-v2-4-5)\n    * [CQT G2Net V2 [6 - 7]](https://www.kaggle.com/miklgr500/cqt-g2net-v2-6-7)\n    * [CQT G2Net V2 [8 - 9]](https://www.kaggle.com/miklgr500/cqt-g2net-v2-8-9)\n    * [CQT G2Net V2 [10 - 11]](https://www.kaggle.com/miklgr500/cqt-g2net-v2-10-11)\n    * [CQT G2Net V2 [12 - 13]](https://www.kaggle.com/miklgr500/cqt-g2net-v2-12-13)\n    * [CQT G2Net V2 [14 - 15]](https://www.kaggle.com/miklgr500/cqt-g2net-v2-14-15)","metadata":{"papermill":{"duration":5.249739,"end_time":"2021-08-10T07:07:16.395439","exception":false,"start_time":"2021-08-10T07:07:11.145700","status":"completed"},"tags":[]}},{"cell_type":"markdown","source":"# Next steps\n* Generate Test Sets\n* Create Inference Notebook\n* Add augmentation\n* Add TTA Inference","metadata":{"papermill":{"duration":5.300442,"end_time":"2021-08-10T07:07:26.925404","exception":false,"start_time":"2021-08-10T07:07:21.624962","status":"completed"},"tags":[]}}]}