{"cells":[{"metadata":{},"cell_type":"markdown","source":"\n# **$\\color{orange}{\\text{Flower Classification on TPU  }}$**\n\n\nKaggle'a TPU seçeneği gelmiş, hoşgelmiş. GPU'dan ziyade TPU'lar çok daha hızlı işlem yapan birimlerdir. Biz de TPU üzerinde temel CNN algoritmalarını deneyerek, TPU kullanımını test etmiş olacağız. Temel fonksiyonlar için Martin Görner'e teşekkür ederim. Öncü ve yönlendirici çalışmasından esinlenerek türkçe bir kaynak oluşturmak istedim. Amacım, ingilizce kaynakları takip edemeyen Türk geliştiriciler için yardımcı bir döküman oluşturmak.\n\nÇalışma içerisinde:\n* TPU Mimarisi ve GPU ve CPU'lara göre avantajları\n* TPU kullanımı ve hazırlanması\n* Çiçek sınıflandırması üzerinde CNN algoritmaları ile pre-trained modeller ile denemeler yapılması\n\nBulunmaktadır.\n\n\n**EfficientNetB6, EfficientNetB7 ve DenseNet201 kullanılmıştır. 20 epoch ile tamamlanmıştır.**\n\n****Kısa Özet: 9 epoch'da model performansları****\n\n\n**$\\color{orange}{\\text{9 Epoch'da EfficientNetB6 için : }}$**\n\n* sparse_categorical_accuracy: 0.9394 - val_loss: 0.4078 - val_sparse_categorical_accuracy: 0.9108\n\n\n\n**$\\color{orange}{\\text{9 Epoch'da DenseNet201 için : }}$**\n\n* sparse_categorical_accuracy: 0.9458 - val_loss: 0.4519 - val_sparse_categorical_accuracy: 0.8898\n\n\n"},{"metadata":{},"cell_type":"markdown","source":"\n\n# **$\\color{pink}{\\text{Ön Çalışma ve İşleme  }}$**\n\n* Gerekli Kütüphaneler yüklenmiştir. -> tensorflow ve keras modelleri kullanılmıştır\n\n* Seed çekirdeği atanmıştır. -> Random atanan değerler için aynı kökten (tohumdan) alması sağlanır."},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"!pip install --quiet efficientnet\nprint(\"VolkanOzdemirDL\")\nimport math, os, re, warnings, random\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nfrom sklearn.utils import class_weight\nfrom sklearn.metrics import classification_report, confusion_matrix\nimport tensorflow as tf\nimport tensorflow.keras.layers as L\nfrom tensorflow.keras import optimizers, applications, Sequential, losses\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, LearningRateScheduler\nimport efficientnet.tfkeras as efn\nfrom IPython.display import SVG\n\n\ndef seed_everything(seed=0):\n    random.seed(seed)\n    np.random.seed(seed)\n    tf.random.set_seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    os.environ['TF_DETERMINISTIC_OPS'] = '1'\n\nseed = 0\nseed_everything(seed)\nwarnings.filterwarnings(\"ignore\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# $\\color{orange}{\\text{TPU Nedir? }}$\n \n\n\nTPU: \"Tensor Processimg Unit\", Türkçe olarak ise tensor işlem birimi büyük data yığınları ve konvalosyonel sinir ağları ( CNN) için son derece optimize edilmiş çok yüksek eğitim verimine sahip donanımlardır. \n\nDaha önce data science veya derin öğrenme ile uğraşmışsanız illaki bu algoritmaların GPU'larda CPU'lara göre ne kadar hızlı olduğunu duymuşsunuzdur. Üstelik tek fark da bu değil, CPU'lar kapasite gereği büyük batch-size kullanamamaktadır ve başarımı yükseltmek için gerekli olan giriş büyüklüğüne (input size) ulaşamamaktadır. CPU'nun 1 ila 8 çekirdeği veya daha fazlası vardır. Bir GPU'da ise yüzlerce vardır. Bu işlem birimlerinin fazla olması yapay sinir ağları gibi toplama ve çarpma gibi temel işlemler üzerine oluşturulmuş ( feed-forward yapılar için wX+b ve aktivasyon fonksiyonları ve back-propogation için gradient descent ) sistemler için çok hızlı işlem yapabilmektedir. GPU ve TPU ise çok benzer teknolojidir. Tek fark,  GPU üreticilerinin kimseye satmadıkları tescilli GPU yongalarını kullanan bir bulut hizmeti olmasıdır. Şu an en ünlü TPU paylaşımcısı Google'dır.\n\n\nCPU, GPU ve TPU'nun farkını anlamak için aslında temel algebra'dan yararlanmak gerekmektedir. CPU işleme birimini skaler bir değer olarak düşünecek olur isek, GPU bir vektör gibi, TPU ise bir matris ya da çok boyutlu matris olan tensor'ler ile ifade edilebilir. Tensor yapıları  çok boyutlu matrisler olarak düşünülmelidir ki CNN'lerin temelinde 3 boyutlu bir RGB resim girişi N boyutlu tensorlere dönmektedir.\n\nGiriş data boyutu: \n* CPU: 1 X 1 data birimi\n* GPU: 1 X N data birimi\n* TPU: N X N data birimi\n\nPerformans olarak:\n\n\n* CPU döngü başına onlarca işlemi idare edebilir.\n* GPU, döngü başına on binlerce işlemi kaldırabilir.\n* TPU, döngü başına 128.000'e kadar işlemi gerçekleştirebilir.\n \nTabi ki, TPU'nun kullanımı uygun olarak ayarlamak ve kullanıma hazır hale getirmek gerekmektedir.\n\n\n\nTek bir Cloud TPU cihazı, her biri iki TPU çekirdeğine sahip dört yongadan oluşur. Yine de Cloud TPU'nun verimli kullanımı için, bir algoritma programı sekiz çekirdeğin her birini kullanmalıdır. \"TPUEstimator\" çoğaltılmış bir hesaplama oluşturmak ve çalıştırmak için bir grafik operatörü sağlar. Her Replica, esasen, her bir çekirdek üzerinde çalıştırılan ve toplam parti boyutunun 1 / 8'ini içeren bir mini parti (mini batch) eğiten, eğitim grafiğinin bir kopyasıdır. Yani eğitimimiz için çalışan ufak minik grafik hesaplayıcılardır. Replica sayısı ile bir çok hyper-parametreyi ayarlayacağız.\n\n\n# Ön Çalışma ve İşleme \n\n* TPU Donanım varlığı test edilmiştir.\n\n> tpu = tf.distribute.cluster_resolver.TPUClusterResolver()   # -> TPU kümesi hakkında bilgi sağlar\n\n> tf.config.experimental_connect_to_cluster(tpu)\n\n> tf.tpu.experimental.initialize_tpu_system(tpu)\n\n> strategy = tf.distribute.experimental.TPUStrategy(tpu)  # ->  TPU configi yapılıyor, ön değerleniyor ve strategy tanımlanıyor\n\n\n> REPLICAS = strategy.num_replicas_in_sync   # -> Gradyan geçişlerinin toplandığı kopya (Replicas) sayısını döndürür.\n"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# TPU or GPU detection\n# Detect hardware, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print(f'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\nAUTO = tf.data.experimental.AUTOTUNE\nREPLICAS = strategy.num_replicas_in_sync\nprint(f'REPLICAS: {REPLICAS}')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Model Parametreleri girilmiştir. TPU'da GPU'da eğitimden farklı olarak strategy tanımlanmakta ve REPLICAS ile parametreler parametrize edilmektedir. Örneğin Batch size 4 * REPLICAS ( bizim durumumuzda 4 * 8=32 olarak) ifade edilmiştir. Burada batch size artırılabilir ve artırılması local minimumlara takılmayı engeller fakat yeterli hafıza olmaması durumunda kodunuz çalışmaz. Eğer kodunuz memory hatası veriyorsa, el mahkum, bu sayıyı küçültmek gerekecektir.\n\nYarışma konusu sınıfalar da teker teker yazılmıştır. Bu bölgedeki kodlar için Martin Görner, https://www.kaggle.com/mgornergoogle 'in çalışmasından yardım alınmıştır ve kendi algoritmamıza göre düzenlenmiştir."},{"metadata":{"trusted":true},"cell_type":"code","source":"BATCH_SIZE = 4 * REPLICAS\nWARMUP_EPOCHS = 3\nWARMUP_LEARNING_RATE = 1e-4 * REPLICAS\nEPOCHS =30\nLEARNING_RATE = 3e-5 * REPLICAS\nHEIGHT = 512\nWIDTH = 512\nCHANNELS = 3\nN_CLASSES = 104\nES_PATIENCE = 5\n\nmodel_path = f'model_{HEIGHT}x{WIDTH}.h5'\n\nGCS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started') + f'/tfrecords-jpeg-{HEIGHT}x{WIDTH}'\n\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')\n\n# Bunu tek tek yazmanıza gerek yok ama inputu tf records olarak verdiklerinden ön işleme uzun sürüyor\nCLASSES = [\n    'pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', \n    'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', \n    'globe thistle', 'snapdragon', \"colt's foot\", 'king protea', 'spear thistle', \n    'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', \n    'balloon flower', 'giant white arum lily', 'fire lily', 'pincushion flower', \n    'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', \n    'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william', \n    'carnation', 'garden phlox', 'love in the mist', 'cosmos',  'alpine sea holly', \n    'ruby-lipped cattleya', 'cape flower', 'great masterwort',  'siam tulip', \n    'lenten rose', 'barberton daisy', 'daffodil',  'sword lily', 'poinsettia', \n    'bolero deep blue',  'wallflower', 'marigold', 'buttercup', 'daisy', \n    'common dandelion', 'petunia', 'wild pansy', 'primula',  'sunflower', \n    'lilac hibiscus', 'bishop of llandaff', 'gaura',  'geranium', 'orange dahlia', \n    'pink-yellow dahlia', 'cautleya spicata',  'japanese anemone', \n    'black-eyed susan', 'silverbush', 'californian poppy',  'osteospermum', \n    'spring crocus', 'iris', 'windflower',  'tree poppy', 'gazania', 'azalea', \n    'water lily',  'rose', 'thorn apple', 'morning glory', 'passion flower',  \n    'lotus', 'toad lily', 'anthurium', 'frangipani',  'clematis', 'hibiscus', \n    'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', \n    'watercress',  'canna lily', 'hippeastrum ', 'bee balm', 'pink quill',  \n    'foxglove', 'bougainvillea', 'camellia', 'mallow',  'mexican petunia',  \n    'bromelia', 'blanket flower', 'trumpet creeper',  'blackberry lily', \n    'common tulip', 'wild rose']","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"* Decode fonksiyonu\n* Etiketli datayı tf record'dan okuma fonksiyonu\n* Etiketlenmemiş datayı tf record'dan okuma fonksiyonu\n* Data seti yükleme\n* Data augmentation --> sağ-sol aynalama, yukarı aşağı aynalama, 90 derece döndürme, rasgele kesme, resize\n* Diğer data ve data görselleştirme fonksiyonları"},{"metadata":{"trusted":true},"cell_type":"code","source":"\nAUTO = tf.data.experimental.AUTOTUNE # instructs the API to read from multiple files if available.\n\ndef decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0\n    image = tf.reshape(image, [HEIGHT, WIDTH, 3])\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        \"class\": 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    return image, label\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"id\": 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['id']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\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    crop_size = tf.random.uniform([], int(HEIGHT*.75), HEIGHT, dtype=tf.int32)\n        \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, lower=0, upper=2)\n    image = tf.image.random_crop(image, size=[crop_size, crop_size, CHANNELS])\n    image = tf.image.resize(image, size=[HEIGHT, WIDTH])\n    image = tf.image.rot90(image)\n    return image, label\n\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_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_training_dataset_preview(ordered=True):\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO)\n    return dataset\n\ndef get_validation_dataset(ordered=False):\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO)\n    return dataset\n\ndef 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)\n    return dataset\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\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":"\nnp.set_printoptions(threshold=15, linewidth=80)\n\ndef batch_to_numpy_images_and_labels(data):\n    images, labels = data\n    numpy_images = images.numpy()\n    numpy_labels = labels.numpy()\n    if numpy_labels.dtype == object: # binary string in this case, these are image ID strings\n        numpy_labels = [None for _ in enumerate(numpy_images)]\n    # If no labels, only image IDs, return None for labels (this is the case for test data)\n    return numpy_images, numpy_labels\n\ndef title_from_label_and_target(label, correct_label):\n    if correct_label is None:\n        return CLASSES[label], True\n    correct = (label == correct_label)\n    return \"{} [{}{}{}]\".format(CLASSES[label], 'OK' if correct else 'NO', u\"\\u2192\" if not correct else '',\n                                CLASSES[correct_label] if not correct else ''), correct\n\ndef display_one_flower(image, title, subplot, red=False, titlesize=16):\n    plt.subplot(*subplot)\n    plt.axis('off')\n    plt.imshow(image)\n    if len(title) > 0:\n        plt.title(title, fontsize=int(titlesize) if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))\n    return (subplot[0], subplot[1], subplot[2]+1)\n\ndef display_batch_of_images(databatch, predictions=None):\n    \"\"\"This will work with:\n    display_batch_of_images(images)\n    display_batch_of_images(images, predictions)\n    display_batch_of_images((images, labels))\n    display_batch_of_images((images, labels), predictions)\n    \"\"\"\n    # data\n    images, labels = batch_to_numpy_images_and_labels(databatch)\n    if labels is None:\n        labels = [None for _ in enumerate(images)]\n        \n    # auto-squaring: this will drop data that does not fit into square or square-ish rectangle\n    rows = int(math.sqrt(len(images)))\n    cols = len(images)//rows\n        \n    # size and spacing\n    FIGSIZE = 13.0\n    SPACING = 0.1\n    subplot=(rows,cols,1)\n    if rows < cols:\n        plt.figure(figsize=(FIGSIZE,FIGSIZE/cols*rows))\n    else:\n        plt.figure(figsize=(FIGSIZE/rows*cols,FIGSIZE))\n    \n    # display\n    for i, (image, label) in enumerate(zip(images[:rows*cols], labels[:rows*cols])):\n        title = '' if label is None else CLASSES[label]\n        correct = True\n        if predictions is not None:\n            title, correct = title_from_label_and_target(predictions[i], label)\n        dynamic_titlesize = FIGSIZE*SPACING/max(rows,cols)*40+3 # magic formula tested to work from 1x1 to 10x10 images\n        subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)\n    \n    #layout\n    plt.tight_layout()\n    if label is None and predictions is None:\n        plt.subplots_adjust(wspace=0, hspace=0)\n    else:\n        plt.subplots_adjust(wspace=SPACING, hspace=SPACING)\n    plt.show()\n    \n# Visualize model predictions\ndef dataset_to_numpy_util(dataset, N):\n    dataset = dataset.unbatch().batch(N)\n    for images, labels in dataset:\n        numpy_images = images.numpy()\n        numpy_labels = labels.numpy()\n        break;  \n    return numpy_images, numpy_labels\n\ndef title_from_label_and_target(label, correct_label):\n    label = np.argmax(label, axis=-1)\n    correct = (label == correct_label)\n    return \"{} [{}{}{}]\".format(CLASSES[label], str(correct), ', shoud be ' if not correct else '',\n                                CLASSES[correct_label] if not correct else ''), correct\n\ndef display_one_flower_eval(image, title, subplot, red=False):\n    plt.subplot(subplot)\n    plt.axis('off')\n    plt.imshow(image)\n    plt.title(title, fontsize=14, color='red' if red else 'black')\n    return subplot+1\n\ndef display_9_images_with_predictions(images, predictions, labels):\n    subplot=331\n    plt.figure(figsize=(13,13))\n    for i, image in enumerate(images):\n        title, correct = title_from_label_and_target(predictions[i], labels[i])\n        subplot = display_one_flower_eval(image, title, subplot, not correct)\n        if i >= 8:\n            break;\n              \n    plt.tight_layout()\n    plt.subplots_adjust(wspace=0.1, hspace=0.1)\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# DATA\n\n* Data Train - Validation - Test olarak ayrılmıştır. \n\ntraining : 12753\nvalidation : 3712\ntest : 7382"},{"metadata":{"trusted":true},"cell_type":"code","source":"\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\ntrain_dataset = get_training_dataset_preview(ordered=True)\ny_train = next(iter(train_dataset.unbatch().map(lambda image, label: label).batch(NUM_TRAINING_IMAGES))).numpy()\nprint(f'Number of training images {NUM_TRAINING_IMAGES}')\n\n\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\nvalid_dataset = get_validation_dataset(ordered=True)\ny_valid = next(iter(valid_dataset.unbatch().map(lambda image, label: label).batch(NUM_VALIDATION_IMAGES))).numpy()\nprint(f'Number of validation images {NUM_VALIDATION_IMAGES}')\n\n\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nprint(f'Number of test images {NUM_TEST_IMAGES}')\ntest_dataset = get_test_dataset(ordered=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display_batch_of_images(next(iter(train_dataset.unbatch().batch(16))))\ntrain_agg = np.asarray([[label, (y_train == index).sum()] for index, label in enumerate(CLASSES)])\nvalid_agg = np.asarray([[label, (y_valid == index).sum()] for index, label in enumerate(CLASSES)])\n\n\n\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Modeller\n\nİlk Model oluşturuldu: Resnet, EfficientNetB6, EfficientNetB7, DenseNet102, DenseNet201 kullanılabilir.Deneyerek performansını görmek gerekir\n\n\"import efficientnet.tfkeras as efn\" ile efficientnet hazır modeli keras'tan çağrılabilir.\n\n* Son layer N_CLASSES (sınıf sayısı=104) kadar nöron içeren softmax olacaktır.\n* Giriş 512,512,3\n* Transfer learning bu case için çok faydalı olacaktır. noisy-student veya imagenet içerisinde çok fazla çiçek fotoğrafı olduğundan dolayı, pre-trained model kullanarak eğitime başlamak avantajlıdır. \n\nPre-trained model kullanırken eğitim yaptığınız konu çok önemlidir, eğer herhangi bir pre-trained modelini içerisinde olmayan örnekler üzerine çalışıyorsanız pre-trained model avantaj yaratmayacaktır."},{"metadata":{"trusted":true},"cell_type":"code","source":"def create_model(input_shape, N_CLASSES):\n    base_model = efn.EfficientNetB6(weights='imagenet', \n                                    include_top=False,\n                                    input_shape=input_shape)\n\n    base_model.trainable = False # Freeze layers\n    model = tf.keras.Sequential([\n        base_model,\n        L.GlobalAveragePooling2D(),\n        L.Dense(N_CLASSES, activation='softmax')])\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Model için Adam optimizer kullanılıldı. Burada farklı şeyler kullanmak mümkün, deneme yanılma ile seçmek gerekecek. Deneme yanılma ile seçtiğimiz parametrelere \"hyper parametre\" deriz. Bu parametreler Cross-validation dediğimiz çapraz gerçekleme ile belirlenmelidir.\n\nloss için ise categorical corss entropy kullanılabileceği gibi, Sparse Categorical Crossentropy de kullanılabilir.\nbknz: https://keras.io/api/optimizers/"},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model = create_model((None, None, CHANNELS), N_CLASSES)\n    \nmetric_list = ['sparse_categorical_accuracy']\n\noptimizer = optimizers.Adam(lr=WARMUP_LEARNING_RATE)\nmodel.compile(optimizer=optimizer, \n              loss=losses.SparseCategoricalCrossentropy(), \n              metrics=metric_list)\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"EfficientNetB6 modeli için ön ısınma turu \"warm up\" konulabilir. Burada 3 epoch layerları dondurulmuş modeli görmekteyiz, çok bir katkısı olmayabilir. Ama genelde büyük modeller üstünde transfer learning yaparken belirli bir epcoh sayısında ilk layerları dondurarak daha çok son layerları eğitiriz. Bunun sebebi ilk layerların temel geometrik şekilleri ve anlamları öğrenmesidir. "},{"metadata":{"trusted":true},"cell_type":"code","source":"STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nwarmup_history = model.fit(x=get_training_dataset(), \n                           steps_per_epoch=STEPS_PER_EPOCH, \n                           validation_data=get_validation_dataset(),\n                           epochs=WARMUP_EPOCHS, \n                           verbose=1).history\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Learning rate'i dinamik vermek mümkündür. Burada farklı stratejiler güdülebilir. Ama temel trend düşük bir learning rate'den başlayarak önce biraz artırmak sonra azaltmaktır. Bu işin temel mantığı optimizasyon teorisine kadar gider. yapay sinir ağları hafıza bakımından en iyi gradient descent tarzı basit optimizasyon modelleri ile verimli çalıştığından dolayı, learning rate ana parametredir ( ilk başlangıç noktası da önemlidir, onu pre-trained model ile sağlıyoruz ). Local minimalara takılmadan gitmek için bu tarz stratejileri öneririm. Bu stratejiyi daha sonra model'i fit ederken callsback_learningrate olarak tanımlayacağız."},{"metadata":{"trusted":true},"cell_type":"code","source":"\nLR_START = 0.00000001\nLR_MIN = 0.000001\nLR_MAX = LEARNING_RATE\nLR_RAMPUP_EPOCHS = 4\nLR_SUSTAIN_EPOCHS = 1\nLR_EXP_DECAY = .81\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    \nrng = [i for i in range(EPOCHS)]\ny = [lrfn(x) for x in rng]\n\nsns.set(style='whitegrid')\nfig, ax = plt.subplots(figsize=(20, 7))\nplt.plot(rng, y)\n\nprint(f'{EPOCHS} total epochs and {NUM_TRAINING_IMAGES//BATCH_SIZE} steps per epoch')\nprint(f'Learning rate schedule: {y[0]:.3g} to {max(y):.3g} to {y[-1]:.3g}')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Dondurduğumuz layerları açtık. Tüm modeli yazdık.\n\noptimizer https://keras.io/api/optimizers/ 'dan seçilebilir. Nadam, Adam, SGD, RMSprop optimizerları arasından en iyi perform verecek optimizer cross-validation ile seçilebilir."},{"metadata":{"trusted":true},"cell_type":"code","source":"for layer in model.layers:\n    layer.trainable = True # Unfreeze layers\n\ncheckpoint = ModelCheckpoint(model_path, monitor='val_loss', mode='min', save_best_only=True)\nes = EarlyStopping(monitor='val_loss', mode='min', patience=ES_PATIENCE, \n                   restore_best_weights=True, verbose=1)\nlr_callback = LearningRateScheduler(lrfn, verbose=0)\n\ncallback_list = [checkpoint, es, lr_callback]\n\noptimizer = optimizers.Adam(lr=LEARNING_RATE)\nmodel.compile(optimizer=optimizer, \n              loss='sparse_categorical_crossentropy', \n              metrics=metric_list)\nmodel.summary()\n\nSVG(tf.keras.utils.model_to_dot(model, dpi=70).create(prog='dot', format='svg'))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Modeli çalıştırdırk."},{"metadata":{"trusted":true},"cell_type":"code","source":"STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\nhistory = model.fit(x=get_training_dataset(), \n                    steps_per_epoch=STEPS_PER_EPOCH, \n                    validation_data=get_validation_dataset(), \n                    callbacks=callback_list, \n                    epochs=30, \n                    verbose=1).history","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Loss grafiği"},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_metrics(history, metric_list):\n    fig, axes = plt.subplots(len(metric_list), 1, sharex='col', figsize=(24, 12))\n    axes = axes.flatten()\n    \n    for index, metric in enumerate(metric_list):\n        axes[index].plot(history[metric], label=f'Train {metric}')\n        axes[index].plot(history[f'val_{metric}'], label=f'Validation {metric}')\n        axes[index].legend(loc='best', fontsize=16)\n        axes[index].set_title(metric)\n\n    plt.xlabel('Epochs', fontsize=16)\n    sns.despine()\n    plt.show()\n\nplot_metrics(history, metric_list=['loss', 'sparse_categorical_accuracy'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Test Sonuçları"},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_test = test_dataset.map(lambda image, idnum: image)\ntest_preds = model.predict(x_test)\ntest_preds = np.argmax(test_preds, axis=-1)\n\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')\n\nsubmission = pd.DataFrame(test_ids, columns=['id'])\nsubmission['label'] = test_preds\nsubmission.to_csv('submission.csv', index=False)\ndisplay(submission.head(12))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# DenseNet201 - Optional\n\nDenseNet102 ve DenseNet201 de güzel modellerdir. Dense yapısı ile başarım göstermektedirler. Efficient Net çoğu durumda DenseNEt'i outperform etse dahi dataya göre farklı öodeller denemek gerekir."},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.applications import DenseNet121\nfrom tensorflow.keras.applications import DenseNet201\nimport cv2\nfrom IPython.display import SVG\n\n\n\n\n\ndef create_model2(input_shape, N_CLASSES):\n    model2 = tf.keras.models.Sequential()\n\n    model2.add(DenseNet201(\n                     input_shape=(512,512,3),\n                     weights = 'imagenet',\n                     include_top=False))\n\n    model2.add(tf.keras.layers.GlobalAveragePooling2D())\n\n    model2.add(tf.keras.layers.Dense(N_CLASSES,\n                                   activation='softmax'))\n\n\n    \n    return model2\n\nwith strategy.scope():\n    model2 = create_model2((None, None, CHANNELS), N_CLASSES)\n    \n\n\ncheckpoint = ModelCheckpoint(model_path, monitor='val_loss', mode='min', save_best_only=True)\nes = EarlyStopping(monitor='val_loss', mode='min', patience=ES_PATIENCE, \n                   restore_best_weights=True, verbose=1)\nlr_callback = LearningRateScheduler(lrfn, verbose=0)\n\ncallback_list = [checkpoint, es, lr_callback]\n\noptimizer = optimizers.Adam(lr=LEARNING_RATE)\nmodel2.compile(optimizer=optimizer, \n              loss='sparse_categorical_crossentropy', \n              metrics=metric_list)\nmodel2.summary()\n\n\n\n    \nSVG(tf.keras.utils.model_to_dot(model2, dpi=70).create(prog='dot', format='svg'))\n                                   ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nhistory = model2.fit(x=get_training_dataset(), \n                    steps_per_epoch=STEPS_PER_EPOCH, \n                    validation_data=get_validation_dataset(), \n                    callbacks=callback_list, \n                    epochs=30, \n                    verbose=1).history","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Generating submission.csv file...')\n\n# Get image ids from test set and convert to unicode\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')\n\n# Write the submission file\nnp.savetxt(\n    'submission.csv',\n    np.rec.fromarrays([test_ids,test_preds]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n)\n\n# Look at the first few predictions\n!head submission.csv","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}