{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install efficientnet > /dev/null","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nimport re\nimport random\nimport pandas as pd\nimport numpy as np\nimport math\n\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nfrom kaggle_datasets import KaggleDatasets\nimport efficientnet.tfkeras as efn","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path('siim-isic-melanoma-classification')\nTEST_FILES = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords/test*')\n\nBATCH_SIZE = 256","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"try:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\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() \n\ndef count_data_items(filenames):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ROT_ = 180.0\nSHR_ = 2.0\nHZOOM_ = 8.0\nWZOOM_ = 8.0\nHSHIFT_ = 8.0\nWSHIFT_ = 8.0\n\ndef get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):\n    # returns 3x3 transformmatrix which transforms indicies\n        \n    # CONVERT DEGREES TO RADIANS\n    rotation = math.pi * rotation / 180.\n    shear    = math.pi * shear    / 180.\n\n    def get_3x3_mat(lst):\n        return tf.reshape(tf.concat([lst],axis=0), [3,3])\n    \n    # ROTATION MATRIX\n    c1   = tf.math.cos(rotation)\n    s1   = tf.math.sin(rotation)\n    one  = tf.constant([1],dtype='float32')\n    zero = tf.constant([0],dtype='float32')\n    \n    rotation_matrix = get_3x3_mat([c1,   s1,   zero, \n                                   -s1,  c1,   zero, \n                                   zero, zero, one])    \n    # SHEAR MATRIX\n    c2 = tf.math.cos(shear)\n    s2 = tf.math.sin(shear)    \n    \n    shear_matrix = get_3x3_mat([one,  s2,   zero, \n                                zero, c2,   zero, \n                                zero, zero, one])        \n    # ZOOM MATRIX\n    zoom_matrix = get_3x3_mat([one/height_zoom, zero,           zero, \n                               zero,            one/width_zoom, zero, \n                               zero,            zero,           one])    \n    # SHIFT MATRIX\n    shift_matrix = get_3x3_mat([one,  zero, height_shift, \n                                zero, one,  width_shift, \n                                zero, zero, one])\n    \n    return K.dot(K.dot(rotation_matrix, shear_matrix), \n                 K.dot(zoom_matrix,     shift_matrix))\n\n\ndef transform(image, DIM=256):    \n    # input image - is one image of size [dim,dim,3] not a batch of [b,dim,dim,3]\n    # output - image randomly rotated, sheared, zoomed, and shifted\n    XDIM = DIM%2 #fix for size 331\n    \n    rot = ROT_ * tf.random.normal([1], dtype='float32')\n    shr = SHR_ * tf.random.normal([1], dtype='float32') \n    h_zoom = 1.0 + tf.random.normal([1], dtype='float32') / HZOOM_\n    w_zoom = 1.0 + tf.random.normal([1], dtype='float32') / WZOOM_\n    h_shift = HSHIFT_ * tf.random.normal([1], dtype='float32') \n    w_shift = WSHIFT_ * tf.random.normal([1], dtype='float32') \n\n    # GET TRANSFORMATION MATRIX\n    m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift) \n\n    # LIST DESTINATION PIXEL INDICES\n    x   = tf.repeat(tf.range(DIM//2, -DIM//2,-1), DIM)\n    y   = tf.tile(tf.range(-DIM//2, DIM//2), [DIM])\n    z   = tf.ones([DIM*DIM], dtype='int32')\n    idx = tf.stack( [x,y,z] )\n    \n    # ROTATE DESTINATION PIXELS ONTO ORIGIN PIXELS\n    idx2 = K.dot(m, tf.cast(idx, dtype='float32'))\n    idx2 = K.cast(idx2, dtype='int32')\n    idx2 = K.clip(idx2, -DIM//2+XDIM+1, DIM//2)\n    \n    # FIND ORIGIN PIXEL VALUES           \n    idx3 = tf.stack([DIM//2-idx2[0,], DIM//2-1+idx2[1,]])\n    d    = tf.gather_nd(image, tf.transpose(idx3))\n        \n    return tf.reshape(d,[DIM, DIM,3])\n\n## Helper Functions\ndef data_augment(image, label):\n    image = transform(image, DIM=128)\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.rot90(image)\n    \n    return image, label  \n\ndef process_test_data(data_file):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"image_name\": tf.io.FixedLenFeature([], tf.string),\n    }\n    data = tf.io.parse_single_example(data_file, LABELED_TFREC_FORMAT)\n    img = tf.image.decode_jpeg(data['image'], channels=3)\n    img = tf.image.resize(img, (128,128))\n    img = tf.cast(img, tf.float32) / 255.0\n    img = tf.reshape(img, [128,128, 3])\n\n    idnum = data['image_name']\n\n    return img, idnum","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"def efficientnetbx():\n    return tf.keras.Sequential([\n                    efn.EfficientNetB0(\n                        input_shape=(128,128, 3),\n                        include_top=False\n                    ),\n                    tf.keras.layers.GlobalAveragePooling2D(),\n                    tf.keras.layers.Dense(1, activation='sigmoid')\n                ])\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"TTA = 11\nif strategy != None:\n    with strategy.scope():\n        model = efficientnetbx()\nelse:\n    model = efficientnetbx()\n\nignore_order = tf.data.Options()\ntest_dataset = (\n    tf.data.TFRecordDataset(\n        TEST_FILES,  \n        num_parallel_reads=tf.data.experimental.AUTOTUNE\n    ).with_options(\n        ignore_order\n    ).map(\n        process_test_data,\n        num_parallel_calls=tf.data.experimental.AUTOTUNE\n    ).map(\n        data_augment, \n        num_parallel_calls=tf.data.experimental.AUTOTUNE\n    ).repeat(\n    ).batch(\n        BATCH_SIZE * 4 \n    ).prefetch(\n        tf.data.experimental.AUTOTUNE\n    )\n)\n\n\n\nmodel.load_weights(\"../input/efficientnetb0-128x128/fold-3.h5\")\n\ntest_imgs = test_dataset.map(lambda images, ids: images)\nimg_ids_ds = test_dataset.map(lambda images, ids: ids).unbatch()\n\nct_test = count_data_items(TEST_FILES)\nSTEPS = TTA * ct_test/(BATCH_SIZE * 4)\npred = model.predict(test_imgs,steps=STEPS,verbose=1)[:TTA*ct_test,] \npredictions = np.mean(pred.reshape((ct_test,TTA),order='F'),axis=1) \n\ntest_ids = next(iter(img_ids_ds.batch(ct_test))).numpy().astype('U') \n\npd.DataFrame({\n     'image_name'  : test_ids, \n     'target'      : predictions\n    }).to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}