{"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":"none","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30761,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport zipfile\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D\nfrom tensorflow.keras.layers import Activation, Dropout, Flatten, Dense\nfrom tensorflow.keras import backend as K\nimport cv2\n\nimport matplotlib.pyplot as pltt\n\n\nfrom tqdm import tqdm\nfrom random import shuffle","metadata":{"execution":{"iopub.status.busy":"2024-08-22T05:20:57.185832Z","iopub.execute_input":"2024-08-22T05:20:57.186386Z","iopub.status.idle":"2024-08-22T05:21:15.223294Z","shell.execute_reply.started":"2024-08-22T05:20:57.186333Z","shell.execute_reply":"2024-08-22T05:21:15.222166Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nzip_test_path = '/kaggle/input/dogs-vs-cats/test1.zip'\nzip_train_path = '/kaggle/input/dogs-vs-cats/train.zip'\n\n\nwith zipfile.ZipFile(zip_test_path, 'r') as zip_ref:  \n    extract_path = '/kaggle/working/'\n    zip_ref.extractall(extract_path)\n    \nwith zipfile.ZipFile(zip_train_path, 'r') as zip_ref:\n    extract_path = '/kaggle/working/'\n    zip_ref.extractall(extract_path)","metadata":{"execution":{"iopub.status.busy":"2024-08-22T05:22:34.329435Z","iopub.execute_input":"2024-08-22T05:22:34.330558Z","iopub.status.idle":"2024-08-22T05:22:47.503221Z","shell.execute_reply.started":"2024-08-22T05:22:34.330489Z","shell.execute_reply":"2024-08-22T05:22:47.502002Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TRAIN_DIR = '/kaggle/working/train'\nTEST_DIR = '/kaggle/working/test1'\nIMG_SIZE = 128","metadata":{"execution":{"iopub.status.busy":"2024-08-22T05:24:12.902981Z","iopub.execute_input":"2024-08-22T05:24:12.903957Z","iopub.status.idle":"2024-08-22T05:24:12.909346Z","shell.execute_reply.started":"2024-08-22T05:24:12.903905Z","shell.execute_reply":"2024-08-22T05:24:12.907869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_label(image_name):\n    word_label = image_name.split('.')[-3]\n    if word_label == 'cat':\n        return np.array([1,0])\n    elif word_label == 'dog':\n        return np.array([0,1])\n\ndef create_train_data():\n    training_data = []\n    for img in tqdm(os.listdir(TRAIN_DIR)):\n        path = os.path.join(TRAIN_DIR, img)\n        img_data = cv2.imread(path)\n        img_data = cv2.resize(img_data, (IMG_SIZE, IMG_SIZE))\n        training_data.append([np.array(img_data), create_label(img)])\n    shuffle(training_data)\n    return training_data","metadata":{"execution":{"iopub.status.busy":"2024-08-22T05:24:32.322412Z","iopub.execute_input":"2024-08-22T05:24:32.322865Z","iopub.status.idle":"2024-08-22T05:24:32.331773Z","shell.execute_reply.started":"2024-08-22T05:24:32.322822Z","shell.execute_reply":"2024-08-22T05:24:32.330443Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = create_train_data()","metadata":{"execution":{"iopub.status.busy":"2024-08-22T05:24:49.957842Z","iopub.execute_input":"2024-08-22T05:24:49.958294Z","iopub.status.idle":"2024-08-22T05:25:18.224535Z","shell.execute_reply.started":"2024-08-22T05:24:49.958252Z","shell.execute_reply":"2024-08-22T05:25:18.223329Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = train_data[0:-15000] \ntest = train_data[-500:] \n\nX_train = np.array([i[0] for i in train]).reshape(-1, IMG_SIZE, IMG_SIZE, 3)/255\ny_train = np.array([i[1] for i in train])\nX_test = np.array([i[0] for i in test]).reshape(-1, IMG_SIZE, IMG_SIZE, 3)/255\ny_test = np.array([i[1] for i in test])","metadata":{"execution":{"iopub.status.busy":"2024-08-22T05:25:43.124708Z","iopub.execute_input":"2024-08-22T05:25:43.125744Z","iopub.status.idle":"2024-08-22T05:25:45.206745Z","shell.execute_reply.started":"2024-08-22T05:25:43.125698Z","shell.execute_reply":"2024-08-22T05:25:45.205662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_model = tf.keras.applications.MobileNetV2(input_shape=(128, 128, 3), include_top=False, weights='imagenet')\nbase_model.summary()\nbase_model.trainable = False","metadata":{"execution":{"iopub.status.busy":"2024-08-22T05:26:04.727207Z","iopub.execute_input":"2024-08-22T05:26:04.729332Z","iopub.status.idle":"2024-08-22T05:26:08.305687Z","shell.execute_reply.started":"2024-08-22T05:26:04.729250Z","shell.execute_reply":"2024-08-22T05:26:08.304413Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"average_pooling_layer = tf.keras.layers.GlobalAveragePooling2D()(base_model.output)\nprediction_layer = tf.keras.layers.Dense(units=2, activation='sigmoid')(average_pooling_layer)","metadata":{"execution":{"iopub.status.busy":"2024-08-22T05:26:46.789877Z","iopub.execute_input":"2024-08-22T05:26:46.790327Z","iopub.status.idle":"2024-08-22T05:26:46.808267Z","shell.execute_reply.started":"2024-08-22T05:26:46.790287Z","shell.execute_reply":"2024-08-22T05:26:46.806981Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = tf.keras.models.Model(inputs=base_model.input, outputs=prediction_layer)\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-08-22T05:26:58.661139Z","iopub.execute_input":"2024-08-22T05:26:58.661547Z","iopub.status.idle":"2024-08-22T05:26:58.939807Z","shell.execute_reply.started":"2024-08-22T05:26:58.661510Z","shell.execute_reply":"2024-08-22T05:26:58.938439Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.0001), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-08-22T05:27:32.920590Z","iopub.execute_input":"2024-08-22T05:27:32.921094Z","iopub.status.idle":"2024-08-22T05:27:32.933398Z","shell.execute_reply.started":"2024-08-22T05:27:32.921048Z","shell.execute_reply":"2024-08-22T05:27:32.932153Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(X_train, y_train, batch_size=32, epochs=25, validation_data=(X_test, y_test))","metadata":{"execution":{"iopub.status.busy":"2024-08-22T05:28:10.557664Z","iopub.execute_input":"2024-08-22T05:28:10.558813Z","iopub.status.idle":"2024-08-22T06:00:23.772616Z","shell.execute_reply.started":"2024-08-22T05:28:10.558764Z","shell.execute_reply":"2024-08-22T06:00:23.771090Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nplt.figure(figsize=(10,4))\nplt.subplot(121),\nplt.title('model accuracy');plt.ylabel('accuracy');plt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper left')\nplt.plot(history.history['accuracy']);plt.plot(history.history['val_accuracy'])\n\nplt.subplot(122)\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper left')\nplt.plot(history.history['loss']);plt.plot(history.history['val_loss'])","metadata":{"execution":{"iopub.status.busy":"2024-08-22T06:18:29.902028Z","iopub.execute_input":"2024-08-22T06:18:29.902782Z","iopub.status.idle":"2024-08-22T06:18:30.611245Z","shell.execute_reply.started":"2024-08-22T06:18:29.902719Z","shell.execute_reply":"2024-08-22T06:18:30.609898Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nfrom PIL import Image\nimport cv2\n\nwidth, height = 128, 128\n\ndef imageToArray(imageName):\n  image_path = f'/kaggle/working/test1/{imageName}.jpg'\n  image = Image.open(image_path)\n  image = image.resize((width, height))\n\n  image_array = np.asarray(image)\n  image_array = image_array / 255.0 \n  image_array = image_array.reshape(1, width, height, 3)  \n  return image_array\n\nlabel = ['Cat','Dog']\nIMAGES_TO_TEST = ['1','2','3', '4', '5', '6', '7', '8', '9', '10']\n\nfor image in IMAGES_TO_TEST:\n  imageName = image\n  image_array = imageToArray(imageName)\n  preds = model.predict(image_array)\n  preds = label[np.argmax(preds)] \n  actual_single = imageName\n  print(f'file name: {actual_single}.jpg')\n  print(f'predict: {preds}')\n  image_path = f'/kaggle/working/test1/{imageName}.jpg'\n  img = cv2.imread(image_path)\n  img = cv2.resize(img, (width, height))\n  plt.imshow(img)\n  plt.show()\n  print('-'*100)","metadata":{"execution":{"iopub.status.busy":"2024-08-22T06:20:14.524983Z","iopub.execute_input":"2024-08-22T06:20:14.525522Z","iopub.status.idle":"2024-08-22T06:20:21.204801Z","shell.execute_reply.started":"2024-08-22T06:20:14.525472Z","shell.execute_reply":"2024-08-22T06:20:21.203397Z"},"trusted":true},"execution_count":null,"outputs":[]}]}