{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":84209,"databundleVersionId":9414711,"sourceType":"competition"},{"sourceId":199803,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":170437,"modelId":192749}],"dockerImageVersionId":30804,"isInternetEnabled":false,"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","trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:05:50.068661Z","iopub.execute_input":"2024-12-16T05:05:50.069393Z","iopub.status.idle":"2024-12-16T05:05:57.586241Z","shell.execute_reply.started":"2024-12-16T05:05:50.069359Z","shell.execute_reply":"2024-12-16T05:05:57.585422Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Create an ImageDataGenerator instance\ndatagen = ImageDataGenerator(rescale=1.0/255,  # Normalize pixel values\n                             rotation_range=20,  # Random rotation\n                             width_shift_range=0.2,  # Random horizontal shift\n                             height_shift_range=0.2,  # Random vertical shift\n                             shear_range=0.2,  # Shear\n                             zoom_range=0.2,  # Zoom\n                             horizontal_flip=True,  # Random horizontal flip\n                             fill_mode=\"nearest\")  # Fill the empty pixels\n\n\n# Load training data\ntrain_data = datagen.flow_from_directory(\n    '/kaggle/input/computer-vision-xm/images',\n    target_size=(128, 128),  # Resize images\n    batch_size=32,\n    class_mode='categorical',  # For multi-class classification\n    subset='training'  # Use this for training\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:05:57.587629Z","iopub.execute_input":"2024-12-16T05:05:57.587924Z","iopub.status.idle":"2024-12-16T05:05:58.723387Z","shell.execute_reply.started":"2024-12-16T05:05:57.587898Z","shell.execute_reply":"2024-12-16T05:05:58.722679Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"file=os.listdir('/kaggle/input/computer-vision-xm/images/kaggle/working/Reorganized_Data/')\nprint(file)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:05:58.724523Z","iopub.execute_input":"2024-12-16T05:05:58.724944Z","iopub.status.idle":"2024-12-16T05:05:58.737498Z","shell.execute_reply.started":"2024-12-16T05:05:58.724906Z","shell.execute_reply":"2024-12-16T05:05:58.736728Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport os\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\n\n# Load CSV\ndf = pd.read_csv('/kaggle/input/computer-vision-xm/train.csv', index_col=0)\n\n# Extract image paths and labels\nimage_dir = '/kaggle/input/computer-vision-xm/images/'\n#df['image_path'] = df['Images'].apply(lambda x: os.path.join(image_dir, x))\n\n# Train-test split\n#train_df, val_df = train_test_split(df, test_size=0.2, random_state=42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:05:58.739012Z","iopub.execute_input":"2024-12-16T05:05:58.739271Z","iopub.status.idle":"2024-12-16T05:05:59.162464Z","shell.execute_reply.started":"2024-12-16T05:05:58.739246Z","shell.execute_reply":"2024-12-16T05:05:59.161454Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#train_df.head()\ntrain_df='/kaggle/input/computer-vision-xm/train.csv'\ntest_df='/kaggle/input/computer-vision-xm/test.csv'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:05:59.163851Z","iopub.execute_input":"2024-12-16T05:05:59.164502Z","iopub.status.idle":"2024-12-16T05:05:59.168604Z","shell.execute_reply.started":"2024-12-16T05:05:59.164452Z","shell.execute_reply":"2024-12-16T05:05:59.167687Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#train_df.head(1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:05:59.169543Z","iopub.execute_input":"2024-12-16T05:05:59.169800Z","iopub.status.idle":"2024-12-16T05:05:59.177660Z","shell.execute_reply.started":"2024-12-16T05:05:59.169761Z","shell.execute_reply":"2024-12-16T05:05:59.176770Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Get a batch of data\nimages, labels = next(train_data)  # Get the first batch from the generator\n\n# Number of images in the batch\nbatch_size = len(images)\nprint(batch_size)\n# Determine grid size based on batch size, you can adjust this\nrows = 4\ncols = 8\n\n# Create a new figure\nplt.figure(figsize=(15, 10))\n\n# Loop over the images in the batch and display them using plt.imshow\nfor i in range(batch_size):\n    plt.subplot(rows, cols, i + 1)  # Specify position in the grid\n    plt.imshow(images[i])  # Display the image\n    plt.axis('off')  # Turn off axes for each image\n\n# Adjust layout to avoid overlap\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:05:59.178801Z","iopub.execute_input":"2024-12-16T05:05:59.179056Z","iopub.status.idle":"2024-12-16T05:06:06.609953Z","shell.execute_reply.started":"2024-12-16T05:05:59.179030Z","shell.execute_reply":"2024-12-16T05:06:06.608695Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"destination_path='/kaggle/input/computer-vision-xm/images/kaggle/working/Reorganized_Data/images'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:06:06.611275Z","iopub.execute_input":"2024-12-16T05:06:06.611563Z","iopub.status.idle":"2024-12-16T05:06:06.615996Z","shell.execute_reply.started":"2024-12-16T05:06:06.611537Z","shell.execute_reply":"2024-12-16T05:06:06.615106Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dir='/kaggle/input'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:06:06.616994Z","iopub.execute_input":"2024-12-16T05:06:06.617261Z","iopub.status.idle":"2024-12-16T05:06:06.632160Z","shell.execute_reply.started":"2024-12-16T05:06:06.617236Z","shell.execute_reply":"2024-12-16T05:06:06.631179Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\n\n# Check if GPU is available\nif tf.config.list_physical_devices('GPU'):\n    print(\"GPU is available!\")\nelse:\n    print(\"No GPU detected.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:06:06.635095Z","iopub.execute_input":"2024-12-16T05:06:06.635436Z","iopub.status.idle":"2024-12-16T05:06:06.951345Z","shell.execute_reply.started":"2024-12-16T05:06:06.635405Z","shell.execute_reply":"2024-12-16T05:06:06.950175Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport cv2\nimport numpy as np\nimport pandas as pd\n\ndef load_images_and_labels(train_df,destination_path, target_size=(128, 128)):\n    \"\"\"\n    Load images and labels based on a CSV file.\n    Args:\n        csv_path (str): Path to the CSV file containing Image_ID and Labels.\n        image_dir (str): Path to the directory containing images.\n        target_size (tuple): Size to which images should be resized (default: (128, 128)).\n    Returns:\n        images (np.array): Array of preprocessed images.\n        labels (np.array): Array of labels corresponding to the images.\n    \"\"\"\n    # Load the CSV file\n    #df = pd.read_csv(train_df)\n    \n    # Initialize lists to store images and labels\n    images = []\n    labels = []\n    \n    # Loop through each row in the CSV\n    for idx, row in df.iterrows():\n        img_path = os.path.join(destination_path, row['Images'])  # Construct the image path\n        img = cv2.imread(img_path)  # Read the image\n        \n        if img is not None:\n            # Resize the image\n            img = cv2.resize(img, target_size)\n            # Normalize the pixel values\n            img = img / 255.0\n            # Append the image and its corresponding label\n            images.append(img)\n            labels.append(row['Labels'])\n        else:\n            print(f\"Failed to load image: {img_path}\")\n    \n    # Convert lists to numpy arrays\n    images = np.array(images)\n    labels = np.array(labels)\n    \n    return images, labels\n\n# Paths to the CSV file and image directory\ncsv_path = '/kaggle/input/dataset/train.csv'  # Update with your actual CSV path\nimage_dir = '/kaggle/input/dataset/images/'  # Update with your actual image folder path\n\n# Load training images and labels\ntrain_images, train_labels = load_images_and_labels(train_df, destination_path)\n\n# Print shapes to confirm successful loading\nprint(f\"Train images shape: {train_images.shape}\")\nprint(f\"Train labels shape: {train_labels.shape}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:06:06.952973Z","iopub.execute_input":"2024-12-16T05:06:06.953416Z","iopub.status.idle":"2024-12-16T05:15:28.182098Z","shell.execute_reply.started":"2024-12-16T05:06:06.953372Z","shell.execute_reply":"2024-12-16T05:15:28.181164Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_images","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:15:28.183422Z","iopub.execute_input":"2024-12-16T05:15:28.183808Z","iopub.status.idle":"2024-12-16T05:15:28.195553Z","shell.execute_reply.started":"2024-12-16T05:15:28.183768Z","shell.execute_reply":"2024-12-16T05:15:28.194614Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(f\"train_images shape: {len(train_images)}\")\nprint(f\"train_labels shape: {len(train_labels)}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:15:28.196698Z","iopub.execute_input":"2024-12-16T05:15:28.196959Z","iopub.status.idle":"2024-12-16T05:15:28.205535Z","shell.execute_reply.started":"2024-12-16T05:15:28.196932Z","shell.execute_reply":"2024-12-16T05:15:28.204865Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:15:28.206525Z","iopub.execute_input":"2024-12-16T05:15:28.206806Z","iopub.status.idle":"2024-12-16T05:15:28.216200Z","shell.execute_reply.started":"2024-12-16T05:15:28.206782Z","shell.execute_reply":"2024-12-16T05:15:28.215510Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"trainX, valX, trainY, valY = train_test_split(train_images, train_labels, test_size=0.2, random_state=42)\n\nprint(f\"Train set: {trainX.shape}, {trainY.shape}\")\nprint(f\"Validation set: {valX.shape}, {valY.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:15:28.217385Z","iopub.execute_input":"2024-12-16T05:15:28.217623Z","iopub.status.idle":"2024-12-16T05:15:28.602308Z","shell.execute_reply.started":"2024-12-16T05:15:28.217585Z","shell.execute_reply":"2024-12-16T05:15:28.601420Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom tensorflow.keras.optimizers import Adam\n\n# Create the CNN model\nmodel = Sequential()\n\n# Add first convolutional layer\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(128, 128, 3)))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\n# Add second convolutional layer\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\n# Flatten the output for the fully connected layers\nmodel.add(Flatten())\n\n# Add dense layer\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))  # Dropout to prevent overfitting\n\n# Output layer (assuming binary classification, change units for multi-class)\nmodel.add(Dense(1, activation='sigmoid'))  # Use softmax if multi-class\n\n# Compile the model\nmodel.compile(optimizer=Adam(), loss='binary_crossentropy', metrics=['accuracy'])\n\n# Summary of the model\nmodel.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:15:28.603443Z","iopub.execute_input":"2024-12-16T05:15:28.603721Z","iopub.status.idle":"2024-12-16T05:15:29.323683Z","shell.execute_reply.started":"2024-12-16T05:15:28.603695Z","shell.execute_reply":"2024-12-16T05:15:29.322782Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nprint(\"Is CUDA available?\", torch.cuda.is_available())\nprint(\"Number of GPUs available:\", torch.cuda.device_count())\nprint(\"CUDA device name:\", torch.cuda.get_device_name(0) if torch.cuda.is_available() else \"No GPU available\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:15:29.324846Z","iopub.execute_input":"2024-12-16T05:15:29.325156Z","iopub.status.idle":"2024-12-16T05:15:32.006436Z","shell.execute_reply.started":"2024-12-16T05:15:29.325100Z","shell.execute_reply":"2024-12-16T05:15:32.005447Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#test_df='/kaggle/input/computer-vision-xm/test.csv'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:15:32.007399Z","iopub.execute_input":"2024-12-16T05:15:32.007675Z","iopub.status.idle":"2024-12-16T05:15:32.011511Z","shell.execute_reply.started":"2024-12-16T05:15:32.007649Z","shell.execute_reply":"2024-12-16T05:15:32.010655Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:15:32.012512Z","iopub.execute_input":"2024-12-16T05:15:32.012848Z","iopub.status.idle":"2024-12-16T05:15:32.025229Z","shell.execute_reply.started":"2024-12-16T05:15:32.012821Z","shell.execute_reply":"2024-12-16T05:15:32.024199Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit(\n    trainX, trainY,  # Training data and labels\n    epochs=10,  # Number of epochs\n    batch_size=32,  # Batch size\n    validation_data=(valX, valY),  # Validation data\n    verbose=1  # Display progress\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:15:32.026133Z","iopub.execute_input":"2024-12-16T05:15:32.026354Z","iopub.status.idle":"2024-12-16T05:15:55.435976Z","shell.execute_reply.started":"2024-12-16T05:15:32.026332Z","shell.execute_reply":"2024-12-16T05:15:55.435180Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# After training the model, save it to a file\n#model1=model.save('K1_model.h5')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:15:55.437230Z","iopub.execute_input":"2024-12-16T05:15:55.437486Z","iopub.status.idle":"2024-12-16T05:15:55.441140Z","shell.execute_reply.started":"2024-12-16T05:15:55.437462Z","shell.execute_reply":"2024-12-16T05:15:55.440303Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(destination_path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:15:55.442204Z","iopub.execute_input":"2024-12-16T05:15:55.442462Z","iopub.status.idle":"2024-12-16T05:15:55.451574Z","shell.execute_reply.started":"2024-12-16T05:15:55.442436Z","shell.execute_reply":"2024-12-16T05:15:55.450861Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_df=pd.read_csv('/kaggle/input/computer-vision-xm/test.csv',index_col=0)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:15:55.452618Z","iopub.execute_input":"2024-12-16T05:15:55.452869Z","iopub.status.idle":"2024-12-16T05:15:55.470911Z","shell.execute_reply.started":"2024-12-16T05:15:55.452844Z","shell.execute_reply":"2024-12-16T05:15:55.469959Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:15:55.471967Z","iopub.execute_input":"2024-12-16T05:15:55.472296Z","iopub.status.idle":"2024-12-16T05:15:55.484746Z","shell.execute_reply.started":"2024-12-16T05:15:55.472269Z","shell.execute_reply":"2024-12-16T05:15:55.483771Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Map TEST Images\nimport os\nimport cv2\nimport numpy as np\nimport pandas as pd\n\ndef load_test_images_and_labels(test_df, destination_path, target_size=(128, 128)):\n    \"\"\"\n    Load images based on a CSV file containing Image_ID and their file paths.\n    Args:\n        test_df (pd.DataFrame): DataFrame with Image_IDs.\n        destination_path (str): Path to the directory containing images.\n        target_size (tuple): Size to which images should be resized (default: (128, 128)).\n    Returns:\n        images (np.array): Array of preprocessed test images.\n    \"\"\"\n    images1 = []\n    test_df=pd.read_csv('/kaggle/input/computer-vision-xm/test.csv')\n    # Loop through each row in the CSV\n    for idx, row in test_df.iterrows():\n        img_path1 = os.path.join(destination_path, row['Images'])  # Construct the image path\n        \n        # Ensure the image has the correct extension (if necessary)\n        #img_path1 = img_path1 + '.jpg'  # Assuming the images are in JPG format\n        \n        img1 = cv2.imread(img_path1)  # Read the image\n        if img1 is not None:\n            # Resize the image\n            img1 = cv2.resize(img1, target_size)\n            # Normalize the pixel values\n            img1 = img1 / 255.0\n            # Append the image to the list\n            images1.append(img1)\n        else:\n            print(f\"Failed to load image: {img_path1}\")\n    \n    # Convert images list to a NumPy array\n    images2 = np.array(images1)\n    \n    return images2\n\n# Load test images\ntest_images = load_test_images_and_labels(test_df, destination_path)\n\n# Print the shape to confirm the successful loading\nprint(f\"Test images shape: {test_images.shape}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:15:55.485946Z","iopub.execute_input":"2024-12-16T05:15:55.486193Z","iopub.status.idle":"2024-12-16T05:18:17.408777Z","shell.execute_reply.started":"2024-12-16T05:15:55.486169Z","shell.execute_reply":"2024-12-16T05:18:17.407826Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(f\"Train images shape: {train_images.shape}\")\nprint(f\"Test images shape: {test_images.shape}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:18:17.410200Z","iopub.execute_input":"2024-12-16T05:18:17.410934Z","iopub.status.idle":"2024-12-16T05:18:17.415383Z","shell.execute_reply.started":"2024-12-16T05:18:17.410885Z","shell.execute_reply":"2024-12-16T05:18:17.414542Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Test the modeL\npredictions = model.predict(test_images)  \npredicted_classes = (predictions > 0.5).astype(\"int32\")\nprint(predicted_classes)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:18:17.416520Z","iopub.execute_input":"2024-12-16T05:18:17.416907Z","iopub.status.idle":"2024-12-16T05:18:18.796525Z","shell.execute_reply.started":"2024-12-16T05:18:17.416865Z","shell.execute_reply":"2024-12-16T05:18:18.795683Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Evaluate the model on the test set\ntest_loss, test_accuracy = model.evaluate(valX, valY)\n\n# Print the results\nprint(f\"Test Loss: {test_loss}\")\nprint(f\"Test Accuracy: {test_accuracy}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:18:18.801558Z","iopub.execute_input":"2024-12-16T05:18:18.801814Z","iopub.status.idle":"2024-12-16T05:18:19.364449Z","shell.execute_reply.started":"2024-12-16T05:18:18.801791Z","shell.execute_reply":"2024-12-16T05:18:19.363529Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# predicted_classes = (predictions > 0.5).astype('int32')  # Threshold at 0.5 for binary classification\n\n# # Step 3: Evaluate the predictions\n# # If you have labels, you can calculate accuracy, confusion matrix, etc.\n# accuracy = accuracy_score(test_labels, predicted_classes)\n# print(f\"Test accuracy: {accuracy * 100:.2f}%\")\n\n# # If you want to evaluate the model on the test data, you can also use model.evaluate\n# loss, accuracy = model.evaluate(test_images, test_labels, batch_size=32)\n# print(f\"Test loss: {loss:.4f}, Test accuracy: {accuracy * 100:.2f}%\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:56:27.015107Z","iopub.execute_input":"2024-12-16T05:56:27.016043Z","iopub.status.idle":"2024-12-16T05:56:27.019876Z","shell.execute_reply.started":"2024-12-16T05:56:27.015996Z","shell.execute_reply":"2024-12-16T05:56:27.018990Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Get a batch of data\n#images, labels = next(train_data)  # Get the first batch from the generator\n\n# Number of images in the batch\nbatch_size = len(test_images)\nprint(batch_size)\nno_images=30\n# Determine grid size based on batch size, you can adjust this\nrows = 4\ncols = 8\n\n# Create a new figure\nplt.figure(figsize=(15, 10))\n\n# Loop over the images in the batch and display them using plt.imshow\nfor i in range(no_images):\n    plt.subplot(rows, cols, i + 1)  # Specify position in the grid\n    plt.imshow(test_images[i])  # Display the image\n    plt.axis('off')  # Turn off axes for each image\n\n# Adjust layout to avoid overlap\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:49:58.829715Z","iopub.execute_input":"2024-12-16T05:49:58.830080Z","iopub.status.idle":"2024-12-16T05:50:00.324535Z","shell.execute_reply.started":"2024-12-16T05:49:58.830048Z","shell.execute_reply":"2024-12-16T05:50:00.323551Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.imshow(test_images[0])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:58:13.476153Z","iopub.execute_input":"2024-12-16T05:58:13.476495Z","iopub.status.idle":"2024-12-16T05:58:13.806569Z","shell.execute_reply.started":"2024-12-16T05:58:13.476463Z","shell.execute_reply":"2024-12-16T05:58:13.805674Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# import cv2\n# import numpy as np\n\n# # Assuming 'image' is your original image with CV_64F type\n# first_image = test_images[0]\n# if first_image.dtype == np.float64:\n#     f_image = np.uint8(np.clip(first_image, 0, 255))  # Clip values and convert to 8-bit\n\n# # Now you can safely apply cvtColor or any other OpenCV operations\n# image_rgb = cv2.cvtColor(f_image, cv2.COLOR_GRAY2RGB)\n# plt.imshow(f_image)\n# plt.axis('off')  # Hide axis\n# plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:58:28.134722Z","iopub.execute_input":"2024-12-16T05:58:28.135559Z","iopub.status.idle":"2024-12-16T05:58:28.139291Z","shell.execute_reply.started":"2024-12-16T05:58:28.135521Z","shell.execute_reply":"2024-12-16T05:58:28.138323Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# import cv2\n# first_image = test_images[0]\n# first_image = cv2.cvtColor(first_image, cv2.COLOR_BGR2RGB)\n\n# # Display the first image\n# plt.imshow(first_image)\n# plt.axis('off')  # Hide axis\n# plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:58:37.926383Z","iopub.execute_input":"2024-12-16T05:58:37.927040Z","iopub.status.idle":"2024-12-16T05:58:37.930707Z","shell.execute_reply.started":"2024-12-16T05:58:37.927006Z","shell.execute_reply":"2024-12-16T05:58:37.929793Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# first_image = test_images[0]\n\n# # Display the first image\n# cv2.imshow('First Image', first_image)\n\n# # Wait for a key press to close the window\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:59:03.222017Z","iopub.execute_input":"2024-12-16T05:59:03.222714Z","iopub.status.idle":"2024-12-16T05:59:03.226626Z","shell.execute_reply.started":"2024-12-16T05:59:03.222678Z","shell.execute_reply":"2024-12-16T05:59:03.225638Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport cv2\n\n# Assuming test_images is your image dataset (loaded as a NumPy array)\nfirst_image = test_images[0]\n\n# If the image is normalized (float64), convert it to uint8\nfirst_image = (first_image * 255).astype(np.uint8)\n\n# Convert from BGR (OpenCV default) to RGB (for correct display in Matplotlib)\nfirst_image = cv2.cvtColor(first_image, cv2.COLOR_BGR2RGB)\n\n# Display the first image using Matplotlib\nplt.imshow(first_image)\nplt.axis('off')  # Hide the axis\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:34:56.881541Z","iopub.execute_input":"2024-12-16T05:34:56.881894Z","iopub.status.idle":"2024-12-16T05:34:57.086073Z","shell.execute_reply.started":"2024-12-16T05:34:56.881862Z","shell.execute_reply":"2024-12-16T05:34:57.085419Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Assuming first_image is already loaded and processed\nimport numpy as np\n\n# Print resolution (height and width)\nheight, width, channels = first_image.shape\nprint(f\"Resolution: {width}x{height}\")\nprint(f\"Number of channels: {channels}\")\n\n# Check data type and pixel value range\nprint(f\"Data type: {first_image.dtype}\")\nprint(f\"Pixel value range: Min={np.min(first_image)}, Max={np.max(first_image)}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:35:01.392281Z","iopub.execute_input":"2024-12-16T05:35:01.393174Z","iopub.status.idle":"2024-12-16T05:35:01.398897Z","shell.execute_reply.started":"2024-12-16T05:35:01.393108Z","shell.execute_reply":"2024-12-16T05:35:01.397840Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Calculate image size in bytes\nimage_size_bytes = first_image.nbytes /1024  # Total number of bytes used by the image array\nprint(f\"Image size: {image_size_bytes} KB\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:35:05.608717Z","iopub.execute_input":"2024-12-16T05:35:05.609403Z","iopub.status.idle":"2024-12-16T05:35:05.614033Z","shell.execute_reply.started":"2024-12-16T05:35:05.609369Z","shell.execute_reply":"2024-12-16T05:35:05.613040Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Assuming train_labels and val_labels are numpy arrays\nunique, counts = np.unique(trainY, return_counts=True)\nplt.bar(unique, counts)\nplt.xticks(unique, ['Healthy', 'Diseased'])\nplt.title('Label Distribution in Training Set')\nplt.xlabel('Labels')\nplt.ylabel('Count')\nplt.show()\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:35:11.678450Z","iopub.execute_input":"2024-12-16T05:35:11.679143Z","iopub.status.idle":"2024-12-16T05:35:11.896677Z","shell.execute_reply.started":"2024-12-16T05:35:11.679097Z","shell.execute_reply":"2024-12-16T05:35:11.895754Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#model.load('K1_model.h5')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:59:24.500839Z","iopub.execute_input":"2024-12-16T05:59:24.501637Z","iopub.status.idle":"2024-12-16T05:59:24.505487Z","shell.execute_reply.started":"2024-12-16T05:59:24.501598Z","shell.execute_reply":"2024-12-16T05:59:24.504438Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\n# List files in the current working directory\nprint(os.listdir('./'))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:35:32.735635Z","iopub.execute_input":"2024-12-16T05:35:32.735982Z","iopub.status.idle":"2024-12-16T05:35:32.740928Z","shell.execute_reply.started":"2024-12-16T05:35:32.735950Z","shell.execute_reply":"2024-12-16T05:35:32.739932Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir('/kaggle/working'))  # Default save location in Kaggle\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:35:35.835976Z","iopub.execute_input":"2024-12-16T05:35:35.836969Z","iopub.status.idle":"2024-12-16T05:35:35.841700Z","shell.execute_reply.started":"2024-12-16T05:35:35.836927Z","shell.execute_reply":"2024-12-16T05:35:35.840753Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save('/kaggle/working/K1_model.h5')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:35:39.169795Z","iopub.execute_input":"2024-12-16T05:35:39.170613Z","iopub.status.idle":"2024-12-16T05:35:39.356905Z","shell.execute_reply.started":"2024-12-16T05:35:39.170578Z","shell.execute_reply":"2024-12-16T05:35:39.356131Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save('/kaggle/output/K1_model.h5')  # Save to the output directory\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:38:01.178267Z","iopub.execute_input":"2024-12-16T05:38:01.179259Z","iopub.status.idle":"2024-12-16T05:38:01.261802Z","shell.execute_reply.started":"2024-12-16T05:38:01.179224Z","shell.execute_reply":"2024-12-16T05:38:01.260758Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.models import load_model\n\nmodel = load_model('/kaggle/working/K1_model.h5')  # Update the path if needed\nmodel.summary()  # Verify the model structure\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:38:36.849040Z","iopub.execute_input":"2024-12-16T05:38:36.849747Z","iopub.status.idle":"2024-12-16T05:38:36.960844Z","shell.execute_reply.started":"2024-12-16T05:38:36.849711Z","shell.execute_reply":"2024-12-16T05:38:36.959962Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save('/kaggle/output/K1_model.h5')  # Save to output directory\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-16T05:44:29.353028Z","iopub.execute_input":"2024-12-16T05:44:29.353876Z","iopub.status.idle":"2024-12-16T05:44:29.427227Z","shell.execute_reply.started":"2024-12-16T05:44:29.353842Z","shell.execute_reply":"2024-12-16T05:44:29.426549Z"}},"outputs":[],"execution_count":null}]}