{"cells":[{"metadata":{},"cell_type":"markdown","source":"# The aim of this kernel is to try a few common models and see how they perform,\n## If you don't know how to use TPU, check out this Kaggle documentation:\n### https://www.kaggle.com/docs/tpu\n## I have also copied the input pipeline from this kernel:\n### https://www.kaggle.com/agentauers/incredible-tpus-finetune-effnetb0-b6-at-once","execution_count":null},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport os\nimport tensorflow as tf\nfrom tensorflow import keras\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport IPython.display as display\nimport scipy.ndimage as ndimage\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_curve, auc, roc_auc_score\nfrom kaggle_datasets import KaggleDatasets\nfrom tqdm import tqdm\nimport math\nimport keras.backend as K\nimport re\nfrom datetime import datetime\nimport time\nimport kerastuner as kt\nfor i in os.listdir('../input/siim-isic-melanoma-classification'):\n    print(f'../input/siim-isic-melanoma-classification/{i}')\n\ntrain = pd.read_csv('../input/siim-isic-melanoma-classification/train.csv')\ntest = pd.read_csv('../input/siim-isic-melanoma-classification/test.csv')\nsample_submission = pd.read_csv('../input/siim-isic-melanoma-classification/sample_submission.csv')\n\n\ntfrecords_path = KaggleDatasets().get_gcs_path('siim-isic-melanoma-classification')\nfiles_train = np.sort(np.array(tf.io.gfile.glob(tfrecords_path + '/tfrecords/train*.tfrec')))\nfiles_test  = np.sort(np.array(tf.io.gfile.glob(tfrecords_path + '/tfrecords/test*.tfrec')))\nprint(tfrecords_path)\n\nDEVICE = \"TPU\"\n\nCFG = dict(\n    batch_size        =  128,\n    \n    read_size         = 1024, \n    crop_size         = 700, \n    net_size          = 512, \n    \n    epochs            =  30,\n    LR_START          =   0.000050,\n    LR_MAX            =   0.000200,\n    LR_MIN            =   0.000010,\n    LR_RAMPUP_EPOCHS  =   5,\n    LR_SUSTAIN_EPOCHS =   0,\n    LR_EXP_DECAY      =   0.8,\n    \n    rot               = 180.0,\n    shr               =   2.0,\n    hzoom             =   8.0,\n    wzoom             =   8.0,\n    hshift            =   8.0,\n    wshift            =   8.0,\n\n    optimizer         = 'adam',\n    label_smooth_fac  =   0.05,\n    \n    tta_steps         =  25,\n    \n    validation_split=0.2\n)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Let's draw some plots to explore the data","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## benign and malignant","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.countplot(x='benign_malignant',data = train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.countplot(x='sex',data = train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.distplot(train[\"age_approx\"])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## benign vs malignant","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"benign_df = train[train.benign_malignant == 'benign']\nmalignant_df = train[train.benign_malignant == 'malignant']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20, 8))\n\nplt.subplot(1, 2, 1)\nsns.countplot(x='sex',data = benign_df)\nplt.title('Benign')\n\nplt.subplot(1, 2, 2)\nsns.countplot(x='sex',data = malignant_df)\nplt.title('Malignant')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20, 8))\n\nplt.subplot(1, 2, 1)\nsns.countplot(x='sex',data = benign_df)\nplt.title('Benign')\n\nplt.subplot(1, 2, 2)\nsns.countplot(x='sex',data = malignant_df)\nplt.title('Malignant')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20, 8))\n\nplt.subplot(1, 2, 1)\nsns.countplot(x='age_approx',data = benign_df)\nplt.title('Benign')\n\nplt.subplot(1, 2, 2)\nsns.countplot(x='age_approx',data = malignant_df)\nplt.title('Malignant')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20, 8))\n\nplt.subplot(1, 2, 1)\nsns.countplot(x='anatom_site_general_challenge',data = benign_df)\nplt.title('Benign')\n\nplt.subplot(1, 2, 2)\nsns.countplot(x='anatom_site_general_challenge',data = malignant_df)\nplt.title('Malignant')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20, 8))\n\nplt.subplot(1, 2, 1)\nsns.countplot(x='diagnosis',data = benign_df)\nplt.title('Benign')\n\nplt.subplot(1, 2, 2)\nsns.countplot(x='diagnosis',data = malignant_df)\nplt.title('Malignant')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Create train and validation datasets and manage unbalanced data \nhttps://www.tensorflow.org/tutorials/structured_data/imbalanced_data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# validation_split = 0.2\n# train['image_name'] = train['image_name'].apply(lambda x: x+'.jpg') \n\n# train,valid = train_test_split(train[['image_name','benign_malignant']],test_size=validation_split,stratify=train['target'])\n\n# print(np.mean(train['benign_malignant'].values))\n# print(np.mean(valid['benign_malignant'].values))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# I used data loading and image transformation from this great kernel:\n### https://www.kaggle.com/agentauers/incredible-tpus-finetune-effnetb0-b6-at-once","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"if DEVICE == \"TPU\":\n    print(\"connecting to TPU...\")\n    try:\n        tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n        print('Running on TPU ', tpu.master())\n    except ValueError:\n        print(\"Could not connect to TPU\")\n        tpu = None\n\n    if tpu:\n        try:\n            print(\"initializing  TPU ...\")\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(\"TPU initialized\")\n        except _:\n            print(\"failed to initialize TPU\")\n    else:\n        DEVICE = \"GPU\"\n\nif DEVICE != \"TPU\":\n    print(\"Using default strategy for CPU and single GPU\")\n    strategy = tf.distribute.get_strategy()\n\nif DEVICE == \"GPU\":\n    print(\"Num GPUs Available: \", len(tf.config.experimental.list_physical_devices('GPU')))\n    \n\nAUTO     = tf.data.experimental.AUTOTUNE\nREPLICAS = strategy.num_replicas_in_sync\nprint(f'REPLICAS: {REPLICAS}')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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, cfg):    \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    DIM = cfg[\"read_size\"]\n    XDIM = DIM%2 #fix for size 331\n    \n    rot = cfg['rot'] * tf.random.normal([1], dtype='float32')\n    shr = cfg['shr'] * tf.random.normal([1], dtype='float32') \n    h_zoom = 1.0 + tf.random.normal([1], dtype='float32') / cfg['hzoom']\n    w_zoom = 1.0 + tf.random.normal([1], dtype='float32') / cfg['wzoom']\n    h_shift = cfg['hshift'] * tf.random.normal([1], dtype='float32') \n    w_shift = cfg['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\ndef read_labeled_tfrecord(example):\n    tfrec_format = {\n        'image'                        : 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 example['image'],example['target']\n\n\ndef read_unlabeled_tfrecord(example, return_image_name):\n    tfrec_format = {\n        'image'                        : tf.io.FixedLenFeature([], tf.string),\n        'image_name'                   : tf.io.FixedLenFeature([], tf.string),\n    }\n    example = tf.io.parse_single_example(example, tfrec_format)\n    return example['image'], example['image_name'] if return_image_name else 0\n\ndef prepare_image(img, cfg=None, augment=True):    \n    img = tf.image.decode_jpeg(img, channels=3)\n    img = tf.image.resize(img, [cfg['read_size'], cfg['read_size']])\n    img = tf.cast(img, tf.float32) / 255.0\n    \n    if augment:\n        img = transform(img, cfg)\n        img = tf.image.random_crop(img, [cfg['crop_size'], cfg['crop_size'], 3])\n        img = tf.image.random_flip_left_right(img)\n        img = tf.image.random_hue(img, 0.01)\n        img = tf.image.random_saturation(img, 0.7, 1.3)\n        img = tf.image.random_contrast(img, 0.8, 1.2)\n        img = tf.image.random_brightness(img, 0.1)\n\n    else:\n        img = tf.image.central_crop(img, cfg['crop_size'] / cfg['read_size'])\n                                   \n    img = tf.image.resize(img, [cfg['net_size'], cfg['net_size']])\n    img = tf.reshape(img, [cfg['net_size'], cfg['net_size'], 3])\n    return img\n\ndef count_data_items(filenames):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) \n         for filename in filenames]\n    return np.sum(n)\n\ndef get_dataset(files, cfg, augment = False, shuffle = False, repeat = False, \n                labeled=True, return_image_names=True,return_validation=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*8)\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_names), \n                    num_parallel_calls=AUTO)      \n    \n    ds = ds.map(lambda img, imgname_or_label: (prepare_image(img, augment=augment, cfg=cfg), \n                                               imgname_or_label), \n                num_parallel_calls=AUTO)\n    \n    if return_validation:\n        val_ds = ds.take(int(count_data_items(files_train)*CFG['validation_split']))\n        \n        ds = ds.batch(cfg['batch_size'] * REPLICAS)\n        val_ds =  val_ds.batch(cfg['batch_size'] * REPLICAS)\n        ds = ds.prefetch(AUTO)\n        val_ds = val_ds.prefetch(AUTO)\n        \n        return ds, val_ds\n\n        \n    \n    ds = ds.batch(cfg['batch_size'] * REPLICAS)\n    ds = ds.prefetch(AUTO)\n    return ds\n\nds_train, ds_valid     = get_dataset(files_train, CFG, augment=True, shuffle=True, repeat=True,return_validation=True)\n# ds_train     = ds_train.map(lambda img, label: (img, [label]))\nsteps_train  = int(count_data_items(files_train)*(1-CFG['validation_split'])) / (CFG['batch_size'] * REPLICAS)\nsteps_valid = int(count_data_items(files_train)*CFG['validation_split']) / (CFG['batch_size'] * REPLICAS)\n\nprint(steps_train,steps_valid)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pos = len(train[train['benign_malignant'] == 'malignant'])\nneg = len(train[train['benign_malignant'] == 'benign'])\n\n\ndef make_model():\n    with strategy.scope():\n        initial_bias = np.log([pos/neg])\n        output_bias = tf.keras.initializers.Constant(initial_bias)\n\n        base_model = tf.keras.applications.ResNet152V2(\n            include_top=False,\n            weights=\"imagenet\",\n            input_shape = (CFG['net_size'],CFG['net_size'],3)\n            )\n        x = base_model.output\n        x = keras.layers.GlobalAveragePooling2D()(x)\n        x = keras.layers.Dense(512, activation='relu')(x)\n        predictions = keras.layers.Dense(1, activation='sigmoid',bias_initializer=output_bias)(x)\n\n        model = keras.models.Model(inputs=base_model.input, outputs=predictions)\n\n        for layer in base_model.layers:\n            layer.trainable = False\n    \n        model.compile(\n            optimizer='adam',\n            loss='binary_crossentropy',\n            metrics=['accuracy',tf.keras.metrics.AUC(name='auc')]\n        )\n    \n        print(model.summary())\n \n        return model\n\nmodel = make_model()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_lr_callback(cfg):\n    lr_start   = cfg['LR_START']\n    lr_max     = cfg['LR_MAX'] * strategy.num_replicas_in_sync\n    lr_min     = cfg['LR_MIN']\n    lr_ramp_ep = cfg['LR_RAMPUP_EPOCHS']\n    lr_sus_ep  = cfg['LR_SUSTAIN_EPOCHS']\n    lr_decay   = cfg['LR_EXP_DECAY']\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\n\nes = tf.keras.callbacks.EarlyStopping(\n    monitor='val_loss',patience=5, verbose=1\n)\n\nrlr = get_lr_callback(CFG)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"hist = model.fit(ds_train,verbose =1,validation_data=ds_valid,validation_steps=steps_valid,steps_per_epoch  = steps_train, epochs= CFG['epochs'],callbacks=[es,rlr])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"CFG['batch_size'] = 128\n\ncnt_test   = count_data_items(files_test)\nsteps      = cnt_test / (CFG['batch_size'] * REPLICAS)\nds_testAug = get_dataset(files_test, CFG, augment=True, repeat=True, \n                         labeled=False, return_image_names=False)\nprint(steps)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = model.predict(ds_testAug,steps=steps,verbose=5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ds = get_dataset(files_test, CFG, augment=False, repeat=True, \n                 labeled=False, return_image_names=True)\n\nimage_names = []\nit = iter(ds.unbatch())\nfor i in range(cnt_test):\n    image_names.append(it.next()[1].numpy().decode(\"utf-8\"))\n    \nimage_names = np.array(image_names).flatten()\n\n\npreds = preds.squeeze()[:len(image_names)]\nsubmission = pd.DataFrame(dict(\n    image_name = image_names,\n    target     = preds.squeeze()))\n\nsubmission = submission.sort_values('image_name')\nsubmission.to_csv('first_submission.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in hist.history.items():\n    print(i[0]) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import plotly.express as px\n\nplot_df = pd.DataFrame(hist.history)\nplot_df['epoch'] = np.arange(1,len(plot_df)+1)\nprint(plot_df)\nfig = px.line(plot_df,x='epoch',y='val_accuracy')\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.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}