{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport cv2\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport math, PIL","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, GlobalAveragePooling2D, Dropout, LeakyReLU, Input, Convolution2D, BatchNormalization\nfrom tensorflow.keras.models import load_model, Sequential, Model\nfrom tensorflow.keras.optimizers import Adam, Adadelta\nfrom tensorflow.keras.applications.vgg16 import VGG16\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3\nimport keras\nfrom kaggle_datasets import KaggleDatasets\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nimport re\n#for dirname, _, filenames in os.walk('/kaggle/input'):\n #   for filename in filenames:\n #       print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras import initializers\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras import constraints\n\nfrom tensorflow.keras.layers import MaxPooling2D, Convolution2D, AveragePooling2D\nfrom tensorflow.keras.layers import Input, Dropout, Dense, Flatten, Activation\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.layers import concatenate\n\nfrom keras.utils.layer_utils import convert_all_kernels_in_model\nfrom keras.utils.data_utils import get_file\nfrom tensorflow.keras.initializers import RandomNormal\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"try:\n    # TPU detection. No parameters necessary if TPU_NAME environment variable is\n    # set: this is always the case on Kaggle.\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    # Default distribution strategy in Tensorflow. Works on CPU and single GPU.\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"input_path = '/kaggle/input/siim-isic-melanoma-classification'\n#input_path = '/kaggle/input/mela-domain-data'\noutput_path = '/kaggle/working'\ntrain_data = pd.read_csv(input_path+'/train.csv', usecols = ['image_name', 'target'])\ntest_data = pd.read_csv(input_path+'/test.csv')\n\nNUM_TEST_IMAGES = test_data.shape[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def focal_loss(gamma=2., alpha=.25):\n    def focal_loss_fixed(y_true, y_pred):\n        pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))\n        pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))\n        return -K.mean(alpha * K.pow(1. - pt_1, gamma) * K.log(pt_1)) - K.mean((1 - alpha) * K.pow(pt_0, gamma) * K.log(1. - pt_0))\n    return focal_loss_fixed","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope(): \n    base=VGG16(input_shape=(256,256,3), weights='imagenet', include_top=False) \n    base.trainable=True \n    model_copy = tf.keras.Sequential([ \n        (base), \n        GlobalAveragePooling2D(),\n        Dense(4096,  name='fc1'), \n        LeakyReLU(alpha=0.2),\n        Dropout(0.2), \n        Dense(4096,  name='fc2'), \n        LeakyReLU(alpha=0.2),\n        Dropout(0.2), \n        Dense(1024,   name='fc3'),\n        LeakyReLU(alpha=0.2),\n        Dropout(0.2), \n        Dense(1, activation ='sigmoid',trainable=True) ])\n\n#model = Model(model.input, x) \nadadelta = tf.keras.optimizers.Adadelta(lr=0.0001) \nmodel_copy.compile(optimizer=adadelta,  loss='binary_crossentropy', metrics=['AUC', 'Recall', 'Precision'])\nmodel_copy.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = load_model('/kaggle/input/target-model/model.h5')\nmodel_copy.set_weights(model.get_weights())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_copy.save('model_copy.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    reload_model = load_model('model_copy.h5')\n    \n#adadelta = tf.keras.optimizers.Adadelta(lr=0.001) \n#model.compile(optimizer=adadelta, loss='binary_crossentropy', metrics=['AUC', 'Recall', 'Precision'])\n#model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_copy.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"[focal_loss(alpha=.25, gamma=2)]\n","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"LR_START = 0.0001\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync\nLR_MIN = 0.1\nLR_RAMPUP_EPOCHS = 5\nLR_SUSTAIN_EPOCHS = 0\nLR_EXP_DECAY = .8\n\ndef lrfn(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:\n        lr = (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS * epoch + LR_START\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        lr = LR_MAX\n    else:\n        lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n    return lr\n\n#def lrfn(epoch):\n#    lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**((50+epoch) - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n#    return lr\n    \nlr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"IMAGE_SIZE = [256, 256]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [1024, 1024, 3]) # explicit size needed for TPU\n    image = tf.image.resize(image, [256, 256])\n    return image\n\n\ndef decode_image_generated(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0 # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [256, 256, 3]) # explicit size needed for TPU\n    return image\n\ndef decode_image_test(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0 # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [1024,1024, 3]) # explicit size needed for TPU\n    image = tf.image.resize(image, [256, 256])\n    return image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def data_augment(img, label):\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    return img, label ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def data_augment_test(img):\n    img = transform(img)\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    return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_dataset(filenames, labeled=True, ordered=False, generated=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_generated_tfrecord if (labeled and generated) else read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        #\"class\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\n        \"target\": tf.io.FixedLenFeature([], tf.int64)  # shape [] means single element\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    #label = tf.cast(example['class'], tf.int32)\n    label = tf.cast(example['target'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_labeled_generated_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        #\"class\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\n        \"target\": tf.io.FixedLenFeature([], tf.int64)  # shape [] means single element\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image_generated(example['image'])\n    #label = tf.cast(example['class'], tf.int32)\n    label = tf.cast(example['target'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"image_name\": tf.io.FixedLenFeature([], tf.string)  # shape [] means single element\n        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image_test(example['image'])\n    idnum = example['image_name']\n    return image, idnum # returns a dataset of image(s)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#GCS_PATH = KaggleDatasets().get_gcs_path('siim-isic-melanoma-classification')\nGCS_PATH = KaggleDatasets().get_gcs_path('mela-domain-data')\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train*.tfrec')\n\nGCS_GR_PATH = KaggleDatasets().get_gcs_path('generated')\nGenerated = tf.io.gfile.glob(GCS_GR_PATH + '/generated*.tfrec')\n\nAUTO = tf.data.experimental.AUTOTUNE\n\nBATCH_SIZE = 8\nEPOCHS = 40\n\nSTEPS_PER_EPOCH = (train_data.shape[0] + 20710) // BATCH_SIZE\n\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True, generated=True)\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    #dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    #dataset = dataset.shuffle(2048)\n    #dataset = dataset.batch(BATCH_SIZE)\n    #dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_training_dataset_gen():\n    dataset = load_dataset(Generated, labeled=True, generated=True)\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    #dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    #dataset = dataset.shuffle(2048)\n    #dataset = dataset.batch(BATCH_SIZE)\n    #dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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":"dataset1 = get_training_dataset()\ndataset2 = get_training_dataset_gen()\n\ndataset1_cnt = count_data_items(TRAINING_FILENAMES)\ndataset2_cnt = count_data_items(Generated)\n\n\ntrain_size_1 = int(0.8 * dataset1_cnt) + 1\nvalid_size_1 = dataset1_cnt - train_size_1\n\ntrain_size_2 = int(0.8 * dataset2_cnt) + 1\nvalid_size_2 = dataset2_cnt - train_size_2\n\ntrain_dataset_1 = dataset1.take(train_size_1)#.shuffle(2048, reshuffle_each_iteration=True)\nvalid_dataset_1 = dataset1.skip(train_size_1)\n\ntrain_dataset_2 = dataset2.take(train_size_2)#.shuffle(2048, reshuffle_each_iteration=True)\nvalid_dataset_2 = dataset2.skip(train_size_2)\n\ntrain_dataset = train_dataset_1.concatenate(train_dataset_2)\ntrain_dataset = train_dataset.batch(BATCH_SIZE)\ntrain_dataset = train_dataset.shuffle(2048, reshuffle_each_iteration=True)\ntrain_dataset = train_dataset.prefetch(AUTO)\n\n\nvalid_dataset = valid_dataset_1.concatenate(valid_dataset_2)\nvalid_dataset = valid_dataset.batch(BATCH_SIZE)\nvalid_dataset = valid_dataset.prefetch(AUTO)\n\n\nreduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1, min_lr=1e-8, mode='auto')\nearly_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0, verbose=1, patience=8, mode='auto')#, restore_best_weights=True)\ncheckpoint = tf.keras.callbacks.ModelCheckpoint(filepath=output_path+'/model.h5', monitor='val_loss', verbose=1, save_best_only=True,save_weights_only=False, mode='auto')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = reload_model.fit(train_dataset, epochs=EPOCHS, validation_data=valid_dataset, callbacks=[reduce_lr, early_stopping, checkpoint])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"reload_model = load_model('/kaggle/working/model.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"GCS_TEST_PATH = KaggleDatasets().get_gcs_path('siim-isic-melanoma-classification')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_TEST_PATH + '/tfrecords/test*.tfrec')\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = reload_model.predict(test_images_ds).flatten()\nprint(probabilities)\n    \nprint('Generating submission.csv file...')\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, probabilities]), fmt=['%s', '%f'], delimiter=',', header='image_name,target', comments='')\n!head submission.csv","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def show_dataset(thumb_size, cols, rows, ds):\n    mosaic = PIL.Image.new(mode='RGB', size=(thumb_size*cols + (cols-1), \n                                             thumb_size*rows + (rows-1)))\n   \n    for idx, data in enumerate(iter(ds)):\n        img, target_or_imgid = data\n        ix  = idx % cols\n        iy  = idx // cols\n        img = np.clip(img.numpy() * 255, 0, 255).astype(np.uint8)\n        img = PIL.Image.fromarray(img)\n        img = img.resize((thumb_size, thumb_size), resample=PIL.Image.BILINEAR)\n        mosaic.paste(img, (ix*thumb_size + ix, \n                           iy*thumb_size + iy))\n\n    display(mosaic)\n\nds = dataset1.take(12*5)   \nshow_dataset(64, 12, 5, ds)","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}