{"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":"# 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\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\n\nimport os\nimport shutil\nimport random\nimport re\n\nimport pandas as pd\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\nfrom kaggle_datasets import KaggleDatasets","metadata":{"execution":{"iopub.status.busy":"2023-10-28T11:42:31.262418Z","iopub.execute_input":"2023-10-28T11:42:31.262766Z","iopub.status.idle":"2023-10-28T11:42:32.112838Z","shell.execute_reply.started":"2023-10-28T11:42:31.262734Z","shell.execute_reply":"2023-10-28T11:42:32.109403Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"source_dataset_root = '/kaggle/input/leafsnap-dataset/leafsnap-dataset/dataset/images/field'\ntarget_dataset_root = '/kaggle/working/dataset'\n# Create the target directory if it doesn't exist\nos.makedirs(target_dataset_root, exist_ok=True)\n\n# Define the subdirectories for train and validation datasets\ntrain_dir = os.path.join(target_dataset_root, 'train')\nvalidation_dir = os.path.join(target_dataset_root, 'validation')\ntest_dir = os.path.join(target_dataset_root, 'test')\n\n# Create train and validation directories if they don't exist\nos.makedirs(train_dir, exist_ok=True)\nos.makedirs(validation_dir, exist_ok=True)\nos.makedirs(test_dir, exist_ok=True)\n\nvalidation_fraction = 0.2\ntest_fraction = 0.2\n\nfor plant_category in os.listdir(source_dataset_root):\n    source_category_dir = os.path.join(source_dataset_root, plant_category)\n    target_train_category_dir = os.path.join(train_dir, plant_category)\n    target_validation_category_dir = os.path.join(validation_dir, plant_category)\n    target_test_category_dir = os.path.join(test_dir, plant_category)\n\n    # Create target directories for this class\n    os.makedirs(target_train_category_dir, exist_ok=True)\n    os.makedirs(target_validation_category_dir, exist_ok=True)\n    os.makedirs(target_test_category_dir, exist_ok=True)\n\n    # Get a list of all image files in the class directory\n    image_files = os.listdir(source_category_dir)\n\n    # Calculate the number of images for validation and test sets\n    num_images = len(image_files)\n    num_validation_images = int(num_images * validation_fraction)\n    num_test_images = int(num_images * test_fraction)\n\n    # Randomly shuffle the image files\n    random.shuffle(image_files)\n\n    # Split the images into train, validation, and test sets\n    validation_images = image_files[:num_validation_images]\n    test_images = image_files[num_validation_images:num_validation_images + num_test_images]\n    train_images = image_files[num_validation_images + num_test_images:]\n\n    # Copy images to their respective directories\n    for image_file in validation_images:\n        source_path = os.path.join(source_category_dir, image_file)\n        destination_path = os.path.join(target_validation_category_dir, image_file)\n        shutil.copyfile(source_path, destination_path)\n\n    for image_file in test_images:\n        source_path = os.path.join(source_category_dir, image_file)\n        destination_path = os.path.join(target_test_category_dir, image_file)\n        shutil.copyfile(source_path, destination_path)\n\n    for image_file in train_images:\n        source_path = os.path.join(source_category_dir, image_file)\n        destination_path = os.path.join(target_train_category_dir, image_file)\n        shutil.copyfile(source_path, destination_path)\n\nprint(\"Train, validation, and test datasets created successfully.\")\n\n\n\n#for dirname, _, filenames in os.walk('/kaggle/input/leafsnap-dataset/leafsnap-dataset/dataset'):\n#    for filename in filenames:\n#        print(os.path.join(dirname, filename))\n\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","metadata":{"execution":{"iopub.status.busy":"2023-10-28T11:42:32.113712Z","iopub.status.idle":"2023-10-28T11:42:32.114087Z","shell.execute_reply.started":"2023-10-28T11:42:32.113898Z","shell.execute_reply":"2023-10-28T11:42:32.113916Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = 224\nBATCH_SIZE = 32\nGCS_DS_PATH = KaggleDatasets().get_gcs_path(\"tpu-getting-started\")\nGCS_PATH = GCS_DS_PATH + f\"/tfrecords-jpeg-{IMAGE_SIZE}x{IMAGE_SIZE}\"\nAUTO = tf.data.experimental.AUTOTUNE\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\nCLASSES = ['pink primrose',    'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea',     'wild geranium',     'tiger lily',           'moon orchid',              'bird of paradise', 'monkshood',        'globe thistle',         # 00 - 09\n           'snapdragon',       \"colt's foot\",               'king protea',      'spear thistle', 'yellow iris',       'globe-flower',         'purple coneflower',        'peruvian lily',    'balloon flower',   'giant white arum lily', # 10 - 19\n           'fire lily',        'pincushion flower',         'fritillary',       'red ginger',    'grape hyacinth',    'corn poppy',           'prince of wales feathers', 'stemless gentian', 'artichoke',        'sweet william',         # 20 - 29\n           'carnation',        'garden phlox',              'love in the mist', 'cosmos',        'alpine sea holly',  'ruby-lipped cattleya', 'cape flower',              'great masterwort', 'siam tulip',       'lenten rose',           # 30 - 39\n           'barberton daisy',  'daffodil',                  'sword lily',       'poinsettia',    'bolero deep blue',  'wallflower',           'marigold',                 'buttercup',        'daisy',            'common dandelion',      # 40 - 49\n           'petunia',          'wild pansy',                'primula',          'sunflower',     'lilac hibiscus',    'bishop of llandaff',   'gaura',                    'geranium',         'orange dahlia',    'pink-yellow dahlia',    # 50 - 59\n           'cautleya spicata', 'japanese anemone',          'black-eyed susan', 'silverbush',    'californian poppy', 'osteospermum',         'spring crocus',            'iris',             'windflower',       'tree poppy',            # 60 - 69\n           'gazania',          'azalea',                    'water lily',       'rose',          'thorn apple',       'morning glory',        'passion flower',           'lotus',            'toad lily',        'anthurium',             # 70 - 79\n           'frangipani',       'clematis',                  'hibiscus',         'columbine',     'desert-rose',       'tree mallow',          'magnolia',                 'cyclamen ',        'watercress',       'canna lily',            # 80 - 89\n           'hippeastrum ',     'bee balm',                  'pink quill',       'foxglove',      'bougainvillea',     'camellia',             'mallow',                   'mexican petunia',  'bromelia',         'blanket flower',        # 90 - 99\n           'trumpet creeper',  'blackberry lily',           'common tulip',     'wild rose']                                                                                                                                               # 100 - 102","metadata":{"execution":{"iopub.status.busy":"2023-10-28T11:42:32.115384Z","iopub.status.idle":"2023-10-28T11:42:32.115743Z","shell.execute_reply.started":"2023-10-28T11:42:32.11558Z","shell.execute_reply":"2023-10-28T11:42:32.115596Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Helper functions","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, IMAGE_SIZE, 3]) # explicit size needed for TPU\n    return image\n\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, tf.one_hot(label, len(CLASSES)) # returns a dataset of (image, label) pairs\n\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\n\ndef load_dataset(filenames, labeled: bool = True, ordered: bool = 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\n\ndef data_augment(image, label):\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_brightness(image, max_delta=0.5)\n    image = tf.image.random_contrast(image, lower=0.1, upper=0.9)\n    image = tf.image.rot90(image, k=tf.random.uniform([], 0, 4, dtype=tf.int32))\n    return image, label   \n\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\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\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\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec\n    # files, i.e. flowers00-230.tfrec = 230 data items\n    return sum(int(re.search(r\"-([0-9]*)\\.\", x).group(1)) for x in filenames)\n\n\ndef get_resnet_model():\n    # Load the ResNet50 model with pre-trained weights\n    backbone = tf.keras.applications.ResNet50(\n        include_top=False,\n        weights=\"imagenet\",\n        input_shape=[IMAGE_SIZE, IMAGE_SIZE, 3],\n    )\n    model = tf.keras.models.Sequential(\n        [\n            backbone,\n            tf.keras.layers.GlobalAveragePooling2D(),\n            tf.keras.layers.Dense(len(CLASSES), activation=\"softmax\"),\n        ]\n    )\n    model.compile(\n        optimizer=tf.keras.optimizers.Adam(learning_rate=1e-4),\n        loss=\"categorical_crossentropy\",\n        metrics=[\"accuracy\"],\n    )\n    return model","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-10-28T11:42:32.119069Z","iopub.status.idle":"2023-10-28T11:42:32.11941Z","shell.execute_reply.started":"2023-10-28T11:42:32.119256Z","shell.execute_reply":"2023-10-28T11:42:32.119271Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import ResNet50\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D\nfrom tensorflow.keras.models import Model\n# Data preprocessing\n# Split data into training and testing sets, and appling necessary preprocessing like resizing and normalization.\ndatagen = ImageDataGenerator(\n    rescale=1.0 / 255,\n)","metadata":{"execution":{"iopub.status.busy":"2023-10-28T11:42:32.120959Z","iopub.status.idle":"2023-10-28T11:42:32.121355Z","shell.execute_reply.started":"2023-10-28T11:42:32.121167Z","shell.execute_reply":"2023-10-28T11:42:32.121183Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = datagen.flow_from_directory(\n    '/kaggle/working/dataset/train',\n    target_size=(224, 224),\n    batch_size=32,\n    class_mode='categorical',\n)","metadata":{"execution":{"iopub.status.busy":"2023-10-28T11:42:32.12213Z","iopub.status.idle":"2023-10-28T11:42:32.122439Z","shell.execute_reply.started":"2023-10-28T11:42:32.122288Z","shell.execute_reply":"2023-10-28T11:42:32.122302Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_generator = datagen.flow_from_directory(\n   '/kaggle/working/dataset/test',\n    target_size=(224, 224),\n    batch_size=32,\n    class_mode='categorical'\n)","metadata":{"execution":{"iopub.status.busy":"2023-10-28T11:42:32.124203Z","iopub.status.idle":"2023-10-28T11:42:32.124651Z","shell.execute_reply.started":"2023-10-28T11:42:32.124407Z","shell.execute_reply":"2023-10-28T11:42:32.124428Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validation_generator = datagen.flow_from_directory(\n    '/kaggle/working/dataset/validation',\n    target_size=(224, 224),\n    batch_size=32,\n    class_mode='categorical',\n)","metadata":{"execution":{"iopub.status.busy":"2023-10-28T11:42:32.125584Z","iopub.status.idle":"2023-10-28T11:42:32.126175Z","shell.execute_reply.started":"2023-10-28T11:42:32.125789Z","shell.execute_reply":"2023-10-28T11:42:32.125811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import random\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\n# Define the root directory of your dataset\ndataset_root = '/kaggle/working/dataset/train'\n\n# Get a list of all plant categories (subdirectories)\nplant_categories = os.listdir(dataset_root)\n\n# Initialize a counter for the displayed images\ndisplayed_images = 0\n\n# Set the number of images you want to display\nnum_images_to_display = 25\n\n# Create a subplot for displaying the images\nplt.figure(figsize=(10, 10))\nplt.subplots_adjust(wspace=0.4, hspace=0.4)\n\nwhile displayed_images < num_images_to_display:\n    # Randomly select a category\n    selected_category = random.choice(plant_categories)\n    \n    # Get a list of all images in the selected category\n    image_files = os.listdir(os.path.join(dataset_root, selected_category))\n    \n    # Randomly select an image from the category\n    selected_image_file = random.choice(image_files)\n    \n    # Load and display the selected image\n    image_path = os.path.join(dataset_root, selected_category, selected_image_file)\n    image = Image.open(image_path)\n    \n    plt.subplot(5, 5, displayed_images + 1)\n    plt.imshow(image)\n    plt.title(f\"Category: {selected_category}\")\n    plt.axis('off')\n    \n    displayed_images += 1\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-10-28T11:42:32.127261Z","iopub.status.idle":"2023-10-28T11:42:32.127734Z","shell.execute_reply.started":"2023-10-28T11:42:32.127484Z","shell.execute_reply":"2023-10-28T11:42:32.127508Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the number of plant species (classes) in your dataset\nnum_classes = 184\n# Load a pre-trained CNN model (e.g., ResNet50)\nbase_model = ResNet50(weights='imagenet', include_top=False)","metadata":{"execution":{"iopub.status.busy":"2023-10-28T11:42:32.129007Z","iopub.status.idle":"2023-10-28T11:42:32.129451Z","shell.execute_reply.started":"2023-10-28T11:42:32.129226Z","shell.execute_reply":"2023-10-28T11:42:32.129247Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Add a custom output layer for classification\nx = base_model.output\nx = GlobalAveragePooling2D()(x)\nx = Dense(1024, activation='relu')(x)\npredictions = Dense(num_classes, activation='softmax')(x)","metadata":{"execution":{"iopub.status.busy":"2023-10-28T11:42:32.131039Z","iopub.status.idle":"2023-10-28T11:42:32.131415Z","shell.execute_reply.started":"2023-10-28T11:42:32.131239Z","shell.execute_reply":"2023-10-28T11:42:32.131255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Model(inputs=base_model.input, outputs=predictions)","metadata":{"_kg_hide-input":false,"execution":{"iopub.status.busy":"2023-10-28T11:42:32.132344Z","iopub.status.idle":"2023-10-28T11:42:32.132667Z","shell.execute_reply.started":"2023-10-28T11:42:32.132508Z","shell.execute_reply":"2023-10-28T11:42:32.132524Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Compile the model\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2023-10-28T11:42:32.134027Z","iopub.status.idle":"2023-10-28T11:42:32.134354Z","shell.execute_reply.started":"2023-10-28T11:42:32.134199Z","shell.execute_reply":"2023-10-28T11:42:32.134214Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# TRAIN PLANT MODEL","metadata":{}},{"cell_type":"code","source":"epochs = 45\n\nhistory = model.fit(\n    train_generator,\n    epochs=epochs,\n    validation_data=validation_generator,\n)\n# Evaluate the model on the test set\ntest_loss, test_accuracy = model.evaluate(test_generator)\nprint(f\"Test Loss: {test_loss}, Test Accuracy: {test_accuracy}\")\n# Save the model to a file\nmodel.save('/kaggle/working/plant_species_model.h5')","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2023-10-28T11:42:32.136895Z","iopub.status.idle":"2023-10-28T11:42:32.137251Z","shell.execute_reply.started":"2023-10-28T11:42:32.137059Z","shell.execute_reply":"2023-10-28T11:42:32.137074Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save('/kaggle/working/plant_species_model.h5')","metadata":{"execution":{"iopub.status.busy":"2023-10-28T11:42:32.13866Z","iopub.status.idle":"2023-10-28T11:42:32.138997Z","shell.execute_reply.started":"2023-10-28T11:42:32.138839Z","shell.execute_reply":"2023-10-28T11:42:32.138854Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Extract the training and validation loss and accuracy from the history\ntrain_loss = history.history['loss']\nval_loss = history.history['val_loss']\ntrain_accuracy = history.history['accuracy']\nval_accuracy = history.history['val_accuracy']\n\n# Create subplots for loss and accuracy\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))\n\n# Plot the training and validation loss\nax1.set_title('Model Loss')\nax1.plot(train_loss, label='train')\nax1.plot(val_loss, label='validation')\nax1.set_xlabel('Epochs')\nax1.set_ylabel('Loss')\nax1.legend()\n\n# Plot the training and validation accuracy\nax2.set_title('Model Accuracy')\nax2.plot(train_accuracy, label='train')\nax2.plot(val_accuracy, label='validation')\nax2.set_xlabel('Epochs')\nax2.set_ylabel('Accuracy')\nax2.legend()\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-10-28T11:42:32.140154Z","iopub.status.idle":"2023-10-28T11:42:32.140452Z","shell.execute_reply.started":"2023-10-28T11:42:32.140302Z","shell.execute_reply":"2023-10-28T11:42:32.140316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# prediction","metadata":{}},{"cell_type":"code","source":"from PIL import Image\n\n# Define the test directory\ntest_dir = '/kaggle/working/dataset/test'  \n\n# Replace 'your_model.h5' with the actual path to your trained model\nmodel = tf.keras.models.load_model('plant_species_model.h5')\n\n# Get a list of all test image files\ntest_image_files = []\nfor category in plant_categories:\n    test_category_dir = os.path.join(test_dir, category)\n    test_image_files.extend([os.path.join(test_category_dir, file) for file in os.listdir(test_category_dir)])\n\n# Randomly select 25 test images\nrandom.seed(42)\nselected_test_images = random.sample(test_image_files, 25)\n\n# Create a subplot for displaying the images and predictions\nplt.figure(figsize=(15, 15))\nfor i, image_path in enumerate(selected_test_images, 1):\n    image = Image.open(image_path)\n    img_array = np.array(image)\n    img_array = np.expand_dims(img_array, axis=0)\n    \n    # Make predictions using the model\n    predictions = model.predict(img_array)\n    \n    plt.subplot(5, 5, i)\n    plt.imshow(image)\n    plt.title(f\"Category: {plant_categories[np.argmax(predictions)]}\\nActual: {os.path.basename(os.path.dirname(image_path))}\")\n    plt.axis('off')\n\nplt.show()","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2023-10-28T11:42:32.14165Z","iopub.status.idle":"2023-10-28T11:42:32.141984Z","shell.execute_reply.started":"2023-10-28T11:42:32.141819Z","shell.execute_reply":"2023-10-28T11:42:32.141835Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load flower data","metadata":{}},{"cell_type":"code","source":"num_training_images = count_data_items(TRAINING_FILENAMES)\nnum_validation_images = count_data_items(VALIDATION_FILENAMES)\nnum_test_images = count_data_items(TEST_FILENAMES)\n\nprint(f\"Number of training images:   {num_training_images:,d}.\")\nprint(f\"Number of validation images: {num_validation_images:,d}.\")\nprint(f\"Number of testing images:    {num_test_images:,d}.\")\n\ntrain_dataset = get_training_dataset()\nval_dataset = get_validation_dataset()\ntest_dataset = get_test_dataset(ordered=True)","metadata":{"execution":{"iopub.status.busy":"2023-10-28T11:42:32.142967Z","iopub.status.idle":"2023-10-28T11:42:32.143315Z","shell.execute_reply.started":"2023-10-28T11:42:32.143155Z","shell.execute_reply":"2023-10-28T11:42:32.143171Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"figure, axes = plt.subplots(5, 5, figsize=(12, 12))\naxes = [y for x in axes for y in x]\n\nfor i, sample in enumerate(train_dataset.unbatch().take(25).as_numpy_iterator()):\n    axes[i].imshow(sample[0])\n    \n    flower_type = CLASSES[tf.argmax(sample[1]).numpy()]\n    axes[i].set_title(flower_type)\n    axes[i].axis('off')","metadata":{"execution":{"iopub.status.busy":"2023-10-28T11:42:32.145056Z","iopub.status.idle":"2023-10-28T11:42:32.145395Z","shell.execute_reply.started":"2023-10-28T11:42:32.145242Z","shell.execute_reply":"2023-10-28T11:42:32.145257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nmodel_resnet = get_resnet_model()\nmodel_resnet.summary()","metadata":{"execution":{"iopub.status.busy":"2023-10-28T11:42:32.146454Z","iopub.status.idle":"2023-10-28T11:42:32.146832Z","shell.execute_reply.started":"2023-10-28T11:42:32.146656Z","shell.execute_reply":"2023-10-28T11:42:32.146673Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Train Model**","metadata":{}},{"cell_type":"code","source":"# Train the ResNet50 model\nhistory_resnet = model_resnet.fit(\n    train_dataset,\n    validation_data=val_dataset,\n    epochs=25,\n    steps_per_epoch=num_training_images // BATCH_SIZE,\n    validation_steps=num_validation_images // BATCH_SIZE,\n    callbacks=[\n        tf.keras.callbacks.ModelCheckpoint(\n            \"resnet50_flower_species_model.h5\", \n            monitor=\"val_accuracy\",\n            mode=\"max\", \n            save_best_only=True,\n            save_weights_only=True,\n            verbose=1,\n        ),\n        tf.keras.callbacks.ReduceLROnPlateau(\n            monitor='val_accuracy',\n            mode='max',\n            patience=5,\n            min_lr=1e-6,\n            verbose=2,\n        ),\n    ],\n    verbose=1 if os.environ[\"KAGGLE_KERNEL_RUN_TYPE\"] == \"Interactive\" else 2,\n).history","metadata":{"execution":{"iopub.status.busy":"2023-10-28T11:42:32.147982Z","iopub.status.idle":"2023-10-28T11:42:32.148357Z","shell.execute_reply.started":"2023-10-28T11:42:32.148186Z","shell.execute_reply":"2023-10-28T11:42:32.148203Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**To free space**","metadata":{}},{"cell_type":"code","source":"import shutil\n\n# Define the directory path to be deleted\ndirectory_to_delete = '/kaggle/working/dataset'\n\n# Use shutil.rmtree() to delete the directory and its contents\nshutil.rmtree(directory_to_delete)\n\n# Confirm the deletion\nprint(f\"Directory '{directory_to_delete}' and its contents have been deleted.\")\n","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-10-28T11:42:32.149528Z","iopub.status.idle":"2023-10-28T11:42:32.149823Z","shell.execute_reply.started":"2023-10-28T11:42:32.149673Z","shell.execute_reply":"2023-10-28T11:42:32.149687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"figure, axes = plt.subplots(1, 1, figsize=(8, 8))\n\nepochs = list(range(len(history_resnet[\"loss\"])))\n\naxes.plot(epochs, history_resnet[\"accuracy\"], label=\"train\")\naxes.plot(epochs, history_resnet[\"val_accuracy\"], label=\"validation\")\naxes.set_title(\"Learning Curves\")\naxes.set_xlabel(\"Epoch\")\naxes.set_ylabel(\"Accuracy\")\naxes.legend()\naxes.grid()","metadata":{"execution":{"iopub.status.busy":"2023-10-28T11:42:32.151403Z","iopub.status.idle":"2023-10-28T11:42:32.15174Z","shell.execute_reply.started":"2023-10-28T11:42:32.151575Z","shell.execute_reply":"2023-10-28T11:42:32.151591Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Saving Model","metadata":{}},{"cell_type":"code","source":"\nmodel_path = '/kaggle/working/flower_species_model.h5'\nif os.path.exists(model_path):\n    print(\"Model file exists.\")\nelse:\n    print(\"Model file does not exist.\")","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-10-28T11:42:32.154854Z","iopub.status.idle":"2023-10-28T11:42:32.155209Z","shell.execute_reply.started":"2023-10-28T11:42:32.155023Z","shell.execute_reply":"2023-10-28T11:42:32.155038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save(\"resnet50_flower_species_model.h5\")","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-10-28T11:42:32.156033Z","iopub.status.idle":"2023-10-28T11:42:32.156375Z","shell.execute_reply.started":"2023-10-28T11:42:32.156211Z","shell.execute_reply":"2023-10-28T11:42:32.156227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.models import load_model\n\n# Recreate the model architecture\n# Replace this with the actual model architecture for your use case\nmodel = create_model()\n\n# Load pre-trained weights\nmodel.load_weights('/kaggle/working/flower_species_model.h5')\n\n# Save the model with architecture included\nmodel.save('/kaggle/working/flower_species_model_with_architecture.h5')","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2023-10-28T11:42:32.157488Z","iopub.status.idle":"2023-10-28T11:42:32.157819Z","shell.execute_reply.started":"2023-10-28T11:42:32.157649Z","shell.execute_reply":"2023-10-28T11:42:32.157664Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow import keras\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Average\n\n# Load the pre-trained models with custom names\nmodel_plant = keras.models.load_model('/kaggle/working/plant_species_model.h5')\nmodel_flower = keras.models.load_model('/kaggle/working/flower_species_model_with_architecture.h5')\n\ninput_shape = (224, 224, 3)\n\ntry:\n    # Rename the layers within the loaded models\n    for layer in model_plant.layers:\n        layer._name = f'plant_{layer.name}'\n\n    for layer in model_flower.layers:\n        layer._name = f'flower_{layer.name}'\n\n    # Create an ensemble model\n    input_layer = keras.layers.Input(shape=input_shape, name='input_layer')\n    output_plant = model_plant(input_layer)\n    output_flower = model_flower(input_layer)\n\n    # Average the predictions\n    averaged_output = Average(name='averaged_output')([output_plant, output_flower])\n\n    ensemble_model = Model(inputs=input_layer, outputs=averaged_output, name='ensemble_model')\nexcept: \n        print (\"An error occurred\") \n","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"execution":{"iopub.status.busy":"2023-10-28T11:42:32.15969Z","iopub.status.idle":"2023-10-28T11:42:32.160189Z","shell.execute_reply.started":"2023-10-28T11:42:32.159897Z","shell.execute_reply":"2023-10-28T11:42:32.159919Z"},"trusted":true},"execution_count":null,"outputs":[]}]}