{"metadata":{"colab":{"provenance":[],"gpuType":"T4"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"},"accelerator":"GPU","kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":2822650,"sourceType":"datasetVersion","datasetId":1715304},{"sourceId":8175911,"sourceType":"datasetVersion","datasetId":4839616}],"dockerImageVersionId":30699,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"Execte the following line of code after uploading Kaggle.json file from the drive :\n\nhttps://drive.google.com/drive/folders/1pgbi-StVe1cWI-2JPGLCJ5Rktlbpxi3Y?usp=drive_link","metadata":{"id":"fr7rggUbLLRg"}},{"cell_type":"code","source":"import numpy as np\nimport tensorflow as tf\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os","metadata":{"id":"rUg-PW-MYCAm","executionInfo":{"status":"ok","timestamp":1713373889881,"user_tz":-330,"elapsed":966,"user":{"displayName":"Arjun G S","userId":"05373839033675248152"}}},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\nimport os\n\nimages = []\n\ndef resize_images(image_folder, output_folder, width, height):\n  \"\"\"\n  Resizes all images in a folder and saves them to an output folder.\n\n  Args:\n      image_folder (str): Path to the folder containing the images to resize.\n      output_folder (str): Path to the folder where the resized images will be saved.\n      width (int): Target width for the resized images.\n      height (int): Target height for the resized images.\n  \"\"\"\n\n  # Create the output folder if it doesn't exist\n  os.makedirs(output_folder, exist_ok=True)\n\n  for filename in os.listdir(image_folder):\n    # Get the full path of the image\n    image_path = os.path.join(image_folder, filename)\n\n    # Check if it's a valid image file\n    if os.path.isfile(image_path) and filename.lower().endswith(('.jpg', '.jpeg', '.png')):\n      # Read the image\n      image = cv2.imread(image_path)\n\n\n      # Resize the image\n      resized_image = cv2.resize(image, (width, height))\n      images.append(resized_image)\n\n      # Generate a new filename with \"resized_\" prefix (optional)\n      new_filename = f\"{filename}\"\n\n      # Save the resized image\n      cv2.imwrite(os.path.join(output_folder, new_filename), resized_image)\n\n      print(f\"Resized '{filename}' to {output_folder}/{new_filename}\")\n\n# Example usage (replace with your folder paths and desired dimensions)\nimage_folder = \"/kaggle/input/aptos2019/train_images/train_images\"\noutput_folder = \"/kaggle/working/resized_images\"\nwidth = 456\nheight = 456\n\nresize_images(image_folder, output_folder, width, height)\n","metadata":{"id":"3RaKScFVZ8Cx","executionInfo":{"status":"ok","timestamp":1713209533739,"user_tz":-330,"elapsed":460522,"user":{"displayName":"Matrix Shore","userId":"13823706920025811759"}},"outputId":"7b7273ac-7294-4bf5-8c49-6dd3c0639938"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Load the train labels\ntrain_labels = pd.read_csv('./train.csv')\ntrain_labels['diagnosis'] = train_labels['diagnosis'].astype(str)\nprint(train_labels['diagnosis'])\n\n# Define the data generator\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,\n    validation_split=0.2,\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    vertical_flip=True\n)\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\n# Load the train data\ntrain_generator = train_datagen.flow_from_dataframe(\n    dataframe=train_labels,\n    directory='/content/resized_images',\n    x_col='id_code',\n    y_col='diagnosis',\n    batch_size=16,\n    class_mode='categorical',\n    subset='training',\n    shuffle=True,  # Shuffle the data\n    validate_filenames=True  # Validate filenames to avoid the warning\n)","metadata":{"id":"hNvsITNNwTI8","executionInfo":{"status":"ok","timestamp":1713209590377,"user_tz":-330,"elapsed":553,"user":{"displayName":"Matrix Shore","userId":"13823706920025811759"}},"outputId":"8b2e7719-a891-4fdd-e5fb-70169cfcc345"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras import layers\nfrom tensorflow.keras.applications import EfficientNetB5\n\n\nNUM_CLASSES = 5\nIMG_SIZE = 456\nsize = (IMG_SIZE, IMG_SIZE)\n\n\ninputs = layers.Input(shape=(IMG_SIZE, IMG_SIZE, 3))\n\n\n# Using model without transfer learning\n\noutputs = EfficientNetB5(include_top=True, weights=None, classes=NUM_CLASSES)(inputs)","metadata":{"id":"oBC45sgdtnXY"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = tf.keras.Model(inputs, outputs)\n\nmodel.compile(optimizer=\"adam\", loss=\"categorical_crossentropy\", metrics=[\"accuracy\"] )\n\nmodel.summary()\n","metadata":{"id":"qgiNhHXdt44V","executionInfo":{"status":"ok","timestamp":1713209605799,"user_tz":-330,"elapsed":8,"user":{"displayName":"Matrix Shore","userId":"13823706920025811759"}},"outputId":"1caa3cc2-7c60-4c45-8641-1a85e65503a3"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"hist = model.fit(train_generator, epochs=25, verbose=2)","metadata":{"id":"U40br8PwuPUM","outputId":"78ed551b-8ece-4139-a884-2f0a3ce21e57","executionInfo":{"status":"ok","timestamp":1713212765856,"user_tz":-330,"elapsed":3132618,"user":{"displayName":"Matrix Shore","userId":"13823706920025811759"}}},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n\ndef plot_hist(hist):\n    plt.plot(hist.history[\"accuracy\"])\n    #plt.plot(hist.history[\"val_accuracy\"])\n    plt.title(\"model accuracy\")\n    plt.ylabel(\"accuracy\")\n    plt.xlabel(\"epoch\")\n    plt.legend([\"train\", \"validation\"], loc=\"upper left\")\n    plt.show()\n\n\nplot_hist(hist)","metadata":{"id":"e1NhStTb0eFk","executionInfo":{"status":"ok","timestamp":1713212817907,"user_tz":-330,"elapsed":829,"user":{"displayName":"Matrix Shore","userId":"13823706920025811759"}},"outputId":"97371bd7-0a3e-4455-aa34-e9f33ec8ca63"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plot the training and validation loss curves\nplt.plot(hist.history['loss'])\n#plt.plot(hist.history['val_loss'])\nplt.title('Model Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()","metadata":{"id":"PWWQdzcp6kwN","executionInfo":{"status":"ok","timestamp":1713212839653,"user_tz":-330,"elapsed":902,"user":{"displayName":"Matrix Shore","userId":"13823706920025811759"}},"outputId":"7eb55452-d3f1-47b7-8895-2b9d362ded6f"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\nimport os\n\nimages = []\n\ndef resize_images(image_folder, output_folder, width, height):\n  \"\"\"\n  Resizes all images in a folder and saves them to an output folder.\n\n  Args:\n      image_folder (str): Path to the folder containing the images to resize.\n      output_folder (str): Path to the folder where the resized images will be saved.\n      width (int): Target width for the resized images.\n      height (int): Target height for the resized images.\n  \"\"\"\n\n  # Create the output folder if it doesn't exist\n  os.makedirs(output_folder, exist_ok=True)\n\n  for filename in os.listdir(image_folder):\n    # Get the full path of the image\n    image_path = os.path.join(image_folder, filename)\n\n    # Check if it's a valid image file\n    if os.path.isfile(image_path) and filename.lower().endswith(('.jpg', '.jpeg', '.png')):\n      # Read the image\n      image = cv2.imread(image_path)\n\n\n      # Resize the image\n      resized_image = cv2.resize(image, (width, height))\n      images.append(resized_image)\n\n      # Generate a new filename with \"resized_\" prefix (optional)\n      new_filename = f\"{filename}\"\n\n      # Save the resized image\n      cv2.imwrite(os.path.join(output_folder, new_filename), resized_image)\n\n      print(f\"Resized '{filename}' to {output_folder}/{new_filename}\")\n\n# Example usage (replace with your folder paths and desired dimensions)\nimage_folder = \"./test_images\"\noutput_folder = \"./resized_test_images\"\nwidth = 456\nheight = 456\n\nresize_images(image_folder, output_folder, width, height)\n","metadata":{"id":"8FJp_tjWMI6W","executionInfo":{"status":"ok","timestamp":1713212943841,"user_tz":-330,"elapsed":98123,"user":{"displayName":"Matrix Shore","userId":"13823706920025811759"}},"outputId":"218977bb-0538-4001-a52c-a9ed3ad99c96"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the train labels\ninput_shape = (456, 456, 3)\ntest_labels = pd.read_csv('/content/test.csv')\n\ntest_generator = test_datagen.flow_from_dataframe(\n    dataframe=test_labels,\n    directory='/content/resized_test_images',\n    x_col='id_code',\n    target_size=input_shape[:2],\n    batch_size=32,\n    class_mode=None,  # Set to None for test data (no labels)\n    shuffle=False  # Do not shuffle test data\n)","metadata":{"id":"bnocEyq91CEQ","executionInfo":{"status":"ok","timestamp":1713214751910,"user_tz":-330,"elapsed":4,"user":{"displayName":"Matrix Shore","userId":"13823706920025811759"}},"outputId":"ad050e83-51ce-4b1d-9543-e34b018dc0e4"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds = model.evaluate(test_generator)\nprint(preds)\nprint (\"Loss = \" + str(preds[0]))\nprint (\"Test Accuracy = \" + str(preds[1]))","metadata":{"id":"g08oOYZa1vcF","executionInfo":{"status":"ok","timestamp":1713214798806,"user_tz":-330,"elapsed":41789,"user":{"displayName":"Matrix Shore","userId":"13823706920025811759"}},"outputId":"844f8cd9-0543-4024-f0fc-86ff3c2136d7"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from matplotlib.pyplot import imread\nfrom matplotlib.pyplot import imshow\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications.imagenet_utils import decode_predictions\nfrom tensorflow.keras.applications.imagenet_utils import preprocess_input\n\n\nimg_path = '/content/train_images/2463bb04ebc3.png'\n\n#img = image.load_img(img_path, target_size=(224, 224))\n#x = img.img_to_array(img)\n\nimg = cv2.imread(img_path)\nimg = cv2.resize(img, (456, 456))\n\nx = np.expand_dims(img, axis=0)\nx = preprocess_input(x)\n\nprint('Input image shape:', x.shape)\n\nmy_image = imread(img_path)\nimshow(my_image)","metadata":{"id":"18R224-ikAwU","executionInfo":{"status":"ok","timestamp":1713215232222,"user_tz":-330,"elapsed":4833,"user":{"displayName":"Matrix Shore","userId":"13823706920025811759"}},"outputId":"da56855c-233a-4432-f252-a16a0b918676"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds=model.predict(x)\npreds","metadata":{"id":"fdPP16yJk2G6","executionInfo":{"status":"ok","timestamp":1713215236686,"user_tz":-330,"elapsed":819,"user":{"displayName":"Matrix Shore","userId":"13823706920025811759"}},"outputId":"4695a340-58e5-4cab-8984-0efc82eacebc"},"execution_count":null,"outputs":[]}]}