{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"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","execution":{"iopub.status.busy":"2023-05-15T22:02:56.565894Z","iopub.execute_input":"2023-05-15T22:02:56.566161Z","iopub.status.idle":"2023-05-15T22:02:56.581973Z","shell.execute_reply.started":"2023-05-15T22:02:56.566130Z","shell.execute_reply":"2023-05-15T22:02:56.581113Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D, BatchNormalization\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img\nimport matplotlib.pyplot as plt\n","metadata":{"execution":{"iopub.status.busy":"2023-05-15T22:08:13.607813Z","iopub.execute_input":"2023-05-15T22:08:13.608209Z","iopub.status.idle":"2023-05-15T22:08:13.613657Z","shell.execute_reply.started":"2023-05-15T22:08:13.608178Z","shell.execute_reply":"2023-05-15T22:08:13.612788Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!unzip -q /kaggle/input/dogs-vs-cats/train.zip\n!unzip -q /kaggle/input/dogs-vs-cats/test1.zip","metadata":{"execution":{"iopub.status.busy":"2023-05-15T22:03:05.043174Z","iopub.execute_input":"2023-05-15T22:03:05.043866Z","iopub.status.idle":"2023-05-15T22:03:21.425413Z","shell.execute_reply.started":"2023-05-15T22:03:05.043831Z","shell.execute_reply":"2023-05-15T22:03:21.424100Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfilenames = os.listdir(\"train/\")\ncategories = []\nfor filename in filenames:\n    category = filename.split('.')[0]\n    if category == 'dog':\n        categories.append(\"dog\")\n    else:\n        categories.append(\"cat\")\n\ndf = pd.DataFrame({\n    'filename': filenames,\n    'category': categories\n})\ntrain_df, val_df = train_test_split(df, test_size=0.20, random_state=42)\ntrain_df = train_df.reset_index(drop=True)\nvalidate_df = val_df.reset_index(drop=True)","metadata":{"execution":{"iopub.status.busy":"2023-05-15T22:12:21.938713Z","iopub.execute_input":"2023-05-15T22:12:21.939220Z","iopub.status.idle":"2023-05-15T22:12:21.983190Z","shell.execute_reply.started":"2023-05-15T22:12:21.939182Z","shell.execute_reply":"2023-05-15T22:12:21.982267Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_size = (128, 128)\ntrain_image_generator = ImageDataGenerator(rescale=1./255, horizontal_flip=True)\ntrain_generator = train_image_generator.flow_from_dataframe(\n    train_df, \n    \"train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=image_size,\n    class_mode='categorical',\n    batch_size=16\n)\nval_image_generator = ImageDataGenerator(rescale=1./255)\nval_generator = val_image_generator.flow_from_dataframe(\n    val_df, \n    \"train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=image_size,\n    class_mode='categorical',\n    batch_size=16\n)","metadata":{"execution":{"iopub.status.busy":"2023-05-15T22:12:22.926010Z","iopub.execute_input":"2023-05-15T22:12:22.926358Z","iopub.status.idle":"2023-05-15T22:12:23.213901Z","shell.execute_reply.started":"2023-05-15T22:12:22.926330Z","shell.execute_reply":"2023-05-15T22:12:23.212944Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def build_model():\n    width, height, channels = 128, 128, 3\n    model = Sequential()\n\n    model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(width, height, channels)))\n    model.add(BatchNormalization())\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    model.add(Dropout(0.25))\n\n\n    model.add(Conv2D(64, (3, 3), activation='relu'))\n    model.add(BatchNormalization())\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    model.add(Dropout(0.25))\n\n    model.add(Conv2D(128, (3, 3), activation='relu'))\n    model.add(BatchNormalization())\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    model.add(Dropout(0.25))\n\n    model.add(Flatten())\n    model.add(Dense(512, activation='relu'))\n    model.add(BatchNormalization())\n    model.add(Dropout(0.25))\n    \n    model.add(Dense(2, activation='softmax')) \n\n    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n    return model\ncnn = build_model()","metadata":{"execution":{"iopub.status.busy":"2023-05-15T22:12:41.661799Z","iopub.execute_input":"2023-05-15T22:12:41.662725Z","iopub.status.idle":"2023-05-15T22:12:41.807027Z","shell.execute_reply.started":"2023-05-15T22:12:41.662690Z","shell.execute_reply":"2023-05-15T22:12:41.806010Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = cnn.fit(\n        train_generator, \n        epochs=10,\n        validation_data=val_generator,\n        validation_steps=5000//16,\n        steps_per_epoch=20000//16,)","metadata":{"execution":{"iopub.status.busy":"2023-05-15T22:14:15.034106Z","iopub.execute_input":"2023-05-15T22:14:15.034472Z","iopub.status.idle":"2023-05-15T22:22:51.775378Z","shell.execute_reply.started":"2023-05-15T22:14:15.034444Z","shell.execute_reply":"2023-05-15T22:22:51.774355Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nplt.plot(history.history['accuracy'], color='b', label=\"Training accuracy\")\nplt.plot(history.history['val_accuracy'], color='r',label=\"Validation accuracy\")\nplt.xlim(0, 9)\nplt.ylim(0, 1)\nlegend = plt.legend()\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Accuracy\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-15T22:26:57.926522Z","iopub.execute_input":"2023-05-15T22:26:57.926967Z","iopub.status.idle":"2023-05-15T22:26:58.182564Z","shell.execute_reply.started":"2023-05-15T22:26:57.926934Z","shell.execute_reply":"2023-05-15T22:26:58.181606Z"},"trusted":true},"execution_count":null,"outputs":[]}]}