{"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":30378,"sourceType":"datasetVersion","datasetId":23777},{"sourceId":9204376,"sourceType":"datasetVersion","datasetId":5565200},{"sourceId":9204483,"sourceType":"datasetVersion","datasetId":5565278}],"dockerImageVersionId":30747,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# basic libraries\nimport os\nimport random\nimport cv2\n\n# For data manipulation\nimport numpy as np \nimport pandas as pd \n\n# For data visualization\nimport matplotlib.pyplot as plt \nimport seaborn as sns\n\n# Ingore the warnings\n# import warnings\n# warnings.filterwarnings('ignore')\n\n# DL Libraries\nimport tensorflow\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout\nfrom tensorflow.keras.utils import image_dataset_from_directory\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing import image","metadata":{"execution":{"iopub.status.busy":"2024-08-19T15:20:00.700991Z","iopub.execute_input":"2024-08-19T15:20:00.701679Z","iopub.status.idle":"2024-08-19T15:20:00.707806Z","shell.execute_reply.started":"2024-08-19T15:20:00.701647Z","shell.execute_reply":"2024-08-19T15:20:00.706843Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dr = keras.utils.image_dataset_from_directory(directory='/kaggle/input/cat-and-dog/training_set/training_set')\ntest_dr = keras.utils.image_dataset_from_directory('/kaggle/input/cat-and-dog/test_set/test_set')","metadata":{"execution":{"iopub.status.busy":"2024-08-19T14:45:57.891018Z","iopub.execute_input":"2024-08-19T14:45:57.891640Z","iopub.status.idle":"2024-08-19T14:46:09.901006Z","shell.execute_reply.started":"2024-08-19T14:45:57.891608Z","shell.execute_reply":"2024-08-19T14:46:09.900282Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"classes = test_dr.class_names\nclasses","metadata":{"execution":{"iopub.status.busy":"2024-08-19T14:46:12.381769Z","iopub.execute_input":"2024-08-19T14:46:12.382546Z","iopub.status.idle":"2024-08-19T14:46:12.389338Z","shell.execute_reply.started":"2024-08-19T14:46:12.382495Z","shell.execute_reply":"2024-08-19T14:46:12.388422Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# getting path from directory\ncats_imgs_dir = []\nfor dirname, _, filenames in os.walk('/kaggle/input/cat-and-dog/training_set/training_set/cats'):\n    for filename in filenames:\n        path = os.path.join(dirname, filename)\n        cats_imgs_dir.append(path)\ncats_imgs_dir[0:5] # show example of first five pics","metadata":{"execution":{"iopub.status.busy":"2024-08-19T14:46:15.399082Z","iopub.execute_input":"2024-08-19T14:46:15.399713Z","iopub.status.idle":"2024-08-19T14:46:16.121587Z","shell.execute_reply.started":"2024-08-19T14:46:15.399665Z","shell.execute_reply":"2024-08-19T14:46:16.120705Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# loop thru to get index and pictures\nfor i, path in enumerate(cats_imgs_dir[0:5]):\n    print(i, path)","metadata":{"execution":{"iopub.status.busy":"2024-08-19T14:46:18.753565Z","iopub.execute_input":"2024-08-19T14:46:18.753925Z","iopub.status.idle":"2024-08-19T14:46:18.759438Z","shell.execute_reply.started":"2024-08-19T14:46:18.753896Z","shell.execute_reply":"2024-08-19T14:46:18.758417Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# getting path from directory\ndogs_imgs_dir = []\nfor dirname, _, filenames in os.walk('/kaggle/input/cat-and-dog/training_set/training_set/dogs'):\n    for filename in filenames:\n        path = os.path.join(dirname, filename)\n        dogs_imgs_dir.append(path)\ndogs_imgs_dir[0:5]","metadata":{"execution":{"iopub.status.busy":"2024-08-19T14:46:56.265002Z","iopub.execute_input":"2024-08-19T14:46:56.265713Z","iopub.status.idle":"2024-08-19T14:46:56.843936Z","shell.execute_reply.started":"2024-08-19T14:46:56.265683Z","shell.execute_reply":"2024-08-19T14:46:56.843029Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# show example of cats and dogs images\nprint('CATs\\n')\nplt.figure(figsize=(10,10))\nfor i, path in enumerate(cats_imgs_dir[20:25]):\n    plt.subplot(1,5,i+1)\n    plt.axis('off')\n    plt.imshow(plt.imread(path))\nplt.show()\n\nprint('\\nDOGs\\n')\nplt.figure(figsize=(10,10))\nfor i, path in enumerate(dogs_imgs_dir[0:5]):\n    plt.subplot(1,5,i+1)\n    plt.axis('off')\n    plt.imshow(plt.imread(path))\n    \nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-08-19T14:46:59.957346Z","iopub.execute_input":"2024-08-19T14:46:59.958034Z","iopub.status.idle":"2024-08-19T14:47:00.760126Z","shell.execute_reply.started":"2024-08-19T14:46:59.958007Z","shell.execute_reply":"2024-08-19T14:47:00.759234Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model Arthitecture","metadata":{}},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(64, kernel_size=(3,3), activation='relu', input_shape=(256,256,3)))\nmodel.add(MaxPooling2D())\n\nmodel.add(Conv2D(128, kernel_size=(3,3), activation='relu'))\nmodel.add(MaxPooling2D())\n\nmodel.add(Flatten())\n\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dense(64, activation='relu'))\nmodel.add(Dense(32, activation='relu'))\n\nmodel.add(Dense(1, activation='sigmoid'))","metadata":{"execution":{"iopub.status.busy":"2024-08-19T15:01:13.716199Z","iopub.execute_input":"2024-08-19T15:01:13.717070Z","iopub.status.idle":"2024-08-19T15:01:13.804929Z","shell.execute_reply.started":"2024-08-19T15:01:13.717038Z","shell.execute_reply":"2024-08-19T15:01:13.804241Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-08-19T14:47:13.599716Z","iopub.execute_input":"2024-08-19T14:47:13.600375Z","iopub.status.idle":"2024-08-19T14:47:13.624994Z","shell.execute_reply.started":"2024-08-19T14:47:13.600344Z","shell.execute_reply":"2024-08-19T14:47:13.624194Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model Compilation","metadata":{}},{"cell_type":"code","source":"model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-08-19T15:01:20.013864Z","iopub.execute_input":"2024-08-19T15:01:20.014232Z","iopub.status.idle":"2024-08-19T15:01:20.023560Z","shell.execute_reply.started":"2024-08-19T15:01:20.014185Z","shell.execute_reply":"2024-08-19T15:01:20.022704Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(train_dr, batch_size=32, epochs=20, validation_data=test_dr, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2024-08-19T15:01:26.769945Z","iopub.execute_input":"2024-08-19T15:01:26.770800Z","iopub.status.idle":"2024-08-19T15:10:53.863864Z","shell.execute_reply.started":"2024-08-19T15:01:26.770768Z","shell.execute_reply":"2024-08-19T15:10:53.863099Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Evaluate the model","metadata":{}},{"cell_type":"code","source":"plt.plot(history.history['accuracy'], label='accuracy')\nplt.plot(history.history['val_accuracy'], label='val_accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend(loc='upper right')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-08-19T15:10:58.496485Z","iopub.execute_input":"2024-08-19T15:10:58.496827Z","iopub.status.idle":"2024-08-19T15:10:58.696624Z","shell.execute_reply.started":"2024-08-19T15:10:58.496801Z","shell.execute_reply":"2024-08-19T15:10:58.695786Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss, accuracy = model.evaluate(test_dr)","metadata":{"execution":{"iopub.status.busy":"2024-08-19T15:11:04.290713Z","iopub.execute_input":"2024-08-19T15:11:04.291056Z","iopub.status.idle":"2024-08-19T15:11:06.120906Z","shell.execute_reply.started":"2024-08-19T15:11:04.291029Z","shell.execute_reply":"2024-08-19T15:11:06.120117Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"accuracy","metadata":{"execution":{"iopub.status.busy":"2024-08-19T15:11:08.701567Z","iopub.execute_input":"2024-08-19T15:11:08.702044Z","iopub.status.idle":"2024-08-19T15:11:08.707882Z","shell.execute_reply.started":"2024-08-19T15:11:08.702002Z","shell.execute_reply":"2024-08-19T15:11:08.706986Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# saving the model","metadata":{}},{"cell_type":"code","source":"# save entire model including artitecture\nmodel.save('cnn_model.h5')","metadata":{"execution":{"iopub.status.busy":"2024-08-19T15:11:16.548894Z","iopub.execute_input":"2024-08-19T15:11:16.549720Z","iopub.status.idle":"2024-08-19T15:11:18.326885Z","shell.execute_reply.started":"2024-08-19T15:11:16.549684Z","shell.execute_reply":"2024-08-19T15:11:18.326094Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# load model","metadata":{}},{"cell_type":"code","source":"# load the model\nloaded_model = load_model('/kaggle/working/cnn_model.h5')\nloaded_model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-08-19T15:11:27.133695Z","iopub.execute_input":"2024-08-19T15:11:27.134056Z","iopub.status.idle":"2024-08-19T15:11:27.792547Z","shell.execute_reply.started":"2024-08-19T15:11:27.134026Z","shell.execute_reply":"2024-08-19T15:11:27.791670Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Predict","metadata":{}},{"cell_type":"code","source":"# Step 2: Load and preprocess the image\ndef load_and_preprocess_image(img_path):\n    # Load the image\n    img = image.load_img(img_path, target_size=(256,256))  # Adjust target_size to match your model input\n    # Convert the image to an array\n    img_array = image.img_to_array(img)\n    # Expand dimensions to match the shape of the model input (1, height, width, channels)\n    img_array = np.expand_dims(img_array, axis=0)\n    # Rescale the image if necessary (depends on your model training)\n#     img_array /= 255.0  # Assuming the model was trained with rescaled images\n    return img_array\n\n# Provide the image path you want to predict\nimg_path = '/kaggle/input/puppy-dog/puppy-1903313_640.jpg'\nprocessed_image = load_and_preprocess_image(img_path)\n\n# Step 3: Make predictions\npredictions = model.predict(processed_image)","metadata":{"execution":{"iopub.status.busy":"2024-08-19T15:27:49.914078Z","iopub.execute_input":"2024-08-19T15:27:49.915170Z","iopub.status.idle":"2024-08-19T15:27:49.996023Z","shell.execute_reply.started":"2024-08-19T15:27:49.915134Z","shell.execute_reply":"2024-08-19T15:27:49.995273Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# let's see an image our model have to predict : it is a puppy\nplt.imshow(plt.imread('/kaggle/input/puppy-dog/puppy-1903313_640.jpg'))\nplt.axis('off')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-08-19T15:32:12.521253Z","iopub.execute_input":"2024-08-19T15:32:12.521631Z","iopub.status.idle":"2024-08-19T15:32:12.802436Z","shell.execute_reply.started":"2024-08-19T15:32:12.521601Z","shell.execute_reply":"2024-08-19T15:32:12.801380Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions[0]","metadata":{"execution":{"iopub.status.busy":"2024-08-19T15:35:33.434086Z","iopub.execute_input":"2024-08-19T15:35:33.434459Z","iopub.status.idle":"2024-08-19T15:35:33.440837Z","shell.execute_reply.started":"2024-08-19T15:35:33.434429Z","shell.execute_reply":"2024-08-19T15:35:33.439894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Step 4: Interpret the results\n# If it's a binary classification problem\nif model.output_shape[-1] == 1:\n#     predicted_class = 'Class 1' if predictions[0] > 0.5 else 'Class 0'\n    predicted_class = 'Dogs' if predictions[0] > 0.5 else 'Cats'\n    confidence = predictions[0][0] if predictions[0] > 0.5 else 1 - predictions[0][0]\nelse:\n    # If it's a multi-class classification problem\n    predicted_class_index = np.argmax(predictions)\n    confidence = np.max(predictions)\n    # Assuming you have a mapping of class indices to class labels\n    class_labels = {0: 'Class 0', 1: 'Class 1', 2: 'Class 2'}  # Modify this according to your classes\n    predicted_class = class_labels[predicted_class_index]\n\nprint(f\"Predicted class: {predicted_class} with confidence {confidence:.2f}\")","metadata":{"execution":{"iopub.status.busy":"2024-08-19T15:30:51.719995Z","iopub.execute_input":"2024-08-19T15:30:51.720802Z","iopub.status.idle":"2024-08-19T15:30:51.727867Z","shell.execute_reply.started":"2024-08-19T15:30:51.720770Z","shell.execute_reply":"2024-08-19T15:30:51.726954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"classes","metadata":{"execution":{"iopub.status.busy":"2024-08-19T15:30:56.211085Z","iopub.execute_input":"2024-08-19T15:30:56.211909Z","iopub.status.idle":"2024-08-19T15:30:56.217444Z","shell.execute_reply.started":"2024-08-19T15:30:56.211874Z","shell.execute_reply":"2024-08-19T15:30:56.216596Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"the model give the correct prediction","metadata":{}}]}