{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# 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)\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\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        pass\n        #print(os.path.join(dirname, filename))\n# You can write up to 20GB 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":"#install efficientnet, as not available in tf.keras\n!pip install -U git+https://github.com/qubvel/efficientnet","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nfrom functools import partial\nfrom sklearn.model_selection import train_test_split\nimport re\nimport efficientnet.keras as efn\nimport random","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#TPU detection\nprint(tf.__version__)\n#version 2.2.0 when TPU connected\n# TF 2.3 version\n# Detect and init the TPU\n#try: # detect TPUs\n#    tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect() # TPU detection\n#    strategy = tf.distribute.TPUStrategy(tpu)\n#except ValueError: # detect GPUs\n#    strategy = tf.distribute.get_strategy() # default strategy that works on CPU and single GPU\n#print(\"Number of accelerators: \", strategy.num_replicas_in_sync)\n\n# TF 2.2 version\ntry:\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)\nexcept ValueError:\n    strategy = tf.distribute.get_strategy() # default strategy that works on CPU and single GPU\nprint(\"Number of accelerators: \", strategy.num_replicas_in_sync)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#variable setup\nAUTOTUNE = tf.data.experimental.AUTOTUNE #autotunes data transfer to optimize efficiency\nGCS_PATH = KaggleDatasets().get_gcs_path()\nBATCH_SIZE = 16*strategy.num_replicas_in_sync\n# larger BATCH_SIZE results in out of memory error\n# I believe this is an 8 core TPU, therefore batch_size = 128, batches of size that are a power of 128 work best\nIMAGE_SIZE = [512,512]\nCLASSES = [\"1\", \"2\", \"3\", \"4\", \"5\"] #4 disease classes and healthy class\nEPOCHS = 30 #for now, will also implement early stopping so maybe this will not be relevant\nprint(GCS_PATH)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#load data\n\n#decode data \ndef decode_img(img):\n    img = tf.io.decode_jpeg(img, channels = 3)\n    img = tf.cast(img, tf.float32)/255.0\n    img = tf.reshape(img, [*IMAGE_SIZE, 3])\n    return img\n#read tfrecords\ndef read_tfrecord(example, labeled):\n    if labeled:\n        TFREC_FORMAT = {\n            \"image\": tf.io.FixedLenFeature([], tf.string), #[] is the shape (is just single value)\n            \"target\": tf.io.FixedLenFeature([], tf.int64)\n        }\n    else:\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    img = decode_img(example[\"image\"])\n    if labeled:\n        label = tf.cast(example[\"target\"], tf.int32)\n        return(img, label)\n    else:\n        idNum = example[\"image_name\"]\n        return(img, idNum)\n#load dataset\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    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False #disable order == increase speed\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads = AUTOTUNE) #automatically interleaves reads from multiple files\n    dataset.with_options(ignore_order) #use data as it streams in\n    dataset = dataset.map(partial(read_tfrecord, labeled = labeled), num_parallel_calls = AUTOTUNE)\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#data augmentation\n#my data augmentation screws with predictions... --> validation accuracy higher than training accuracy\ndef data_augment(img, label):\n    #perhaps use this https://keras.io/api/preprocessing/image/  --> ImageDataGenerator\n    #test ^ function on 1 example to see input and output shapes\n    tf.image.random_flip_left_right(img)\n    tf.image.random_flip_up_down(img)\n    if random.randint(0,100)>=35:\n        tf.image.transpose(img)\n    if random.randint(0,100)>=35:\n        tf.image.rot90(img, random.choice([1,3]))\n    if random.randint(0,100)>=35:\n        tf.image.random_brightness(img, max_delta = 0.3)\n    if random.randint(0,100)>=35:\n        tf.image.random_contrast(img, lower = 0.7, upper = 1.3)\n    if random.randint(0,100)>=35:\n        tf.image.random_saturation(img, lower = 0.7, upper = 1.3)\n    if random.randint(0,100)>=35:\n        tf.image.random_hue(img,max_delta = 0.15)\n    if random.randint(0,100)>=35:\n        tf.image.random_jpeg_quality(img, 25, 100)\n    #need to find out how to add rotation and random crop + resize\n    if random.randint(0,100)>=35:\n        newX = random.randint(400, 512)\n        newY = random.randint(400, 512)\n        tf.image.random_crop(img, size = [newX, newY, 3])\n        tf.image.resize(img, size = IMAGE_SIZE, method = tf.image.ResizeMethod.NEAREST_NEIGHBOR)\n\n    #care, some data augmentation will NOT work with TPU\n    #can add crop (or shift), etc maybe\n    return img, label\ndef take_center(img, label):\n    return img, label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#split, look into using cross validation instead of test train split\nTRAIN_FILENAMES, VALID_FILENAMES = train_test_split(\n    tf.io.gfile.glob(GCS_PATH+\"/train_tfrecords/ld_train*.tfrec\"),\n    test_size = 0.2)\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH+\"/test_tfrecords/ld_test*.tfrec\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#loading data\n\ndef get_train_data():\n    dataset = load_dataset(filenames = TRAIN_FILENAMES, labeled = True)\n    dataset = dataset.map(data_augment, num_parallel_calls = AUTOTUNE)\n    dataset = dataset.repeat() #repeats dataset, maybe can put before data augmentation\n    dataset = dataset.shuffle(2048) #shuffles dataset, 2048 is the buffer size > batch size\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTOTUNE) #creates a dataset that automatically prefetches data from this dataset... maybe acts like some kind of generator object or something\n    return dataset\n\ndef get_valid_data(ordered = False):\n    dataset = load_dataset(filenames = VALID_FILENAMES, labeled = True)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache() #remembers this dataset\n    dataset = dataset.prefetch(AUTOTUNE)\n    return dataset\n\ndef get_test_data(ordered = False): #for outputting actual test data, will need to specify ordered = True\n    dataset = load_dataset(filenames = TEST_FILENAMES, labeled = False, ordered = ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTOTUNE)\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#some dataset parameter stuff\ndef dataset_sizes(filenames):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return(np.sum(n))\nNUM_TRAINING_IMAGES = dataset_sizes(TRAIN_FILENAMES)\nNUM_VALIDATION_IMAGES = dataset_sizes(VALID_FILENAMES)\nNUM_TEST_IMAGES = dataset_sizes(TEST_FILENAMES)\n\nprint('Dataset: {} training images, {} validation images, {} (unlabeled) test images'.format(\n    NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#possible dataset exploration here","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#building model\n\n#define parameters\n\n#try stochastic gradient descent with warm restarts\ndef scheduler_lr_1(epoch):\n    if epoch < 22:\n        return(5e-5+1e-3*(1+np.cos(np.pi*epoch/7))*(1-epoch/30))\n    elif epoch < 28:\n        return(1e-5)\n    #elif epoch < 34:\n    #    return(1e-6)\n    else:\n        return(1e-6)#maybe unnecessary or worse\n    \nlr_schedule1 = tf.keras.callbacks.LearningRateScheduler(scheduler_lr_1)\n\n#model\nwith strategy.scope():\n    #img_adjust_layer = tf.keras.layers.Lambda(\n    #    #tf.keras.applications.xception.preprocess_input, input_shape = [*IMAGE_SIZE, 3]\n    #    efn.preprocess_input#, input_shape = [*IMAGE_SIZE, 3]\n    #)\n    base_model = efn.EfficientNetB5(include_top = False, weights = \"imagenet\", input_shape = (*IMAGE_SIZE, 3))\n    base_model.trainable = False\n    model = tf.keras.Sequential([\n        tf.keras.layers.BatchNormalization(renorm = True),\n        #img_adjust_layer, #idk how to use preprocess_input\n        base_model,\n        tf.keras.layers.GlobalAveragePooling2D(), #may swap this out for dense layers\n        tf.keras.layers.Dropout(0.1), #dropout of 0.05 works incrementally better... this does not get rid of overfitting when training whole model\n        tf.keras.layers.Dense(len(CLASSES), activation = \"softmax\"),\n    ])\n    model.compile(\n        optimizer = tf.keras.optimizers.Adam(),#learning_rate = lr_schedule),\n        loss = \"sparse_categorical_crossentropy\", #use categorical_crossentropy if using one-hot encodings\n        metrics = [\"sparse_categorical_accuracy\"]\n    )\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#train model\n#load data\ntrain_data = get_train_data()\nvalid_data = get_valid_data()\n\n#other parameters\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE #pretty sure this should not be a floor calculation (ie should round up) \n#steps_per_epoch = int( np.ceil(x_train.shape[0] / batch_size) ) -> using floor will have missing data that does not go in\nVALID_STEPS = NUM_VALIDATION_IMAGES // BATCH_SIZE\n\nprint(BATCH_SIZE)\nprint(STEPS_PER_EPOCH)\nprint(VALID_STEPS)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"early_stop = tf.keras.callbacks.EarlyStopping(\n    #monitor = \"val_loss\",\n    min_delta = 0.001,\n    patience = 15,\n    restore_best_weights = True,\n)\n\n#maybe add early stop too\nhistory = model.fit(train_data, \n                    steps_per_epoch=STEPS_PER_EPOCH, \n                    epochs=34,#EPOCHS,\n                    validation_data=valid_data,\n                    validation_steps=VALID_STEPS,\n                    callbacks = [lr_schedule1])#, early_stop])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(model.summary())\nhistory_df = pd.DataFrame(history.history)\nhistory_df.loc[:, ['loss', 'val_loss']].plot()\nhistory_df.loc[:, ['sparse_categorical_accuracy', 'val_sparse_categorical_accuracy']].plot()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#make top few layers in base model trainable, then train on dataset again\n#make all layers trainable\nfor layer in model.layers:\n    layer.trainable = True\n    \n#l2 regularization #https://stackoverflow.com/questions/48330137/adding-regularizer-to-an-existing-layer-of-a-trained-model-without-resetting-wei\nl2 = tf.keras.regularizers.l2(1e-4)#1e-3 for B7 model\n#1e-4 works better 1e-5, also seems to work better than 1e-3, i believe that default is 1e-5\nfor layer in model.layers[1].layers:\n    if isinstance(layer, tf.keras.layers.Conv2D):\n        layer.kernel_regularizer = l2\n\nprint(model.summary())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(\n    initial_learning_rate = 1e-3, #1e-4 for B7\n    decay_steps=50000,\n    decay_rate=0.95,\n)\n\n#define early stopping\nearly_stop = tf.keras.callbacks.EarlyStopping(\n    #monitor = \"val_sparse_categorical_accuracy\",\n    min_delta = 0.001,\n    patience = 5,\n    restore_best_weights = True,\n)\n\nwith strategy.scope():\n    model.compile(\n        optimizer = tf.keras.optimizers.Adam(learning_rate = lr_schedule),# epsilon = 1e-7 is default already\n        loss = \"sparse_categorical_crossentropy\", #use categorical_crossentropy if using one-hot encodings\n        metrics = [\"sparse_categorical_accuracy\"]\n    )\n\nhistory2 = model.fit(train_data, \n                     steps_per_epoch=STEPS_PER_EPOCH, \n                     epochs=EPOCHS,\n                     callbacks = [early_stop],#, lr_schedule1], #lr_schedule1 is not a good fit (initial decrease is good, but increasing again is a mistake)\n                     #likely should use early stopping too... also reducing the l2 cost seems to make overfitting an increasing issue\n                     validation_data=valid_data,\n                     validation_steps=VALID_STEPS)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#redefine early stop\n#define new early stopping\nearly_stop = tf.keras.callbacks.EarlyStopping(\n    monitor = \"val_sparse_categorical_accuracy\",\n    min_delta = 0.0005,\n    patience = 5,\n    restore_best_weights = True,\n)\n\nwith strategy.scope():\n    model.compile(\n        optimizer = tf.keras.optimizers.Adam(learning_rate = 1e-5),\n        loss = \"sparse_categorical_crossentropy\", #use categorical_crossentropy if using one-hot encodings\n        metrics = [\"sparse_categorical_accuracy\"]\n    )\n\nhistory2_2 = model.fit(train_data, \n                     steps_per_epoch=STEPS_PER_EPOCH, \n                     epochs=EPOCHS,\n                     callbacks = [early_stop],\n                     validation_data=valid_data,\n                     validation_steps=VALID_STEPS)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model.compile(\n        optimizer = tf.keras.optimizers.Adam(learning_rate = 1e-7),\n        loss = \"sparse_categorical_crossentropy\", #use categorical_crossentropy if using one-hot encodings\n        metrics = [\"sparse_categorical_accuracy\"]\n    )\n\nhistory2_3 = model.fit(train_data, \n                     steps_per_epoch=STEPS_PER_EPOCH, \n                     epochs=EPOCHS,\n                     callbacks = [early_stop],\n                     validation_data=valid_data,\n                     validation_steps=VALID_STEPS)\n\nmodel.save('EfficientNetB5_based(2).h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#append new data onto history_df to see full training graph\nhistory_df2 = pd.DataFrame(history2.history) \nhistory_df2.loc[:, ['loss', 'val_loss']].plot() \nhistory_df2.loc[:, ['sparse_categorical_accuracy', 'val_sparse_categorical_accuracy']].plot()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history_df2.index = range(31,31+len(history_df2.index))\n\ntotal_history_df = pd.concat([history_df, history_df2])\ntotal_history_df.loc[:, ['loss', 'val_loss']].plot()\ntotal_history_df.loc[:, ['sparse_categorical_accuracy', 'val_sparse_categorical_accuracy']].plot()","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}