{"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":"none","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30664,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"#  1. Liberaries","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport os\nimport cv2\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Flatten\nimport warnings\nwarnings.filterwarnings('ignore')","metadata":{"execution":{"iopub.status.busy":"2024-03-12T02:42:37.766329Z","iopub.execute_input":"2024-03-12T02:42:37.766734Z","iopub.status.idle":"2024-03-12T02:42:52.188734Z","shell.execute_reply.started":"2024-03-12T02:42:37.766702Z","shell.execute_reply":"2024-03-12T02:42:52.187632Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#  2. Dataset","metadata":{}},{"cell_type":"code","source":"import zipfile\nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\", 'r') as zip_ref:\n  zip_ref.extractall(\"/kaggle/working/\")\nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/test1.zip\", 'r') as zip_ref:\n  zip_ref.extractall(\"/kaggle/working/\")","metadata":{"execution":{"iopub.status.busy":"2024-03-12T02:53:49.14867Z","iopub.execute_input":"2024-03-12T02:53:49.14981Z","iopub.status.idle":"2024-03-12T02:54:06.070182Z","shell.execute_reply.started":"2024-03-12T02:53:49.149769Z","shell.execute_reply":"2024-03-12T02:54:06.068848Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the paths to your dataset (assumes you have separate folders for cats and dogs)\ntrain_dir = '/path/to/train'\ntest_dir = '/path/to/test'","metadata":{"execution":{"iopub.status.busy":"2024-03-12T02:58:15.281528Z","iopub.execute_input":"2024-03-12T02:58:15.281947Z","iopub.status.idle":"2024-03-12T02:58:15.28711Z","shell.execute_reply.started":"2024-03-12T02:58:15.281916Z","shell.execute_reply":"2024-03-12T02:58:15.285982Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DATADIR = \"/kaggle/input/dogs-vs-cats\"\n\nCATEGORIES = ['test1', 'train']\n\nfor category in CATEGORIES:  # do dogs and cats\n    path = os.path.join(DATADIR,category)  # create path to dogs and cats\n    x=0\n    for img in os.listdir(path):  # iterate over each image per dogs and cats\n        x+=1\n        img_array = cv2.imread(os.path.join(path,img) ,cv2.IMREAD_GRAYSCALE)  # convert to array\n        plt.imshow(img_array, cmap='gray')  # graph it\n        plt.show()  # display!\n        if x==10 :\n           break  # we just want one for now so break\n    ","metadata":{"execution":{"iopub.status.busy":"2024-03-12T03:18:04.015601Z","iopub.execute_input":"2024-03-12T03:18:04.016016Z","iopub.status.idle":"2024-03-12T03:18:04.061411Z","shell.execute_reply.started":"2024-03-12T03:18:04.015982Z","shell.execute_reply":"2024-03-12T03:18:04.060253Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(img_array)\nprint(img_array.shape)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 3. Data Preprocessing:","metadata":{}},{"cell_type":"code","source":"IMG_SIZE = 100\n\nnew_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))\nplt.imshow(new_array, cmap='gray')\nplt.show()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"training_data = []\n\ndef create_training_data():\n    for category in CATEGORIES:  # do dogs and cats\n\n        path = os.path.join(DATADIR,category)  # create path to dogs and cats\n        class_num = CATEGORIES.index(category)  # get the classification  (0 or a 1). 0=dog 1=cat\n\n        for img in tqdm(os.listdir(path)):  # iterate over each image per dogs and cats\n            try:\n                img_array = cv2.imread(os.path.join(path,img) ,cv2.IMREAD_GRAYSCALE)  # convert to array\n                new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))  # resize to normalize data size\n                training_data.append([new_array, class_num])  # add this to our training_data\n            except Exception as e:  # in the interest in keeping the output clean...\n                pass\n            #except OSError as e:\n            #    print(\"OSErrroBad img most likely\", e, os.path.join(path,img))\n            #except Exception as e:\n            #    print(\"general exception\", e, os.path.join(path,img))\n\ncreate_training_data()\n\nprint(len(training_data))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(training_data[:5])","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(training_data[6000:6010])","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import random\n\nrandom.shuffle(training_data)\nfor sample in training_data[:10]:\n    print(sample[1])","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = []\ny = []\n\nfor features,label in training_data:\n    X.append(features)\n    y.append(label)\n\nprint(X[0].reshape(-1, IMG_SIZE, IMG_SIZE, 1))\n\nX = np.array(X).reshape(-1, IMG_SIZE, IMG_SIZE, 1)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X[:1]","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y[:1]","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"# 4. Built CNN Model & Train","metadata":{}},{"cell_type":"code","source":"# Splitting data\nX_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, random_state=42, shuffle=True)\nprint(X_train.shape)\nprint(X_test.shape)\nprint(y_train.shape)\nprint(y_test.shape)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nmodel = keras.Sequential([\n    keras.layers.Flatten(input_shape=(IMG_SIZE,IMG_SIZE)),\n    keras.layers.Dense(512,activation=tf.nn.relu),\n    keras.layers.Dense(256,activation=tf.nn.relu),\n    keras.layers.Dense(128,activation=tf.nn.relu),\n    keras.layers.Dense(512,activation=tf.nn.relu),\n    keras.layers.Dense(64,activation=tf.nn.relu),\n    keras.layers.Dense(32,activation=tf.nn.relu),\n    keras.layers.Dense(2,activation=tf.nn.softmax)\n])","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 5. Model Performance","metadata":{}},{"cell_type":"code","source":"model.fit(X_train, y_train, batch_size=32, epochs=10, validation_split=0.3)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_acc = history.history['accuracy']\ntrain_loss = history.history['loss']\n\nval_acc = history.history['val_accuracy']\nval_loss = history.history['val_loss']\n\nindex_loss = np.argmin(val_loss)\nindex_acc = np.argmax(val_acc)\n\nval_lowest = val_loss[index_loss]\nval_highest = val_acc[index_acc]\n\nEpochs = [i+1 for i in range(len(train_acc))]\n\nloss_label = f'Best Epoch = {str(index_loss + 1)}'\nacc_label = f'Best Epoch = {str(index_acc + 1)}'\n\nplt.figure(figsize= (20,8))\nplt.style.use('fivethirtyeight')\n\nplt.subplot(1,2,1)\nplt.plot(Epochs , train_loss , 'r', label = 'Training Loss')\nplt.plot(Epochs , val_loss , 'g' , label = 'Validation Loss')\nplt.scatter(index_loss +1 , val_lowest , s = 150 , c = 'blue' , label = loss_label)\nplt.title('Training vs Validation (loss)')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.subplot(1,2,2)\nplt.plot(Epochs , train_acc , 'r', label= 'Training Accuracy')\nplt.plot(Epochs , val_acc , 'g' , label = 'Validation Accuracy')\nplt.scatter(index_acc + 1 , val_highest , s= 150 , c = 'blue' , label= acc_label)\nplt.title('Training vs Validation (Accuracy)')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\n\nplt.tight_layout\nplt.show();","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 6. Model Evaluation","metadata":{}},{"cell_type":"code","source":"test_loss, test_acc = model.evaluate(X_test,y_test)\ntest_acc","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"output= model.predict(X_test)\ny_pred=np.argmax(output,axis=1)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 7. Confusion Matrix and Classification Report","metadata":{}},{"cell_type":"code","source":"classification_rep = classification_report(y_pred,y_test)\nprint(\"\\nClassification Report:\")\nprint(classification_rep)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"confusion_matrix(y_test,y_pred)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"## Visualise predictions ( 6 out of 9 correct predicitions )\npath = 'D:\\Courses\\Interns\\ProdigyInfoTech\\Task_3\\Dogs vs. Cats/test1/'\ncount = 0\n\ndef processImg(img):\n    img = img.flatten()\n    return img/255\n\nplt.figure(figsize=(10,10))\nfor filename in os.listdir(path):\n    count += 1\n    img = cv2.imread(os.path.join(path, filename))\n    img = (cv2.resize(img, (150, 110)))\n    plt.subplot(3,3,count)\n    plt.imshow(img)\n    if count == 9:\n        break","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(f'Accuracy score: {accuracy_score(y_pred,y_test)}%')","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"![Thankyou](https://c.tenor.com/PQc4WMULi28AAAAC/slothilda-sloth.gif)","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}