{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":21154,"databundleVersionId":1243559,"sourceType":"competition"},{"sourceId":7350379,"sourceType":"datasetVersion","datasetId":4247656}],"dockerImageVersionId":30684,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\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":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-04-15T15:10:02.929533Z","iopub.execute_input":"2024-04-15T15:10:02.929913Z","iopub.status.idle":"2024-04-15T15:10:03.831356Z","shell.execute_reply.started":"2024-04-15T15:10:02.929882Z","shell.execute_reply":"2024-04-15T15:10:03.830305Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = np.load('/kaggle/input/flower/x_train.npy')\ny_train = np.load('/kaggle/input/flower/y_train.npy')\nprint(x_train.shape, y_train.shape)\n\nx_validation = np.load('/kaggle/input/flower/x_validation.npy')\ny_validation = np.load('/kaggle/input/flower/y_validation.npy')\nprint(x_validation.shape, y_validation.shape)","metadata":{"execution":{"iopub.status.busy":"2024-04-15T15:10:08.857536Z","iopub.execute_input":"2024-04-15T15:10:08.858056Z","iopub.status.idle":"2024-04-15T15:11:41.358276Z","shell.execute_reply.started":"2024-04-15T15:10:08.858024Z","shell.execute_reply":"2024-04-15T15:11:41.357218Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train_flattened = x_train.reshape(x_train.shape[0], -1)\nx_validation_flattened = x_validation.reshape(x_validation.shape[0], -1)\n\nprint(x_train_flattened.shape, y_train.shape)\nprint(x_validation_flattened.shape, y_validation.shape)","metadata":{"execution":{"iopub.status.busy":"2024-04-15T15:11:46.054355Z","iopub.execute_input":"2024-04-15T15:11:46.05508Z","iopub.status.idle":"2024-04-15T15:11:46.061135Z","shell.execute_reply.started":"2024-04-15T15:11:46.055032Z","shell.execute_reply":"2024-04-15T15:11:46.060078Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_croval = np.concatenate((x_train_flattened, x_validation_flattened), axis=0)\ny_croval = np.concatenate((y_train, y_validation), axis=0)\n\nprint(x_croval.shape, y_croval.shape)","metadata":{"execution":{"iopub.status.busy":"2024-04-15T15:11:49.56056Z","iopub.execute_input":"2024-04-15T15:11:49.561409Z","iopub.status.idle":"2024-04-15T15:11:52.222779Z","shell.execute_reply.started":"2024-04-15T15:11:49.561372Z","shell.execute_reply":"2024-04-15T15:11:52.221631Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(\n    rotation_range=20,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    fill_mode='nearest'\n)\n\n# Apply data augmentation to training data\ntrain_datagen.fit(x_train)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-15T15:11:54.994537Z","iopub.execute_input":"2024-04-15T15:11:54.995444Z","iopub.status.idle":"2024-04-15T15:12:04.851957Z","shell.execute_reply.started":"2024-04-15T15:11:54.995408Z","shell.execute_reply":"2024-04-15T15:12:04.850813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef display_images(dataset, n, cols):\n    \"\"\"\n    Display images from the dataset in a grid layout.\n\n    Args:\n    - dataset: NumPy array or list containing image data.\n    - n: Number of images to display.\n    - cols: Number of columns in the grid layout.\n    \"\"\"\n    rows = (n + cols - 1) // cols  # Calculate the number of rows needed\n\n    plt.figure(figsize=(cols * 3, rows * 3))  # Set the size of the figure\n\n    for i in range(n):\n        plt.subplot(rows, cols, i + 1)  # Create subplots\n        plt.imshow(dataset[i])  # Display the image\n        plt.axis('off')  # Turn off axis labels\n        plt.title(f'Image {i + 1}')  # Set the title\n\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-15T15:12:07.076159Z","iopub.execute_input":"2024-04-15T15:12:07.076885Z","iopub.status.idle":"2024-04-15T15:12:07.084781Z","shell.execute_reply.started":"2024-04-15T15:12:07.076852Z","shell.execute_reply":"2024-04-15T15:12:07.08375Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef display_augmented_images(datagen, dataset, n, cols):\n    \"\"\"\n    Display augmented images generated by an ImageDataGenerator in a grid layout.\n\n    Args:\n    - datagen: ImageDataGenerator object for data augmentation.\n    - dataset: NumPy array or list containing original image data.\n    - n: Number of augmented images to display.\n    - cols: Number of columns in the grid layout.\n    \"\"\"\n    rows = (n + cols - 1) // cols  # Calculate the number of rows needed\n\n    plt.figure(figsize=(cols * 3, rows * 3))  # Set the size of the figure\n\n    # Generate augmented images\n    augmented_data = datagen.flow(dataset, batch_size=1, shuffle=False)\n\n    for i in range(n):\n        augmented_image = augmented_data[i][0]  # Get the augmented image\n        augmented_image = (augmented_image * 255).astype('uint8')  # Scale to [0, 255] and convert to uint8\n        plt.subplot(rows, cols, i + 1)  # Create subplots\n        plt.imshow(augmented_image)  # Display the augmented image\n        plt.axis('off')  # Turn off axis labels\n        plt.title(f'Augmented Image {i + 1}')  # Set the title\n\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-15T15:12:09.791353Z","iopub.execute_input":"2024-04-15T15:12:09.792232Z","iopub.status.idle":"2024-04-15T15:12:09.799998Z","shell.execute_reply.started":"2024-04-15T15:12:09.792194Z","shell.execute_reply":"2024-04-15T15:12:09.798998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef adjust_brightness_contrast(image, brightness=0, contrast=0):\n    \"\"\"\n    Adjust the brightness and contrast of an image.\n\n    Args:\n    - image: Input image as a NumPy array.\n    - brightness: Brightness adjustment factor (-255 to 255).\n    - contrast: Contrast adjustment factor (-127 to 127).\n\n    Returns:\n    - Adjusted image as a NumPy array.\n    \"\"\"\n    # Convert image to uint8 (0-255) and apply brightness and contrast adjustments\n    adjusted_image = cv2.convertScaleAbs(image, alpha=contrast / 127.0, beta=brightness)\n    return adjusted_image\n\ndef display_augmented_images_with_adjustments(datagen, dataset, n, cols, brightness=0, contrast=0):\n    \"\"\"\n    Display augmented images with brightness and contrast adjustments.\n\n    Args:\n    - datagen: ImageDataGenerator object for data augmentation.\n    - dataset: NumPy array or list containing original image data.\n    - n: Number of augmented images to display.\n    - cols: Number of columns in the grid layout.\n    - brightness: Brightness adjustment factor (-255 to 255).\n    - contrast: Contrast adjustment factor (-127 to 127).\n    \"\"\"\n    rows = (n + cols - 1) // cols  # Calculate the number of rows needed\n\n    plt.figure(figsize=(cols * 3, rows * 3))  # Set the size of the figure\n\n    # Generate augmented images with shuffling enabled\n    augmented_data = datagen.flow(dataset, batch_size=1, shuffle=False)\n\n    for i in range(n):\n        augmented_image = augmented_data[i][0]  # Get the augmented image\n        augmented_image = (augmented_image * 255).astype('uint8')  # Scale to [0, 255] and convert to uint8\n\n        # Adjust brightness and contrast\n        augmented_image = adjust_brightness_contrast(augmented_image, brightness, contrast)\n\n        plt.subplot(rows, cols, i + 1)  # Create subplots\n        plt.imshow(augmented_image)  # Display the augmented image\n        plt.axis('off')  # Turn off axis labels\n        plt.title(f'Augmented Image {i + 1}')  # Set the title\n\n    plt.show()\n\n# Example usage:\n# Assuming 'train_datagen' is the ImageDataGenerator object for data augmentation\n# Assuming 'X_train' contains the original training image data\n# Display 10 shuffled augmented images with brightness=50 and contrast=20 in a 2x5 grid layout\n# display_augmented_images_with_adjustments(train_datagen, X_train, 10, 5, brightness=50, contrast=20)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-15T15:12:11.89695Z","iopub.execute_input":"2024-04-15T15:12:11.897391Z","iopub.status.idle":"2024-04-15T15:12:12.0602Z","shell.execute_reply.started":"2024-04-15T15:12:11.897357Z","shell.execute_reply":"2024-04-15T15:12:12.059337Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"display_images(x_train, 10, 5)","metadata":{"execution":{"iopub.status.busy":"2024-04-15T15:12:14.979236Z","iopub.execute_input":"2024-04-15T15:12:14.981322Z","iopub.status.idle":"2024-04-15T15:12:16.107261Z","shell.execute_reply.started":"2024-04-15T15:12:14.98108Z","shell.execute_reply":"2024-04-15T15:12:16.106071Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"display_augmented_images(train_datagen, x_train, 10, 5)","metadata":{"execution":{"iopub.status.busy":"2024-04-15T15:12:19.503359Z","iopub.execute_input":"2024-04-15T15:12:19.504388Z","iopub.status.idle":"2024-04-15T15:12:20.863081Z","shell.execute_reply.started":"2024-04-15T15:12:19.504343Z","shell.execute_reply":"2024-04-15T15:12:20.861994Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"display_augmented_images_with_adjustments(train_datagen, x_train, 10, 5, brightness=70, contrast=50)","metadata":{"execution":{"iopub.status.busy":"2024-04-15T14:39:29.327242Z","iopub.execute_input":"2024-04-15T14:39:29.328322Z","iopub.status.idle":"2024-04-15T14:39:30.430887Z","shell.execute_reply.started":"2024-04-15T14:39:29.328289Z","shell.execute_reply":"2024-04-15T14:39:30.429925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import layers, models\n\ndef residual_block(x, filters, strides=1):\n    \"\"\"\n    Define a residual block for ResNet.\n\n    Args:\n    - x: Input tensor.\n    - filters: Number of filters in the convolutional layers.\n    - strides: Stride size for the first convolutional layer (default=1).\n\n    Returns:\n    - Output tensor.\n    \"\"\"\n    shortcut = x  # Save the input tensor for the shortcut connection\n\n    # First convolutional layer\n    x = layers.Conv2D(filters, kernel_size=3, strides=strides, padding='same')(x)\n    x = layers.BatchNormalization()(x)\n    x = layers.ReLU()(x)\n\n    # Second convolutional layer\n    x = layers.Conv2D(filters, kernel_size=3, strides=1, padding='same')(x)\n    x = layers.BatchNormalization()(x)\n\n    # Shortcut connection\n    if strides != 1 or shortcut.shape[-1] != filters:\n        shortcut = layers.Conv2D(filters, kernel_size=1, strides=strides, padding='same')(shortcut)\n        shortcut = layers.BatchNormalization()(shortcut)\n\n    x = layers.add([x, shortcut])  # Add the shortcut connection\n    x = layers.ReLU()(x)\n\n    return x\n\ndef ResNet(input_shape=(224, 224, 3), num_classes=1000):\n    \"\"\"\n    Define the ResNet model.\n\n    Args:\n    - input_shape: Input shape of the images (default=(224, 224, 3)).\n    - num_classes: Number of output classes (default=1000).\n\n    Returns:\n    - ResNet model.\n    \"\"\"\n    inputs = layers.Input(shape=input_shape)\n\n    # Initial convolutional layer\n    x = layers.Conv2D(64, kernel_size=7, strides=2, padding='same')(inputs)\n    x = layers.BatchNormalization()(x)\n    x = layers.ReLU()(x)\n    x = layers.MaxPooling2D(pool_size=3, strides=2, padding='same')(x)\n\n    # Residual blocks\n    x = residual_block(x, filters=64, strides=1)\n    x = residual_block(x, filters=64, strides=1)\n    x = residual_block(x, filters=128, strides=2)\n    x = residual_block(x, filters=128, strides=1)\n    x = residual_block(x, filters=256, strides=2)\n    x = residual_block(x, filters=256, strides=1)\n    x = residual_block(x, filters=512, strides=2)\n    x = residual_block(x, filters=512, strides=1)\n\n    # Global average pooling layer\n    x = layers.GlobalAveragePooling2D()(x)\n\n    # Output layer\n    outputs = layers.Dense(num_classes, activation='softmax')(x)\n\n    # Create model\n    model = models.Model(inputs, outputs)\n    return model\n\n# Example usage:\n# Create a ResNet model with input shape (224, 224, 3) and 1000 output classes\nresnet_model = ResNet(input_shape=(192, 192, 3), num_classes=1000)\n# resnet_model.summary()\n","metadata":{"execution":{"iopub.status.busy":"2024-04-15T14:50:59.709348Z","iopub.execute_input":"2024-04-15T14:50:59.710098Z","iopub.status.idle":"2024-04-15T14:51:00.088853Z","shell.execute_reply.started":"2024-04-15T14:50:59.710059Z","shell.execute_reply":"2024-04-15T14:51:00.087991Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping\nresnet_model.compile(optimizer='adam',\n                     loss='sparse_categorical_crossentropy',\n                     metrics=['accuracy'])\nearly_stopping = EarlyStopping(monitor='val_loss', patience=3)\n# history = resnet_model.fit(x_train, y_train, validation_split=0.2, epochs=100, batch_size=128, verbose=2, callbacks=[early_stopping])\nhistory = resnet_model.fit(x_train, y_train, validation_split=0.2, epochs=30, batch_size=128, verbose=2)","metadata":{"execution":{"iopub.status.busy":"2024-04-15T14:51:16.075562Z","iopub.execute_input":"2024-04-15T14:51:16.076504Z","iopub.status.idle":"2024-04-15T15:04:28.279813Z","shell.execute_reply.started":"2024-04-15T14:51:16.07647Z","shell.execute_reply":"2024-04-15T15:04:28.278771Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_loss, test_acc = resnet_model.evaluate(x_train, y_train, verbose=2)\nprint('Test accuracy:', test_acc)","metadata":{"execution":{"iopub.status.busy":"2024-04-15T15:04:32.695472Z","iopub.execute_input":"2024-04-15T15:04:32.696217Z","iopub.status.idle":"2024-04-15T15:04:58.823155Z","shell.execute_reply.started":"2024-04-15T15:04:32.696178Z","shell.execute_reply":"2024-04-15T15:04:58.822012Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import layers, models\n\ndef VGG(input_shape=(224, 224, 3), num_classes=1000):\n    \"\"\"\n    Define the VGG model.\n\n    Args:\n    - input_shape: Input shape of the images (default=(224, 224, 3)).\n    - num_classes: Number of output classes (default=1000).\n\n    Returns:\n    - VGG model.\n    \"\"\"\n    inputs = layers.Input(shape=input_shape)\n\n    # Block 1\n    x = layers.Conv2D(64, kernel_size=3, padding='same', activation='relu')(inputs)\n    x = layers.Conv2D(64, kernel_size=3, padding='same', activation='relu')(x)\n    x = layers.MaxPooling2D(pool_size=2, strides=2)(x)\n\n    # Block 2\n    x = layers.Conv2D(128, kernel_size=3, padding='same', activation='relu')(x)\n    x = layers.Conv2D(128, kernel_size=3, padding='same', activation='relu')(x)\n    x = layers.MaxPooling2D(pool_size=2, strides=2)(x)\n\n    # Block 3\n    x = layers.Conv2D(256, kernel_size=3, padding='same', activation='relu')(x)\n    x = layers.Conv2D(256, kernel_size=3, padding='same', activation='relu')(x)\n    x = layers.Conv2D(256, kernel_size=3, padding='same', activation='relu')(x)\n    x = layers.MaxPooling2D(pool_size=2, strides=2)(x)\n\n    # Block 4\n    x = layers.Conv2D(512, kernel_size=3, padding='same', activation='relu')(x)\n    x = layers.Conv2D(512, kernel_size=3, padding='same', activation='relu')(x)\n    x = layers.Conv2D(512, kernel_size=3, padding='same', activation='relu')(x)\n    x = layers.MaxPooling2D(pool_size=2, strides=2)(x)\n\n    # Block 5\n    x = layers.Conv2D(512, kernel_size=3, padding='same', activation='relu')(x)\n    x = layers.Conv2D(512, kernel_size=3, padding='same', activation='relu')(x)\n    x = layers.Conv2D(512, kernel_size=3, padding='same', activation='relu')(x)\n    x = layers.MaxPooling2D(pool_size=2, strides=2)(x)\n\n    # Flatten and fully connected layers\n    x = layers.Flatten()(x)\n    x = layers.Dense(4096, activation='relu')(x)\n    x = layers.Dense(4096, activation='relu')(x)\n\n    # Output layer\n    outputs = layers.Dense(num_classes, activation='softmax')(x)\n\n    # Create model\n    model = models.Model(inputs, outputs)\n    return model\n\n# Example usage:\n# Create a VGG model with input shape (224, 224, 3) and 1000 output classes\nvgg_model = VGG(input_shape=(224, 224, 3), num_classes=1000)\nvgg_model.summary()\n","metadata":{"execution":{"iopub.status.busy":"2024-04-15T15:05:26.55646Z","iopub.execute_input":"2024-04-15T15:05:26.556914Z","iopub.status.idle":"2024-04-15T15:05:26.733302Z","shell.execute_reply.started":"2024-04-15T15:05:26.556868Z","shell.execute_reply":"2024-04-15T15:05:26.732412Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping\nvgg_model.compile(optimizer='adam',\n                  loss='sparse_categorical_crossentropy',\n                  metrics=['accuracy'])\nearly_stopping = EarlyStopping(monitor='val_loss', patience=3)\n# history = resnet_model.fit(x_train, y_train, validation_split=0.2, epochs=100, batch_size=128, verbose=2, callbacks=[early_stopping])\n# Assuming X_train and y_train are your training images and labels\n# Assuming X_val and y_val are your validation images and labels\n\nhistory = vgg_model.fit(x_train, y_train,\n                         validation_data=(x_validation, y_validation),\n                         epochs=30,\n                         batch_size=128)","metadata":{"execution":{"iopub.status.busy":"2024-04-15T15:08:30.253553Z","iopub.execute_input":"2024-04-15T15:08:30.254009Z","iopub.status.idle":"2024-04-15T15:08:30.301548Z","shell.execute_reply.started":"2024-04-15T15:08:30.253968Z","shell.execute_reply":"2024-04-15T15:08:30.300103Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"進行 inference","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nimport tensorflow_datasets as tfds\n\n# Step 4: Load and Prepare the Dataset\ndataset, info = tfds.load('oxford_flowers102', with_info=True, as_supervised=True)\ntrain_dataset, test_dataset = dataset['train'], dataset['test']\n\ndef preprocess_img(image, label):\n    image = tf.image.resize(image, (224, 224))\n    image = tf.cast(image, tf.float32) / 255.0  # Normalize pixel values\n    return image, label\n\ntrain_dataset = train_dataset.map(preprocess_img).shuffle(1000).batch(32)\ntest_dataset = test_dataset.map(preprocess_img).batch(32)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-15T11:09:26.375477Z","iopub.execute_input":"2024-04-15T11:09:26.375872Z","iopub.status.idle":"2024-04-15T11:10:04.776021Z","shell.execute_reply.started":"2024-04-15T11:09:26.375839Z","shell.execute_reply":"2024-04-15T11:10:04.774996Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Build ResNet Model","metadata":{}},{"cell_type":"code","source":"base_model = tf.keras.applications.ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3))\nbase_model.trainable = False\n\nmodel = tf.keras.Sequential([\n    base_model,\n    tf.keras.layers.GlobalAveragePooling2D(),\n    tf.keras.layers.Dense(102, activation='softmax')  # Number of classes in the dataset\n])","metadata":{"execution":{"iopub.status.busy":"2024-04-15T11:10:04.777225Z","iopub.execute_input":"2024-04-15T11:10:04.777476Z","iopub.status.idle":"2024-04-15T11:10:07.094167Z","shell.execute_reply.started":"2024-04-15T11:10:04.777454Z","shell.execute_reply":"2024-04-15T11:10:07.093204Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE\n\n# Detect TPU, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver() \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() \n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)\n\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\n\nIMAGE_SIZE = [192, 192]                   \nEPOCHS = 20\nBATCH_SIZE = 24 * strategy.num_replicas_in_sync\n\nSEED = 919\n\nGCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-192x192'\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\n\nnp.set_printoptions(threshold=15, linewidth=80)","metadata":{"execution":{"iopub.status.busy":"2024-04-15T11:21:49.033531Z","iopub.execute_input":"2024-04-15T11:21:49.033923Z","iopub.status.idle":"2024-04-15T11:21:49.553034Z","shell.execute_reply.started":"2024-04-15T11:21:49.033896Z","shell.execute_reply":"2024-04-15T11:21:49.552197Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = np.array(train_dataset)\ny = np.array(test_dataset[\"category\"])\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)\n\n# Define the ResNet model\nbase_model = ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3))\n\n# Freeze the pre-trained layers\nfor layer in base_model.layers:\n    layer.trainable = False\n\nmodel = models.Sequential([\n    base_model,\n    layers.GlobalAveragePooling2D(),\n    layers.Dense(102, activation='softmax')  # Number of classes in the dataset\n])\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n\n# Train the model\nhistory = model.fit(X_train, y_train, epochs=10, batch_size=32, validation_data=(X_val, y_val))\n\n# Plot training history\nplt.plot(history.history['accuracy'], label='accuracy')\nplt.plot(history.history['val_accuracy'], label = 'val_accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.ylim([0, 1])\nplt.legend(loc='lower right')\nplt.show()\n\n# Evaluate the model\ntest_images = []\nfor img_name in test_df[\"image_id\"]:\n    img = tf.keras.preprocessing.image.load_img(\"../input/ptm-dataset/test/test/\"+img_name, target_size=(224,224))\n    img = tf.keras.preprocessing.image.img_to_array(img)\n    img = img / 255.0  # Normalize pixel values\n    test_images.append(img)\n\nX_test = np.array(test_images)\ny_test = np.array(test_df[\"category\"])\n\ntest_loss, test_acc = model.evaluate(X_test, y_test, verbose=2)\nprint('Test accuracy:', test_acc)","metadata":{"execution":{"iopub.status.busy":"2024-04-15T11:30:40.651947Z","iopub.execute_input":"2024-04-15T11:30:40.65231Z","iopub.status.idle":"2024-04-15T11:30:40.709145Z","shell.execute_reply.started":"2024-04-15T11:30:40.652283Z","shell.execute_reply":"2024-04-15T11:30:40.708039Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}