{"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":"gpu","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30787,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Binary classification using CNN","metadata":{}},{"cell_type":"markdown","source":"## Package imports ","metadata":{}},{"cell_type":"code","source":"import os\nimport cv2\nimport sys  \nimport random\nimport zipfile\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport tensorflow as tf\nfrom pathlib import Path\nfrom datetime import datetime\nfrom matplotlib import pyplot as plt","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:13:51.670102Z","iopub.execute_input":"2024-12-01T18:13:51.670670Z","iopub.status.idle":"2024-12-01T18:14:02.994965Z","shell.execute_reply.started":"2024-12-01T18:13:51.670635Z","shell.execute_reply":"2024-12-01T18:14:02.994238Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# DL \nimport keras\nimport keras.api\nimport tensorboard\nfrom keras import Model\nfrom keras.api.layers import Conv2D\nfrom keras.api.layers import MaxPool2D\nfrom keras.api.layers import Flatten\nfrom keras.api.layers import Dense\nfrom keras.api.layers import Dropout","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:02.996396Z","iopub.execute_input":"2024-12-01T18:14:02.996900Z","iopub.status.idle":"2024-12-01T18:14:03.010830Z","shell.execute_reply.started":"2024-12-01T18:14:02.996871Z","shell.execute_reply":"2024-12-01T18:14:03.009843Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Verify if GPU Available \ntf.test.is_gpu_available()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:03.011741Z","iopub.execute_input":"2024-12-01T18:14:03.012060Z","iopub.status.idle":"2024-12-01T18:14:03.319249Z","shell.execute_reply.started":"2024-12-01T18:14:03.012034Z","shell.execute_reply":"2024-12-01T18:14:03.318294Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:03.321151Z","iopub.execute_input":"2024-12-01T18:14:03.321432Z","iopub.status.idle":"2024-12-01T18:14:03.905177Z","shell.execute_reply.started":"2024-12-01T18:14:03.321406Z","shell.execute_reply":"2024-12-01T18:14:03.904221Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Paths verification ","metadata":{}},{"cell_type":"code","source":"for dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:03.906490Z","iopub.execute_input":"2024-12-01T18:14:03.907122Z","iopub.status.idle":"2024-12-01T18:14:03.914317Z","shell.execute_reply.started":"2024-12-01T18:14:03.907083Z","shell.execute_reply":"2024-12-01T18:14:03.913457Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Useful methods ","metadata":{}},{"cell_type":"code","source":"def unzipFiles(pathRootFolder:str, output:str) -> int:\n    '''\n        Method to uncompress the zip files in a specifc folder \n\n        Parameters \n        ----------\n            pathRootFolder : str, Absoulte path to the folder that contain the zip files \n            output : str, Path to the folder to uncompress the files \n\n        Return\n        -------\n            int \n                1 if everything is fine \n                0 if it was not possible to uncompress the files \n    '''\n    path2work = str(Path(pathRootFolder).resolve())\n    path2out = str(Path(output).resolve())\n    listSourceFiles = [os.path.join(path2work, fileName) for fileName in os.listdir(path2work) if 'zip' in fileName]\n    if len(listSourceFiles) <= 0:\n        return 0\n    if not os.path.exists(output):\n        try: \n            os.mkdir(output)\n        except:\n            return 0 \n    for currentZipFile in listSourceFiles:\n        with zipfile.ZipFile(currentZipFile, 'r') as objFile:\n            objFile.extractall(path2out)\n    return 1","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:03.915280Z","iopub.execute_input":"2024-12-01T18:14:03.915566Z","iopub.status.idle":"2024-12-01T18:14:03.923400Z","shell.execute_reply.started":"2024-12-01T18:14:03.915540Z","shell.execute_reply":"2024-12-01T18:14:03.922742Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def splitTrainTestFromFolder(path2folder:str, ptest:float=0.20):\n    '''\n        Obtain a list of file-paths for train and test sets \n\n        Parameters\n        -----------\n\n            path2folder : str, Path to the folder that contain the dataset cat-dogs \n            ptest : float, Percentage of the dataset to set in the test\n\n        Returns\n        --------\n\n            list, list, list, list\n                X_train, X_test, y_train, y_test  \n\n        NOTE\n        ----\n            Label 0 represents Dogs \n            Label 1 represents Cats \n    '''\n    path2work = str(Path(path2folder).resolve())\n    listOfFiles = [os.path.join(path2folder, fileName) for fileName in os.listdir(path2work)]\n    random.shuffle(listOfFiles)\n    getLabel = lambda text: 0 if 'dog' in os.path.split(text)[-1] else 1\n    listOfLabels = [getLabel(cFile) for cFile in listOfFiles]\n    X_train, X_test, y_train, y_test = train_test_split(listOfFiles, \n                     listOfLabels,\n                     test_size=ptest,\n                     stratify=listOfLabels)\n    return X_train, X_test, y_train, y_test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:03.924171Z","iopub.execute_input":"2024-12-01T18:14:03.924375Z","iopub.status.idle":"2024-12-01T18:14:03.934473Z","shell.execute_reply.started":"2024-12-01T18:14:03.924354Z","shell.execute_reply":"2024-12-01T18:14:03.933702Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def datasetLoaderFromLists(listXpaths:list, listYlabels:list, batchLen:int=5, imSz:tuple = (32, 32), channels:int=3):\n    '''\n        Create a datagenerator for the dataset \n\n        Parameters \n        -----------\n            listXpaths : list, List of List, each sub-list contain the path to each file of the dataset \n            listYlabels : list, List with the labels related to each file \n            batchLen : int, Length of the batch. Default: 5\n            imSz : tuple, New size of the images (width, height)\n            channels : int, Number image channels, Default: 3\n    '''\n    lck = True \n    cntr = 0\n    batchCntr = 0\n    batchX = []\n    batchY = []\n    while(lck):\n        cFilePath = listXpaths[cntr]\n        cLabel = listYlabels[cntr]\n        try:\n            cImage = cv2.imread(cFilePath, \n                                cv2.COLOR_BGR2RGB)\n        except:\n            cImage = cv2.imread(cFilePath.decode('utf-8'), \n                                cv2.COLOR_BGR2RGB)\n        imgrsz = cv2.resize(cImage,\n                            imSz)\n        img2ret = np.asarray(imgrsz)/255.0\n        batchX.append(img2ret)\n        batchY.append(cLabel)\n        batchCntr += 1\n        if batchCntr >= batchLen:\n            tmp2batchX = np.array(batchX).reshape(batchLen, imSz[0], imSz[1], channels) \n            tmp2batchY = np.array(batchY).reshape(batchLen,)\n            batchY = []\n            batchX = []\n            batchCntr = 0\n            yield tmp2batchX, tmp2batchY\n        cntr += 1\n        if cntr >= len(listXpaths):\n            cntr = 0","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:03.935430Z","iopub.execute_input":"2024-12-01T18:14:03.935660Z","iopub.status.idle":"2024-12-01T18:14:03.949151Z","shell.execute_reply.started":"2024-12-01T18:14:03.935637Z","shell.execute_reply":"2024-12-01T18:14:03.948422Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class SimpleCNN(Model):\n\n    def __init__(self, inputs=(128, 128, 3), name=None):\n        super().__init__(name=name)\n        self.cInput = keras.Input(shape=inputs)\n        self._inputs = inputs\n        self.conv2d_block_1 = Conv2D(32,\n                                      (3,3),\n                                      activation='relu')\n        self.conv2d_block_2 = Conv2D(64,\n                                     (3,3),\n                                      activation='relu')\n        self.conv2d_block_3 = Conv2D(64,\n                                     (3,3),\n                                      activation='relu')\n        self.dense_block_4 = Dense(64, \n                                   activation='relu')\n        self.dense_block_5 = Dense(1,\n                                   activation='sigmoid')\n        self.maxPool_1 = MaxPool2D((2,2))\n        self.maxPool_2 = MaxPool2D((2,2))\n        self.dropOut = Dropout(0.6)\n        self.flatten = Flatten()\n    \n    def call(self, inputs):\n        x = self.conv2d_block_1(inputs)\n        x = self.maxPool_1(x)\n        x = self.conv2d_block_2(x)\n        x = self.maxPool_2(x)\n        x = self.conv2d_block_3(x)\n        x = self.flatten(x)\n        x = self.dropOut(self.dense_block_4(x))\n        return self.dense_block_5(x)\n\n    def summary_model(self):\n        inputs = keras.Input(shape=self._inputs)\n        outputs = self.call(inputs)\n        model = Model(inputs=inputs,\n              outputs=outputs,\n              name='simpleCNN')\n        model.summary()\n\n    def get_config(self):\n            return {\"name\": self.name}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:27:40.858651Z","iopub.execute_input":"2024-12-01T18:27:40.859009Z","iopub.status.idle":"2024-12-01T18:27:40.867411Z","shell.execute_reply.started":"2024-12-01T18:27:40.858976Z","shell.execute_reply":"2024-12-01T18:27:40.866422Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Unzip data and create the desired TFDatasets","metadata":{"execution":{"iopub.status.busy":"2024-12-01T16:42:36.480210Z","iopub.execute_input":"2024-12-01T16:42:36.481036Z","iopub.status.idle":"2024-12-01T16:42:36.484720Z","shell.execute_reply.started":"2024-12-01T16:42:36.481000Z","shell.execute_reply":"2024-12-01T16:42:36.483716Z"}}},{"cell_type":"code","source":"path2zipFiles = os.path.join('/kaggle', 'input', 'dogs-vs-cats')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:03.950050Z","iopub.execute_input":"2024-12-01T18:14:03.950366Z","iopub.status.idle":"2024-12-01T18:14:03.962659Z","shell.execute_reply.started":"2024-12-01T18:14:03.950330Z","shell.execute_reply":"2024-12-01T18:14:03.961942Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"path2unzipFiles = os.path.join('/kaggle', 'working')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:03.964780Z","iopub.execute_input":"2024-12-01T18:14:03.965068Z","iopub.status.idle":"2024-12-01T18:14:03.972601Z","shell.execute_reply.started":"2024-12-01T18:14:03.965044Z","shell.execute_reply":"2024-12-01T18:14:03.971747Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if unzipFiles(path2zipFiles,\n             path2unzipFiles):\n    print('Files were unzip sucessfully')\nelse:\n    print('There was a problem unzipping the files')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:03.973470Z","iopub.execute_input":"2024-12-01T18:14:03.973714Z","iopub.status.idle":"2024-12-01T18:14:18.941535Z","shell.execute_reply.started":"2024-12-01T18:14:03.973690Z","shell.execute_reply":"2024-12-01T18:14:18.940637Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"path2train = os.path.join(path2unzipFiles, 'train')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:18.942603Z","iopub.execute_input":"2024-12-01T18:14:18.942914Z","iopub.status.idle":"2024-12-01T18:14:18.946697Z","shell.execute_reply.started":"2024-12-01T18:14:18.942886Z","shell.execute_reply":"2024-12-01T18:14:18.945883Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"path2test = os.path.join(path2unzipFiles, 'test1')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:18.948082Z","iopub.execute_input":"2024-12-01T18:14:18.948387Z","iopub.status.idle":"2024-12-01T18:14:18.959001Z","shell.execute_reply.started":"2024-12-01T18:14:18.948352Z","shell.execute_reply":"2024-12-01T18:14:18.958189Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X_train, X_test, y_train, y_test = splitTrainTestFromFolder(path2train,\n                                                           ptest=0.2)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:18.959974Z","iopub.execute_input":"2024-12-01T18:14:18.960197Z","iopub.status.idle":"2024-12-01T18:14:19.054474Z","shell.execute_reply.started":"2024-12-01T18:14:18.960174Z","shell.execute_reply":"2024-12-01T18:14:19.053841Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(f'Train sample: {X_train[0]} - Label sample {y_train[0]}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:19.055293Z","iopub.execute_input":"2024-12-01T18:14:19.055531Z","iopub.status.idle":"2024-12-01T18:14:19.060372Z","shell.execute_reply.started":"2024-12-01T18:14:19.055506Z","shell.execute_reply":"2024-12-01T18:14:19.059533Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"batchSize = 10\nimageNewSize = (32, 32)\nchannels = 3","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:19.061299Z","iopub.execute_input":"2024-12-01T18:14:19.061532Z","iopub.status.idle":"2024-12-01T18:14:19.071249Z","shell.execute_reply.started":"2024-12-01T18:14:19.061509Z","shell.execute_reply":"2024-12-01T18:14:19.070570Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"exampleGen = datasetLoaderFromLists(X_train, \n                                    y_train, \n                                    batchSize, \n                                    channels=channels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:19.072285Z","iopub.execute_input":"2024-12-01T18:14:19.072530Z","iopub.status.idle":"2024-12-01T18:14:19.080949Z","shell.execute_reply.started":"2024-12-01T18:14:19.072506Z","shell.execute_reply":"2024-12-01T18:14:19.080285Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sampleBatch, sampleLabels = next(exampleGen)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:19.081884Z","iopub.execute_input":"2024-12-01T18:14:19.082146Z","iopub.status.idle":"2024-12-01T18:14:19.119277Z","shell.execute_reply.started":"2024-12-01T18:14:19.082123Z","shell.execute_reply":"2024-12-01T18:14:19.118490Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sampleBatch.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:19.120342Z","iopub.execute_input":"2024-12-01T18:14:19.120742Z","iopub.status.idle":"2024-12-01T18:14:19.126563Z","shell.execute_reply.started":"2024-12-01T18:14:19.120703Z","shell.execute_reply":"2024-12-01T18:14:19.125591Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sampleLabels.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:19.127621Z","iopub.execute_input":"2024-12-01T18:14:19.127912Z","iopub.status.idle":"2024-12-01T18:14:19.437298Z","shell.execute_reply.started":"2024-12-01T18:14:19.127877Z","shell.execute_reply":"2024-12-01T18:14:19.436386Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.imshow(sampleBatch[0],\n          cmap='gray')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:14:19.438471Z","iopub.execute_input":"2024-12-01T18:14:19.438859Z","iopub.status.idle":"2024-12-01T18:14:19.643782Z","shell.execute_reply.started":"2024-12-01T18:14:19.438821Z","shell.execute_reply":"2024-12-01T18:14:19.642954Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"trainGen = datasetLoaderFromLists(X_train, \n                                    y_train, \n                                    batchSize, \n                                    channels=channels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:19:16.403767Z","iopub.execute_input":"2024-12-01T18:19:16.404663Z","iopub.status.idle":"2024-12-01T18:19:16.408683Z","shell.execute_reply.started":"2024-12-01T18:19:16.404629Z","shell.execute_reply":"2024-12-01T18:19:16.407702Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"testGen = datasetLoaderFromLists(X_test, \n                                    y_test, \n                                    batchSize, \n                                    channels=channels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:19:31.910766Z","iopub.execute_input":"2024-12-01T18:19:31.911148Z","iopub.status.idle":"2024-12-01T18:19:31.915399Z","shell.execute_reply.started":"2024-12-01T18:19:31.911117Z","shell.execute_reply":"2024-12-01T18:19:31.914508Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"tfDataset = tf.data.Dataset.from_generator(datasetLoaderFromLists, \n                            args=[X_train, y_train, batchSize, imageNewSize],\n                            output_signature = (tf.TensorSpec(shape=[batchSize, imageNewSize[0], imageNewSize[1], 3], dtype=tf.float32),\n                                                tf.TensorSpec(shape=[batchSize,], dtype=tf.int32)))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:20:41.687416Z","iopub.execute_input":"2024-12-01T18:20:41.687761Z","iopub.status.idle":"2024-12-01T18:20:42.126709Z","shell.execute_reply.started":"2024-12-01T18:20:41.687729Z","shell.execute_reply":"2024-12-01T18:20:42.126042Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"tfDatasetTest = tf.data.Dataset.from_generator(datasetLoaderFromLists, \n                            args=[X_test, y_test, batchSize, imageNewSize],\n                            output_signature = (tf.TensorSpec(shape=[batchSize, imageNewSize[0], imageNewSize[1], 3], dtype=tf.float32),\n                                                tf.TensorSpec(shape=[batchSize,], dtype=tf.int32)))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:22:05.734490Z","iopub.execute_input":"2024-12-01T18:22:05.735118Z","iopub.status.idle":"2024-12-01T18:22:05.770969Z","shell.execute_reply.started":"2024-12-01T18:22:05.735083Z","shell.execute_reply":"2024-12-01T18:22:05.770116Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"datasetTrain = tfDataset.map(lambda x, y: (x, y))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:21:48.255056Z","iopub.execute_input":"2024-12-01T18:21:48.255942Z","iopub.status.idle":"2024-12-01T18:21:48.277082Z","shell.execute_reply.started":"2024-12-01T18:21:48.255904Z","shell.execute_reply":"2024-12-01T18:21:48.276276Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"datasetTest = tfDatasetTest.map(lambda x, y: (x, y))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:22:20.557660Z","iopub.execute_input":"2024-12-01T18:22:20.558358Z","iopub.status.idle":"2024-12-01T18:22:20.570574Z","shell.execute_reply.started":"2024-12-01T18:22:20.558323Z","shell.execute_reply":"2024-12-01T18:22:20.569577Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Training the model ","metadata":{}},{"cell_type":"code","source":"path2keepModel = os.path.join('/kaggle', 'working')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:23:27.609988Z","iopub.execute_input":"2024-12-01T18:23:27.610342Z","iopub.status.idle":"2024-12-01T18:23:27.614643Z","shell.execute_reply.started":"2024-12-01T18:23:27.610311Z","shell.execute_reply":"2024-12-01T18:23:27.613753Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"tensorboard_callback = keras.callbacks.TensorBoard(log_dir=path2keepModel)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:23:28.672859Z","iopub.execute_input":"2024-12-01T18:23:28.673646Z","iopub.status.idle":"2024-12-01T18:23:28.677350Z","shell.execute_reply.started":"2024-12-01T18:23:28.673615Z","shell.execute_reply":"2024-12-01T18:23:28.676587Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"epochs = 20\nstepsPerEpoch = 500","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:24:52.271989Z","iopub.execute_input":"2024-12-01T18:24:52.272322Z","iopub.status.idle":"2024-12-01T18:24:52.276514Z","shell.execute_reply.started":"2024-12-01T18:24:52.272296Z","shell.execute_reply":"2024-12-01T18:24:52.275659Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sCNN = SimpleCNN(inputs=(imageNewSize[0], imageNewSize[1],3))  ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:27:49.215287Z","iopub.execute_input":"2024-12-01T18:27:49.216098Z","iopub.status.idle":"2024-12-01T18:27:49.229657Z","shell.execute_reply.started":"2024-12-01T18:27:49.216062Z","shell.execute_reply":"2024-12-01T18:27:49.228787Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sCNN.compile(optimizer='adam',\n            loss='binary_crossentropy', # sparse_categorical_crossentropy\n            metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:28:59.569247Z","iopub.execute_input":"2024-12-01T18:28:59.569972Z","iopub.status.idle":"2024-12-01T18:28:59.588477Z","shell.execute_reply.started":"2024-12-01T18:28:59.569937Z","shell.execute_reply":"2024-12-01T18:28:59.587856Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = sCNN.fit(datasetTrain,\n        epochs=epochs, \n        steps_per_epoch=stepsPerEpoch,\n        batch_size=batchSize,\n        callbacks=[tensorboard_callback])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:29:01.176953Z","iopub.execute_input":"2024-12-01T18:29:01.177306Z","iopub.status.idle":"2024-12-01T18:30:43.979755Z","shell.execute_reply.started":"2024-12-01T18:29:01.177276Z","shell.execute_reply":"2024-12-01T18:30:43.979071Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Model Performance on training ","metadata":{}},{"cell_type":"code","source":"plt.plot(range(len(history.history['accuracy'])), history.history[\"accuracy\"])\nplt.xlabel(\"Epochs\")\nplt.ylabel('Accuracy')\nplt.title('SimpleCNN - Training - Accuracy over the CatsDogs dataset')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:34:33.249592Z","iopub.execute_input":"2024-12-01T18:34:33.250388Z","iopub.status.idle":"2024-12-01T18:34:33.510814Z","shell.execute_reply.started":"2024-12-01T18:34:33.250351Z","shell.execute_reply":"2024-12-01T18:34:33.510026Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.plot(range(len(history.history['loss'])), history.history[\"loss\"])\nplt.xlabel(\"Epochs\")\nplt.ylabel('Loss')\nplt.title('SimpleCNN - Loss - Error over the CatsDogs dataset')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:35:13.380406Z","iopub.execute_input":"2024-12-01T18:35:13.381130Z","iopub.status.idle":"2024-12-01T18:35:13.577469Z","shell.execute_reply.started":"2024-12-01T18:35:13.381095Z","shell.execute_reply":"2024-12-01T18:35:13.576671Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Model on the test set ","metadata":{}},{"cell_type":"code","source":"results = sCNN.evaluate(datasetTest, \n                        batch_size=batchSize,\n                        steps=stepsPerEpoch,\n                        callbacks=[tensorboard_callback])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:37:03.541120Z","iopub.execute_input":"2024-12-01T18:37:03.541726Z","iopub.status.idle":"2024-12-01T18:37:08.410576Z","shell.execute_reply.started":"2024-12-01T18:37:03.541692Z","shell.execute_reply":"2024-12-01T18:37:08.409719Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(f'test loss: {round(results[0],3)}, test acc: {round(results[1],3)}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T18:39:21.146483Z","iopub.execute_input":"2024-12-01T18:39:21.147164Z","iopub.status.idle":"2024-12-01T18:39:21.151711Z","shell.execute_reply.started":"2024-12-01T18:39:21.147131Z","shell.execute_reply":"2024-12-01T18:39:21.150730Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}