{"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":"gpu","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"},{"sourceId":9343611,"sourceType":"datasetVersion","datasetId":5662767},{"sourceId":109642,"sourceType":"modelInstanceVersion","modelInstanceId":91826,"modelId":116037}],"dockerImageVersionId":30762,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"<div style =\"font-family:Trebuchet MS; background-color : #f8f0fa; border-left: 5px solid #1b4332; padding: 12px; border-radius: 50px 50px;\">\n    <h2 style=\"color: #1b4332; font-size: 48px; text-align: center;\"><b> Dog-Cat Classification\n </b></h2>","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport gc\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport random\nimport matplotlib.image as mpimg\nimport cv2\nimport zipfile\nfrom tqdm import tqdm\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import Sequential,Model\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Activation, BatchNormalization,Dense, Dropout,GlobalAveragePooling2D\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-09-09T07:14:01.737786Z","iopub.execute_input":"2024-09-09T07:14:01.738171Z","iopub.status.idle":"2024-09-09T07:14:01.745801Z","shell.execute_reply.started":"2024-09-09T07:14:01.738138Z","shell.execute_reply":"2024-09-09T07:14:01.744716Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Images Exploration & Analysis","metadata":{}},{"cell_type":"code","source":"zip_file_path = '/kaggle/input/dogs-vs-cats/train.zip'\nextract_folder = '/kaggle/working/pictures'\n\n\nos.makedirs(extract_folder, exist_ok=True)\n\n# Extract the zip file\nwith zipfile.ZipFile(zip_file_path, 'r') as zip_ref:\n    zip_ref.extractall(extract_folder)\nprint(os.listdir(extract_folder))\n","metadata":{"execution":{"iopub.status.busy":"2024-09-09T07:14:02.981998Z","iopub.execute_input":"2024-09-09T07:14:02.982744Z","iopub.status.idle":"2024-09-09T07:14:12.127514Z","shell.execute_reply.started":"2024-09-09T07:14:02.982705Z","shell.execute_reply":"2024-09-09T07:14:12.126488Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image\n\n# Folder where the images are extracted\nimage_folder = '/kaggle/working/pictures/train'\n\n# Get a list of image filenames\nimage_files = [f for f in os.listdir(image_folder) if f.endswith(('.png', '.jpg', '.jpeg'))]\n\n# Show sample images with their filenames\nnum_samples = min(5, len(image_files))  # Display up to 5 images\n\nplt.figure(figsize=(10, 10))\nfor i, image_file in enumerate(image_files[:num_samples]):\n    img_path = os.path.join(image_folder, image_file)\n    img = Image.open(img_path)\n    \n    # Display the image\n    plt.subplot(1, num_samples, i + 1)\n    plt.imshow(img)\n    plt.title(image_file, fontsize=8)\n    plt.axis('off')\n\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-09-09T07:14:12.129525Z","iopub.execute_input":"2024-09-09T07:14:12.129968Z","iopub.status.idle":"2024-09-09T07:14:12.625680Z","shell.execute_reply.started":"2024-09-09T07:14:12.129920Z","shell.execute_reply":"2024-09-09T07:14:12.624708Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(image_files)","metadata":{"execution":{"iopub.status.busy":"2024-09-09T07:14:12.626742Z","iopub.execute_input":"2024-09-09T07:14:12.627037Z","iopub.status.idle":"2024-09-09T07:14:12.633079Z","shell.execute_reply.started":"2024-09-09T07:14:12.627005Z","shell.execute_reply":"2024-09-09T07:14:12.632087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(image_files[4])","metadata":{"execution":{"iopub.status.busy":"2024-09-09T07:14:12.635150Z","iopub.execute_input":"2024-09-09T07:14:12.635449Z","iopub.status.idle":"2024-09-09T07:14:12.642779Z","shell.execute_reply.started":"2024-09-09T07:14:12.635417Z","shell.execute_reply":"2024-09-09T07:14:12.641936Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_files[0].split('.')[0]","metadata":{"execution":{"iopub.status.busy":"2024-09-09T07:14:12.643972Z","iopub.execute_input":"2024-09-09T07:14:12.644340Z","iopub.status.idle":"2024-09-09T07:14:12.652866Z","shell.execute_reply.started":"2024-09-09T07:14:12.644296Z","shell.execute_reply":"2024-09-09T07:14:12.651906Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cats = 0\ndogs = 0\nfor file in image_files :\n    if file.split('.')[0] == 'dog' :\n        dogs += 1\n    else :\n        cats +=1 \n\ncats,dogs\n    ","metadata":{"execution":{"iopub.status.busy":"2024-09-09T07:14:12.654121Z","iopub.execute_input":"2024-09-09T07:14:12.654486Z","iopub.status.idle":"2024-09-09T07:14:12.674708Z","shell.execute_reply.started":"2024-09-09T07:14:12.654443Z","shell.execute_reply":"2024-09-09T07:14:12.673927Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Labels and data for the pie chart\nlabels = ['Dogs', 'Cats']\nsizes = [dogs, cats]\ncolors = ['#ff9999','#66b3ff']  \n# Create a pie chart\nplt.figure(figsize=(6, 6))\nplt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, colors=colors)\nplt.axis('equal')\nplt.title('Distribution of Dogs and Cats')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-09-09T07:14:12.675835Z","iopub.execute_input":"2024-09-09T07:14:12.676182Z","iopub.status.idle":"2024-09-09T07:14:12.821599Z","shell.execute_reply.started":"2024-09-09T07:14:12.676141Z","shell.execute_reply":"2024-09-09T07:14:12.819998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**we have a balanced data**","metadata":{}},{"cell_type":"code","source":"del image_files\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-09-09T07:14:12.823734Z","iopub.execute_input":"2024-09-09T07:14:12.824390Z","iopub.status.idle":"2024-09-09T07:14:13.160737Z","shell.execute_reply.started":"2024-09-09T07:14:12.824324Z","shell.execute_reply":"2024-09-09T07:14:13.159738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Preprocessing","metadata":{}},{"cell_type":"code","source":"IMAGE_SIZE = (224,224)\ndef load_data(image_dir_train):\n    def process_images(image_dir):\n        images = []\n        print(\"Loading images from {}\".format(image_dir))\n        for image_file in tqdm(os.listdir(image_dir)):\n            img_path = os.path.join(image_dir, image_file)\n\n            # Open and resize the image\n            image = cv2.imread(img_path)\n            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n            image = cv2.resize(image, IMAGE_SIZE)\n\n            images.append(image)\n\n        return np.array(images, dtype='float32')\n\n    # Process train images and labels\n    train_images = process_images(image_dir_train)\n    labels = []\n    for image_file in tqdm(os.listdir(image_dir_train)):\n        image_class = image_file.split('.')[0]\n        if image_class == 'dog' :\n            labels.append(1)\n        else :\n            labels.append(0)\n    train_labels = np.array(labels, dtype='int32')\n    return train_images,train_labels \n\ntrain_images , train_labels = load_data(image_folder)\n ","metadata":{"execution":{"iopub.status.busy":"2024-09-09T07:18:05.385361Z","iopub.execute_input":"2024-09-09T07:18:05.386335Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mymap = {\n    0 : 'cat' ,\n    1 : 'dog'\n}","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Show the image (you must normalise it between 0 to 1)\ndef show_random(samples=5) :\n    plt.figure(figsize=(10, 10))\n    for i in range(samples) :\n        r = random.randint(0, 25000)\n        plt.subplot(1, samples, i + 1)\n        plt.imshow(train_images[r] / 255.0)\n        plt.title(f\"Label: {mymap[train_labels[r]]}\")\n        plt.axis('off')\n    plt.tight_layout()  # Adjust spacing to make sure images fit well\n    plt.show()\nshow_random()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# CNN creation ","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain_images = train_images.astype('uint8')\n# Split data into training and validation sets\nX_train, X_val, y_train, y_val = train_test_split(train_images, train_labels, test_size=0.2,shuffle=True, random_state=42)\n\nprint(f\"Training data shape: {X_train.shape}\")\nprint(f\"Validation data shape: {X_val.shape}\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from collections import Counter\n\nprint(\"Train labels distribution:\", Counter(y_train))\nprint(\"Validation labels distribution:\", Counter(y_val))\n","metadata":{"execution":{"iopub.status.busy":"2024-09-07T21:37:42.349713Z","iopub.execute_input":"2024-09-07T21:37:42.350114Z","iopub.status.idle":"2024-09-07T21:37:42.362957Z","shell.execute_reply.started":"2024-09-07T21:37:42.350077Z","shell.execute_reply":"2024-09-07T21:37:42.362022Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del train_images,train_labels\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-09-07T21:37:42.857621Z","iopub.execute_input":"2024-09-07T21:37:42.857974Z","iopub.status.idle":"2024-09-07T21:37:43.097375Z","shell.execute_reply.started":"2024-09-07T21:37:42.857930Z","shell.execute_reply":"2024-09-07T21:37:43.096437Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential([\n    Conv2D(32, (3, 3),input_shape = (224,224,3) , activation='relu'),\n    MaxPooling2D(2, 2),\n    Conv2D(64, (3, 3), activation='relu'),\n    MaxPooling2D(2, 2),\n    Conv2D(128, (3, 3),  activation='relu'),\n    MaxPooling2D(2, 2),\n    Conv2D(256, (3, 3), activation='relu'),\n    MaxPooling2D(2, 2),\n    Flatten(),\n    Dense(512, activation='relu'),\n    Dropout(0.4),  # Dropout to prevent overfitting\n    Dense(1, activation='sigmoid')\n])","metadata":{"execution":{"iopub.status.busy":"2024-09-07T21:37:56.685904Z","iopub.execute_input":"2024-09-07T21:37:56.686886Z","iopub.status.idle":"2024-09-07T21:37:56.745330Z","shell.execute_reply.started":"2024-09-07T21:37:56.686842Z","shell.execute_reply":"2024-09-07T21:37:56.744316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=Adam(learning_rate=0.0001), \n              loss='binary_crossentropy', \n              metrics=['accuracy'])\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-09-07T21:38:00.773663Z","iopub.execute_input":"2024-09-07T21:38:00.774590Z","iopub.status.idle":"2024-09-07T21:38:00.811131Z","shell.execute_reply.started":"2024-09-07T21:38:00.774541Z","shell.execute_reply":"2024-09-07T21:38:00.810214Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**adding callback early stop**","metadata":{}},{"cell_type":"code","source":"early_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)","metadata":{"execution":{"iopub.status.busy":"2024-09-07T21:38:09.737282Z","iopub.execute_input":"2024-09-07T21:38:09.738419Z","iopub.status.idle":"2024-09-07T21:38:09.742532Z","shell.execute_reply.started":"2024-09-07T21:38:09.738378Z","shell.execute_reply":"2024-09-07T21:38:09.741647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BATCH_SIZE = 32\n# datagen3 = ImageDataGenerator(\n#     rescale=1.0/255.0,\n# )\n# train_generator3 = datagen3.flow(X_train, y_train, BATCH_SIZE,shuffle=True)\nval_datagen = ImageDataGenerator(rescale=1./255)\nval_generator = val_datagen.flow(X_val, y_val, BATCH_SIZE)","metadata":{"execution":{"iopub.status.busy":"2024-09-07T21:38:28.854827Z","iopub.execute_input":"2024-09-07T21:38:28.855828Z","iopub.status.idle":"2024-09-07T21:38:29.570319Z","shell.execute_reply.started":"2024-09-07T21:38:28.855776Z","shell.execute_reply":"2024-09-07T21:38:29.569456Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def train_model_with_generator(train_gen, batch_size=32, epochs=15):\n    history = model.fit(\n    train_gen,\n    validation_data= val_generator,\n    epochs=epochs,\n    callbacks=[early_stopping],\n        )\n\n    \n    return history","metadata":{"execution":{"iopub.status.busy":"2024-09-07T21:38:35.227117Z","iopub.execute_input":"2024-09-07T21:38:35.228296Z","iopub.status.idle":"2024-09-07T21:38:35.234348Z","shell.execute_reply.started":"2024-09-07T21:38:35.228242Z","shell.execute_reply":"2024-09-07T21:38:35.233273Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_loss(history) :\n    plt.figure(figsize=(10, 6))\n    plt.plot(history.history['loss'], label='Train Loss')\n    plt.plot(history.history['val_loss'], label='Validation Loss')\n    plt.title('Model Loss')\n    plt.xlabel('Epoch')\n    plt.ylabel('Loss')\n    plt.legend(loc='upper right')\n    plt.grid(True)\n    plt.show()\n\n    # Evaluate the model\n    val_loss, val_accuracy = model.evaluate(X_val, y_val, verbose=0)\n    print(f\"Validation Loss: {val_loss:.4f}\")\n    print(f\"Validation Accuracy: {val_accuracy:.4f}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-09-07T21:38:36.704951Z","iopub.execute_input":"2024-09-07T21:38:36.705827Z","iopub.status.idle":"2024-09-07T21:38:36.712033Z","shell.execute_reply.started":"2024-09-07T21:38:36.705788Z","shell.execute_reply":"2024-09-07T21:38:36.711097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_acc(history) :\n    plt.figure(figsize=(10, 6))\n    plt.plot(history.history['accuracy'], label='Train Accuracy')\n    plt.plot(history.history['val_accuracy'], label='Validation Accuracy')\n    plt.title('Model Accuracy')\n    plt.xlabel('Epoch')\n    plt.ylabel('Loss')\n    plt.legend(loc='upper right')\n    plt.grid(True)\n    plt.show()\n\n    # Evaluate the model\n    val_loss, val_accuracy = model.evaluate(X_val, y_val, verbose=0)\n    print(f\"Validation Loss: {val_loss:.4f}\")\n    print(f\"Validation Accuracy: {val_accuracy:.4f}\")","metadata":{"execution":{"iopub.status.busy":"2024-09-07T21:38:36.896132Z","iopub.execute_input":"2024-09-07T21:38:36.896808Z","iopub.status.idle":"2024-09-07T21:38:36.903074Z","shell.execute_reply.started":"2024-09-07T21:38:36.896772Z","shell.execute_reply":"2024-09-07T21:38:36.902122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# history =  train_model_with_generator(train_generator3)","metadata":{"execution":{"iopub.status.busy":"2024-09-07T21:30:37.150173Z","iopub.execute_input":"2024-09-07T21:30:37.150976Z","iopub.status.idle":"2024-09-07T21:34:41.432498Z","shell.execute_reply.started":"2024-09-07T21:30:37.150931Z","shell.execute_reply":"2024-09-07T21:34:41.431434Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plot_acc(history)\n# plot_loss(history)","metadata":{"execution":{"iopub.status.busy":"2024-09-07T21:34:45.527871Z","iopub.execute_input":"2024-09-07T21:34:45.528857Z","iopub.status.idle":"2024-09-07T21:34:53.507484Z","shell.execute_reply.started":"2024-09-07T21:34:45.528807Z","shell.execute_reply":"2024-09-07T21:34:53.506480Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# del train_generator3,datagen3,history\n# import gc\n# gc.collect()\n","metadata":{"execution":{"iopub.status.busy":"2024-09-07T21:35:05.899491Z","iopub.execute_input":"2024-09-07T21:35:05.900386Z","iopub.status.idle":"2024-09-07T21:35:06.152685Z","shell.execute_reply.started":"2024-09-07T21:35:05.900344Z","shell.execute_reply":"2024-09-07T21:35:06.151695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Augmentation","metadata":{}},{"cell_type":"code","source":"datagen2 = ImageDataGenerator(\n    rescale=1.0/255.0,\n    horizontal_flip=True,     # Randomly flip half the images horizontally\n    zoom_range=[0.9, 1.1],    # Slightly conservative zoom\n    brightness_range=[0.8, 1.2], # Randomly change brightness\n    fill_mode='nearest'       # Fill in new pixels using reflection to avoid artifacts\n)\ntrain_generator2 = datagen2.flow(X_train, y_train, BATCH_SIZE)","metadata":{"execution":{"iopub.status.busy":"2024-09-07T21:38:52.496112Z","iopub.execute_input":"2024-09-07T21:38:52.496780Z","iopub.status.idle":"2024-09-07T21:38:55.323886Z","shell.execute_reply.started":"2024-09-07T21:38:52.496741Z","shell.execute_reply":"2024-09-07T21:38:55.323001Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history_image_augmentation = train_model_with_generator(train_generator2)","metadata":{"execution":{"iopub.status.busy":"2024-09-07T21:39:10.196940Z","iopub.execute_input":"2024-09-07T21:39:10.197729Z","iopub.status.idle":"2024-09-07T22:39:16.771709Z","shell.execute_reply.started":"2024-09-07T21:39:10.197691Z","shell.execute_reply":"2024-09-07T22:39:16.770777Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_acc(history_image_augmentation)\nplot_loss(history_image_augmentation)","metadata":{"execution":{"iopub.status.busy":"2024-09-07T22:39:29.591591Z","iopub.execute_input":"2024-09-07T22:39:29.592485Z","iopub.status.idle":"2024-09-07T22:39:34.333236Z","shell.execute_reply.started":"2024-09-07T22:39:29.592444Z","shell.execute_reply":"2024-09-07T22:39:34.332253Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**we got better results with data augmentation**","metadata":{}},{"cell_type":"markdown","source":"# Make Prediction & Save the Model","metadata":{}},{"cell_type":"code","source":"# model.save('rafik_dog_cat_class.h5')","metadata":{"execution":{"iopub.status.busy":"2024-09-07T22:49:36.280907Z","iopub.execute_input":"2024-09-07T22:49:36.281802Z","iopub.status.idle":"2024-09-07T22:49:36.495976Z","shell.execute_reply.started":"2024-09-07T22:49:36.281762Z","shell.execute_reply":"2024-09-07T22:49:36.495163Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.models import load_model\n\nmodel = load_model('/kaggle/input/rafik_cat_dog/keras/default/1/rafik_dog_cat_class.h5')\n","metadata":{"execution":{"iopub.status.busy":"2024-09-09T06:36:01.147885Z","iopub.execute_input":"2024-09-09T06:36:01.148340Z","iopub.status.idle":"2024-09-09T06:36:03.159271Z","shell.execute_reply.started":"2024-09-09T06:36:01.148295Z","shell.execute_reply":"2024-09-09T06:36:03.158485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing import image\nimport numpy as np\n\nmymap = {\n    0 : 'cat' ,\n    1 : 'dog'\n}\nmodel = load_model('/kaggle/input/rafik_cat_dog/keras/default/1/rafik_dog_cat_class.h5')\n\n\ndef preprocess_image(image_path, target_size=(224, 224)):\n    img = image.load_img(image_path, target_size=target_size)\n    img_array = image.img_to_array(img)\n    img_array = np.expand_dims(img_array, axis=0) \n    img_array = img_array / 255.0  \n    return img_array\n\nimg_array = preprocess_image('/kaggle/input/cat-dog-test/dog3.jpg')\npredictions = model.predict(img_array)\nprint(predictions)\npredicted_class = (predictions > 0.5).astype(\"int32\")\nprint(f\"Predicted class: {predicted_class}\")\nplt.imshow(np.squeeze(img_array, axis=0))\nplt.title(f\"Label: {mymap[predicted_class[0][0]]}\")\nplt.axis('off')\nplt.tight_layout()  \nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-09-09T06:36:06.291430Z","iopub.execute_input":"2024-09-09T06:36:06.291831Z","iopub.status.idle":"2024-09-09T06:36:09.415996Z","shell.execute_reply.started":"2024-09-09T06:36:06.291792Z","shell.execute_reply":"2024-09-09T06:36:09.415090Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submit result ","metadata":{}},{"cell_type":"code","source":"# sample_submission = pd.read_csv('/kaggle/input/dogs-vs-cats/sampleSubmission.csv')\n# sample_submission","metadata":{"execution":{"iopub.status.busy":"2024-09-09T06:36:25.664235Z","iopub.execute_input":"2024-09-09T06:36:25.664965Z","iopub.status.idle":"2024-09-09T06:36:25.696544Z","shell.execute_reply.started":"2024-09-09T06:36:25.664921Z","shell.execute_reply":"2024-09-09T06:36:25.695675Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# zip_file_path = '/kaggle/input/dogs-vs-cats/test1.zip'\n# extract_folder = '/kaggle/working/pictures'\n\n\n# os.makedirs(extract_folder, exist_ok=True)\n\n# # Extract the zip file\n# with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:\n#     zip_ref.extractall(extract_folder)\n# print(os.listdir(extract_folder))\n","metadata":{"execution":{"iopub.status.busy":"2024-09-09T06:36:26.730218Z","iopub.execute_input":"2024-09-09T06:36:26.730835Z","iopub.status.idle":"2024-09-09T06:36:31.155099Z","shell.execute_reply.started":"2024-09-09T06:36:26.730793Z","shell.execute_reply":"2024-09-09T06:36:31.154127Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# from PIL import Image\n\n# # Folder where the images are extracted\n# image_folder = '/kaggle/working/pictures/test1'\n\n# image_files = [f for f in os.listdir(image_folder) if f.endswith(('.png', '.jpg', '.jpeg'))]\n# num_samples = min(5, len(image_files))\n\n# plt.figure(figsize=(10, 10))\n# for i, image_file in enumerate(image_files[:num_samples]):\n#     img_path = os.path.join(image_folder, image_file)\n#     img = Image.open(img_path)\n    \n#     # Display the image\n#     plt.subplot(1, num_samples, i + 1)\n#     plt.imshow(img)\n#     plt.title(image_file, fontsize=8)\n#     plt.axis('off')\n\n# plt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-09-09T06:36:31.156885Z","iopub.execute_input":"2024-09-09T06:36:31.157614Z","iopub.status.idle":"2024-09-09T06:36:31.621499Z","shell.execute_reply.started":"2024-09-09T06:36:31.157567Z","shell.execute_reply":"2024-09-09T06:36:31.620607Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# IMAGE_SIZE = (224,224)\n# def load_data(image_dir):\n#     \"\"\"\n#     Load and preprocess the test images.\n#     \"\"\"\n#     images = []\n#     ids = []\n\n#     print(\"Loading test images from {}\".format(image_dir))\n#     for image_file in tqdm(os.listdir(image_dir)):\n#         img_path = os.path.join(image_dir, image_file)\n        \n#         # Load and preprocess the image\n#         img = cv2.imread(img_path)\n#         img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n#         img = cv2.resize(img, IMAGE_SIZE)\n\n       \n#         img = img / 255.0\n        \n#         images.append(img)\n#         img_id = image_file.split('.')[0]  # Extract the image ID (without extension)\n#         ids.append(img_id)\n\n#     return np.array(images, dtype='float32'), ids\n\n# # Load test images\n# test_images, ids = load_data('/kaggle/working/pictures/test1')\n\n# print(\"Making predictions on the test images...\")\n# predictions = model.predict(test_images)\n\n# # Convert predictions to labels\n# predicted_labels = (predictions > 0.5).astype('int32').flatten()\n\n\n# submission_df = pd.DataFrame({\n#     'id': ids,\n#     'label': predicted_labels\n# })\n# submission_csv_path = 'submission.csv' \n# submission_df = submission_df.sort_values(by='id')\n# submission_df.to_csv(submission_csv_path, index=False)\n# print(f\"Submission file saved: {submission_csv_path}\")","metadata":{"execution":{"iopub.status.busy":"2024-09-09T06:37:15.527513Z","iopub.execute_input":"2024-09-09T06:37:15.528330Z","iopub.status.idle":"2024-09-09T06:38:10.764360Z","shell.execute_reply.started":"2024-09-09T06:37:15.528289Z","shell.execute_reply":"2024-09-09T06:38:10.763407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# output_submission = pd.read_csv('/kaggle/working/submission.csv')\n# output_submission","metadata":{"execution":{"iopub.status.busy":"2024-09-09T06:38:22.933308Z","iopub.execute_input":"2024-09-09T06:38:22.934180Z","iopub.status.idle":"2024-09-09T06:38:22.948262Z","shell.execute_reply.started":"2024-09-09T06:38:22.934134Z","shell.execute_reply":"2024-09-09T06:38:22.947166Z"},"trusted":true},"execution_count":null,"outputs":[]}]}