{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import layers, models\nfrom kaggle_datasets import KaggleDatasets\nimport numpy as np\nimport pandas as pd\nimport os\n\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2023-11-12T22:25:33.834525Z","iopub.execute_input":"2023-11-12T22:25:33.835540Z","iopub.status.idle":"2023-11-12T22:25:39.291141Z","shell.execute_reply.started":"2023-11-12T22:25:33.835432Z","shell.execute_reply":"2023-11-12T22:25:39.290086Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Detect my accelerator","metadata":{}},{"cell_type":"code","source":"\n# Detect hardware, return appropriate distribution strategy\ntry:\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\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2023-11-12T22:25:39.293287Z","iopub.execute_input":"2023-11-12T22:25:39.294291Z","iopub.status.idle":"2023-11-12T22:25:39.306798Z","shell.execute_reply.started":"2023-11-12T22:25:39.294247Z","shell.execute_reply":"2023-11-12T22:25:39.305980Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Get my data path","metadata":{}},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path() # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"","metadata":{"execution":{"iopub.status.busy":"2023-11-12T22:25:39.307881Z","iopub.execute_input":"2023-11-12T22:25:39.308207Z","iopub.status.idle":"2023-11-12T22:25:39.753230Z","shell.execute_reply.started":"2023-11-12T22:25:39.308180Z","shell.execute_reply":"2023-11-12T22:25:39.752215Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Set some parameters","metadata":{}},{"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE\n\n#IMAGE_SIZE = [224, 224] # at this size, a GPU will run out of memory. Use the TPU\nIMAGE_SIZE = [331, 331] # at this size, a GPU will run out of memory. Use the TPU\n#IMAGE_SIZE = [512, 512] # at this size, a GPU will run out of memory. Use the TPU\nEPOCHS = 5\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nNUM_TRAINING_IMAGES = 12753\nNUM_TEST_IMAGES = 7382\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE","metadata":{"execution":{"iopub.status.busy":"2023-11-12T22:25:39.755344Z","iopub.execute_input":"2023-11-12T22:25:39.755671Z","iopub.status.idle":"2023-11-12T22:25:39.761279Z","shell.execute_reply.started":"2023-11-12T22:25:39.755640Z","shell.execute_reply":"2023-11-12T22:25:39.760310Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load my data\n\nThis data is loaded from Kaggle and automatically sharded to maximize parallelization.","metadata":{}},{"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    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 # 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        \"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    # 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)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef get_training_dataset():\n    #dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-224x224/train/*.tfrec'), labeled=True)\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-331x331/train/*.tfrec'), labeled=True)\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_validation_dataset():\n    #dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-224x224/val/*.tfrec'), labeled=True, ordered=False)\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-331x331/val/*.tfrec'), labeled=True, ordered=False)\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 get_test_dataset(ordered=False):\n    #dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-224x224/test/*.tfrec'), labeled=False, ordered=ordered)\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-331x331/test/*.tfrec'), 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\ntraining_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()","metadata":{"execution":{"iopub.status.busy":"2023-11-12T22:25:39.762680Z","iopub.execute_input":"2023-11-12T22:25:39.763068Z","iopub.status.idle":"2023-11-12T22:25:43.892108Z","shell.execute_reply.started":"2023-11-12T22:25:39.763032Z","shell.execute_reply":"2023-11-12T22:25:43.890985Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Build a model.","metadata":{}},{"cell_type":"code","source":"with strategy.scope():    \n    #pretrained_model = tf.keras.applications.VGG16(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n    pretrained_model = tf.keras.applications.MobileNetV2(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n    pretrained_model.trainable = False # tramsfer learning\n    \n    model = tf.keras.Sequential([\n        pretrained_model,\n        #tf.keras.layers.MaxPooling2D(),\n        #tf.keras.layers.Dense(104, activation='softmax'),\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(104, activation='softmax')\n    ])\n\n    \n# # Build a simple convolutional neural network (CNN) model\n# model = models.Sequential()\n# model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)))\n# model.add(layers.MaxPooling2D((2, 2)))\n# model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n# model.add(layers.MaxPooling2D((2, 2)))\n# model.add(layers.Conv2D(128, (3, 3), activation='relu'))\n# model.add(layers.MaxPooling2D((2, 2)))\n# model.add(layers.Flatten())\n# model.add(layers.Dense(128, activation='relu'))\n# model.add(layers.Dense(104, activation='softmax'))\n        \nmodel.compile(\n    optimizer = 'adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics = ['accuracy']\n)\n\nhistorical = model.fit(training_dataset, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS, \n          validation_data=validation_dataset)","metadata":{"execution":{"iopub.status.busy":"2023-11-12T22:25:43.893380Z","iopub.execute_input":"2023-11-12T22:25:43.893679Z","iopub.status.idle":"2023-11-12T22:29:03.989624Z","shell.execute_reply.started":"2023-11-12T22:25:43.893652Z","shell.execute_reply":"2023-11-12T22:29:03.988755Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Unfreeze the pretrained model\npretrained_model.trainable = True\n\n# Unfreeze the last 'N' layers\nN = 5  # Number of layers to unfreeze\nfor layer in pretrained_model.layers[-N:]:\n    layer.trainable = True\n\n\n# Compile the model with a lower learning rate\nmodel.compile(\n    optimizer=tf.keras.optimizers.RMSprop(learning_rate=1e-4),\n    loss='sparse_categorical_crossentropy',\n    metrics=['accuracy']\n)\n\n# Continue training\nfine_tune_epochs = 5  # Additional number of epochs for fine-tuning\ntotal_epochs = EPOCHS + fine_tune_epochs\n\nhistorical_fine = model.fit(\n    training_dataset,\n    steps_per_epoch=STEPS_PER_EPOCH,\n    epochs=total_epochs,\n    initial_epoch=historical.epoch[-1],  # Start from the last epoch of the previous training\n    validation_data=validation_dataset\n)\n","metadata":{"execution":{"iopub.status.busy":"2023-11-12T22:29:03.991081Z","iopub.execute_input":"2023-11-12T22:29:03.991366Z","iopub.status.idle":"2023-11-12T22:45:18.201537Z","shell.execute_reply.started":"2023-11-12T22:29:03.991341Z","shell.execute_reply":"2023-11-12T22:45:18.200452Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Compute your predictions on the test set!\n\nThis will create a file that can be submitted to the competition.","metadata":{}},{"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 = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)\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, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')","metadata":{"execution":{"iopub.status.busy":"2023-11-12T22:45:18.203438Z","iopub.execute_input":"2023-11-12T22:45:18.203865Z","iopub.status.idle":"2023-11-12T22:45:42.821898Z","shell.execute_reply.started":"2023-11-12T22:45:18.203825Z","shell.execute_reply":"2023-11-12T22:45:42.820837Z"},"trusted":true},"execution_count":null,"outputs":[]}]}