{"cells":[{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"#loading modules\nimport math, random, os, re, time\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nfrom tensorflow.keras import layers, Model\nimport matplotlib.pylab as plt\nfrom sklearn.model_selection import train_test_split, KFold\nimport PIL\nimport cv2\nimport seaborn as sns\nfrom kaggle_datasets import KaggleDatasets\nfrom tqdm import tqdm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"try:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\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() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\n\nAUTO     = tf.data.experimental.AUTOTUNE\nREPLICAS = strategy.num_replicas_in_sync\n#REPLICAS = 8\nprint(f'REPLICAS: {REPLICAS}')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#loading data\ndirname='../input/siim-isic-melanoma-classification/'\ntrain = pd.read_csv(dirname+'train.csv')\ntest = pd.read_csv(dirname + 'test.csv')\nprint(train.head())\nprint(len(train))\nprint(len(test))\nprint(train['target'].value_counts())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.countplot(train['target'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"GCS_PATH = KaggleDatasets().get_gcs_path('512x512-melanoma-tfrecords-70k-images')\ntrain_set = tf.io.gfile.glob(GCS_PATH + '/train*.tfrec')\ntest_filenames = tf.io.gfile.glob(GCS_PATH + '/test*.tfrec')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_filenames , valid_filenames = train_test_split(train_set , test_size=0.2,shuffle=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"BATCH_SIZE = 8 * strategy.num_replicas_in_sync\nIMAGE_SIZE = [512,512]\nAUTO = tf.data.experimental.AUTOTUNE\nimSize = 512","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, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    image = tf.image.resize(image, [imSize,imSize])\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\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['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(example['image'])\n    idnum = example['image_name']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=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_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\n\ndef data_augment(image, label):\n    # data augmentation. Thanks to the dataset.prefetch(AUTO) statement in the next function (below),\n    # this happens essentially for free on TPU. Data pipeline code is executed on the \"CPU\" part\n    # of the TPU while the TPU itself is computing gradients.\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_up_down(image)\n    image = tf.image.random_saturation(image, 0, 2)\n    image = tf.image.random_hue(image,0.15)\n    return image, label   \n\ndef get_training_dataset():\n    dataset = load_dataset(train_filenames, labeled=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_val_dataset():\n    dataset = load_dataset(valid_filenames, labeled=True)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\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)\n\nNUM_TRAINING_IMAGES = count_data_items(train_filenames)\nNUM_TEST_IMAGES = count_data_items(valid_filenames)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nprint('Dataset: {} training images, {} labeled validation images'.format(NUM_TRAINING_IMAGES, NUM_TEST_IMAGES))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for image, label in get_training_dataset().take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Training data label examples:\", label.numpy())\n# print(\"Test data shapes:\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model = tf.keras.Sequential()\n    model.add(tf.keras.applications.Xception(include_top=False, weights='imagenet',\n                                           input_tensor=layers.Input((512, 512, 3)),\n                                           input_shape=(512,512,3), pooling='avg'))\n    model.add(layers.Flatten())\n    model.add(layers.Dense(4096, activation='relu', name='fc1'))\n    model.add(layers.Dense(1024, activation='relu', name='fc2'))\n    model.add(layers.Dense(1, activation='sigmoid', name='answer'))\n    model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n    model.load_weights('../input/melanoma-tfk-rs50/melanoma_wg.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tf.keras.utils.plot_model(\n    model, to_file='model.png', show_shapes=False, show_layer_names=True,\n    rankdir='TB', expand_nested=False, dpi=96)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau\ndef callback():\n    cb = []\n    \n    checkpoint = ModelCheckpoint('/kaggle/working'+'/melanoma_wg.h5',\n                                 save_best_only=True,\n                                 mode='min',\n                                 monitor='val_loss',\n                                 save_weights_only=True, verbose=1)\n    cb.append(checkpoint)\n    \n    reduceLROnPlat = ReduceLROnPlateau(monitor='val_loss',\n                                   factor=0.3, patience=3,\n                                   verbose=1, mode='auto',\n                                   epsilon=0.0001, cooldown=1, min_lr=0.000001)\n    cb.append(reduceLROnPlat)\n    return cb","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cb = callback()\nhistories = []\nfolds = 4\n#train and validate\nepochs = 7\nfor i in range(folds):\n    print(\"Fold \", i+1)\n    train_filenames , valid_filenames = train_test_split(train_set , test_size=0.2,shuffle=True)\n    history = model.fit(get_training_dataset(), \n                        epochs=epochs, verbose=True, \n                        steps_per_epoch=NUM_TRAINING_IMAGES // BATCH_SIZE,\n                        validation_data = get_val_dataset(), \n                        validation_steps =NUM_TEST_IMAGES//BATCH_SIZE, \n                        callbacks=cb)\n    histories.append(history)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"columns = 1\nrows = folds\nfig = plt.figure(figsize = (15,10))\ni=1\nfor history in histories:\n    graph = fig.add_subplot(rows, columns, i)\n    graph.plot(history.history['accuracy'])\n    graph.plot(history.history['val_accuracy'])\n    graph.set_title('model accuracy')\n    graph.set_ylabel('accuracy')\n    graph.set_xlabel('epoch')\n    graph.legend(['train', 'test'], loc='upper left')\n    i+=1\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.figure(figsize = (15,10))\ni=1\nfor history in histories:\n    graph = fig.add_subplot(rows, columns, i)\n    graph.plot(history.history['loss'])\n    graph.plot(history.history['val_loss'])\n    graph.set_title('model loss')\n    graph.set_ylabel('loss')\n    graph.set_xlabel('epoch')\n    graph.legend(['train', 'test'], loc='upper left')\n    i+=1\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_test_images = count_data_items(test_filenames)\nnum_test_images","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_test_dataset(ordered=False):\n    dataset = load_dataset(test_filenames, labeled=False,ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ntest_dataset = get_test_dataset(ordered=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Computing predictions...')\ntest_images_ds = test_dataset.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds).flatten()\nprint(probabilities)\n\n\nprint('Generating submission.csv file...')\ntest_ids_ds = test_dataset.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='')","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}