{"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":"2022-06-05T10:35:00.330162Z","iopub.execute_input":"2022-06-05T10:35:00.330958Z","iopub.status.idle":"2022-06-05T10:35:00.356123Z","shell.execute_reply.started":"2022-06-05T10:35:00.330869Z","shell.execute_reply":"2022-06-05T10:35:00.355233Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install mplcyberpunk\nimport numpy as np \nimport pandas as pd\nimport cv2\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom keras.layers import Dense, Flatten, Dropout, Activation, Conv2D, MaxPooling2D, BatchNormalization\nfrom zipfile import ZipFile\nimport pathlib, os, random, mplcyberpunk\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"execution":{"iopub.status.busy":"2022-06-05T10:58:19.394372Z","iopub.execute_input":"2022-06-05T10:58:19.395225Z","iopub.status.idle":"2022-06-05T10:58:34.873638Z","shell.execute_reply.started":"2022-06-05T10:58:19.395184Z","shell.execute_reply":"2022-06-05T10:58:34.872608Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with ZipFile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip') as zf:\n    zf.extractall('.')\n    \nwith ZipFile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip') as zf:\n    zf.extractall('.')","metadata":{"execution":{"iopub.status.busy":"2022-06-05T10:58:40.697438Z","iopub.execute_input":"2022-06-05T10:58:40.698382Z","iopub.status.idle":"2022-06-05T10:59:02.999821Z","shell.execute_reply.started":"2022-06-05T10:58:40.69834Z","shell.execute_reply":"2022-06-05T10:59:02.998851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X, y = [], []\n\nmain_dir = \"/kaggle/working/\"\ntrain_dir = \"train\"\npath=os.path.join(main_dir,train_dir)\nfor i in os.listdir(path):\n    classes = i.split('.')[0]\n#     print(classes)\n#     break\n    img = cv2.imread(os.path.join(path, i), 0)\n    img = cv2.resize(img, dsize=(100, 100))\n    X.append(img)\n    y.append(classes)","metadata":{"execution":{"iopub.status.busy":"2022-06-05T10:59:09.061796Z","iopub.execute_input":"2022-06-05T10:59:09.062781Z","iopub.status.idle":"2022-06-05T10:59:32.25423Z","shell.execute_reply.started":"2022-06-05T10:59:09.062737Z","shell.execute_reply":"2022-06-05T10:59:32.253308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataInfo = pd.DataFrame(y)\ndataInfo.columns = ['Target']\ndictForClasses = {'cat': 0, 'dog': 1}\nfor i in range(25000):\n    dataInfo.iloc[i, 0] = dictForClasses[dataInfo.iloc[i, 0]]","metadata":{"execution":{"iopub.status.busy":"2022-06-05T10:59:41.527234Z","iopub.execute_input":"2022-06-05T10:59:41.527655Z","iopub.status.idle":"2022-06-05T10:59:44.64316Z","shell.execute_reply.started":"2022-06-05T10:59:41.527621Z","shell.execute_reply":"2022-06-05T10:59:44.642276Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataInfo","metadata":{"execution":{"iopub.status.busy":"2022-06-05T10:59:48.290359Z","iopub.execute_input":"2022-06-05T10:59:48.291213Z","iopub.status.idle":"2022-06-05T10:59:48.325782Z","shell.execute_reply.started":"2022-06-05T10:59:48.29116Z","shell.execute_reply":"2022-06-05T10:59:48.321683Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y = np.asarray(dataInfo.Target).astype('int64')\nX = np.asarray(X).astype('float64')","metadata":{"execution":{"iopub.status.busy":"2022-06-05T11:11:23.482807Z","iopub.execute_input":"2022-06-05T11:11:23.483744Z","iopub.status.idle":"2022-06-05T11:11:25.614181Z","shell.execute_reply.started":"2022-06-05T11:11:23.483705Z","shell.execute_reply":"2022-06-05T11:11:25.613028Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = X.reshape(-1, 100, 100, 1)","metadata":{"execution":{"iopub.status.busy":"2022-06-05T11:11:27.295399Z","iopub.execute_input":"2022-06-05T11:11:27.296075Z","iopub.status.idle":"2022-06-05T11:11:27.301152Z","shell.execute_reply.started":"2022-06-05T11:11:27.29604Z","shell.execute_reply":"2022-06-05T11:11:27.299974Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class BaseModel(tf.keras.Model):\n    def __init__(self):\n        super(BaseModel, self).__init__()\n        self.C1 = Conv2D(32, (3 * 3), input_shape=(100, 100, 1), padding='same')\n        self.B1 = BatchNormalization()\n        self.A1 = Activation('relu')\n        \n        self.C2 = Conv2D(32, (3 * 3), padding='same')\n        self.B2 = BatchNormalization()\n        self.A2 = Activation('relu')\n        self.P1 = MaxPooling2D(2, padding='same')\n        self.Dr1 = Dropout(0.2)\n        \n#         self.C3 = Conv2D(16, (3 * 3))\n#         self.B3 = BatchNormalization()\n#         self.A3 = Activation('relu')\n#         self.P2 = MaxPooling2D(2, padding='same')\n#         self.Dr2 = Dropout(0.3)\n        \n        self.F1 = Flatten()\n        self.B4 = BatchNormalization()\n        self.D1 = Dense(64, activation='relu')\n        self.Dr3 = Dropout(0.2)\n        self.D2 = Dense(64, activation='relu')\n        self.Dr4 = Dropout(0.3)\n        self.D3 = Dense(2, activation='sigmoid')\n        \n    def call(self, x):\n        x = self.C1(x)\n        x = self.B1(x)\n        x = self.A1(x)\n        \n        x = self.C2(x)\n        x = self.B2(x)\n        x = self.A2(x)\n        x = self.P1(x)\n        x = self.Dr1(x)\n        \n#         x = self.C3(x)\n#         x = self.B3(x)\n#         x = self.A3(x)\n#         x = self.P2(x)\n#         x = self.Dr2(x)\n\n        x = self.F1(x)\n        x = self.B4(x)\n        x = self.D1(x)\n#         x = self.Dr3(x)\n        x = self.D2(x)\n        x = self.Dr4(x)\n        y = self.D3(x)\n        return y\n    \nmodel = BaseModel()\n\nmodel.compile(optimizer='adam',\n             loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n             metrics=['accuracy'])\n\n# checkpoint_save_path = './DogsAndCatsModel.ckpt'\n\n# if os.path.exists(checkpoint_save_path + '.index'):\n#     model.load_weights(checkpoint_save_path)\n    \n# cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,\n#                                     save_best_only=True, save_weights_only=True)\n\n# history = model.fit(X, y, epochs=20, batch_size=32,validation_split=0.2, \n#                     callbacks=[cp_callback])\n\nhistory = model.fit(X, y, epochs=30, batch_size=32,validation_split=0.2 )\n\n# file = open('./DogsAndCatsModel.txt', 'w')\n# for v in model.trainable_variables:\n#     file.write(str(v.name) + '\\n')\n#     file.write(str(v.shape) + '\\n')\n#     file.write(str(v.numpy()) + '\\n')\n\n# file.close()\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-06-05T11:11:29.625123Z","iopub.execute_input":"2022-06-05T11:11:29.625532Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc = history.history['accuracy']\nloss = history.history['loss']\n\nplt.figure(figsize=(12, 6))\nplt.style.use('cyberpunk')\nplt.subplot(1, 2, 1)\nplt.plot(acc, label='Training Acc')\nplt.ylim(0.5, 1)\nplt.title('BaseModel Training Acc')\nmplcyberpunk.add_glow_effects()\nplt.legend()\n\nplt.subplot(1, 2, 2)\nplt.plot(loss, label='Training Loss')\nplt.title('BaseModel Training Loss')\nmplcyberpunk.add_glow_effects()\nplt.legend()\n\nplt.show()","metadata":{},"execution_count":null,"outputs":[]}]}