{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","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":30588,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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-11-26T00:13:25.315745Z","iopub.execute_input":"2023-11-26T00:13:25.316105Z","iopub.status.idle":"2023-11-26T00:13:25.330672Z","shell.execute_reply.started":"2023-11-26T00:13:25.316075Z","shell.execute_reply":"2023-11-26T00:13:25.329856Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls /kaggle/input/dogs-vs-cats","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:13:32.334909Z","iopub.execute_input":"2023-11-26T00:13:32.335246Z","iopub.status.idle":"2023-11-26T00:13:32.651032Z","shell.execute_reply.started":"2023-11-26T00:13:32.335218Z","shell.execute_reply":"2023-11-26T00:13:32.650231Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os, cv2, re, random\nimport numpy as np\nimport pandas as pd\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing.image import img_to_array, load_img\nfrom keras import layers, models, optimizers\nfrom keras import backend as K\nfrom sklearn.model_selection import train_test_split","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:25:31.720150Z","iopub.execute_input":"2023-11-26T00:25:31.720843Z","iopub.status.idle":"2023-11-26T00:25:43.675032Z","shell.execute_reply.started":"2023-11-26T00:25:31.720812Z","shell.execute_reply":"2023-11-26T00:25:43.674028Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!unzip ../input/dogs-vs-cats/train.zip\n!ls train/","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:25:53.162549Z","iopub.execute_input":"2023-11-26T00:25:53.163656Z","iopub.status.idle":"2023-11-26T00:26:04.582596Z","shell.execute_reply.started":"2023-11-26T00:25:53.163620Z","shell.execute_reply":"2023-11-26T00:26:04.581596Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!unzip ../input/dogs-vs-cats/test1.zip\n!ls test1/","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:26:04.584553Z","iopub.execute_input":"2023-11-26T00:26:04.584867Z","iopub.status.idle":"2023-11-26T00:26:11.137623Z","shell.execute_reply.started":"2023-11-26T00:26:04.584836Z","shell.execute_reply":"2023-11-26T00:26:11.136474Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_width = 150\nimg_height = 150\nTRAIN_DIR = 'train/'\nTEST_DIR = 'test1/'\ntrain_images_dogs_cats = [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR)] # use this for full dataset\ntest_images_dogs_cats = [TEST_DIR+i for i in os.listdir(TEST_DIR)]\n\n","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:28:36.425055Z","iopub.execute_input":"2023-11-26T00:28:36.426051Z","iopub.status.idle":"2023-11-26T00:28:36.458298Z","shell.execute_reply.started":"2023-11-26T00:28:36.426003Z","shell.execute_reply":"2023-11-26T00:28:36.457593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def atoi(text):\n    return int(text) if text.isdigit() else text\n\ndef natural_keys(text):\n    return [ atoi(c) for c in re.split('(\\d+)', text) ]","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:28:37.297424Z","iopub.execute_input":"2023-11-26T00:28:37.297771Z","iopub.status.idle":"2023-11-26T00:28:37.303117Z","shell.execute_reply.started":"2023-11-26T00:28:37.297741Z","shell.execute_reply":"2023-11-26T00:28:37.302059Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_images_dogs_cats.sort(key=natural_keys)\ntrain_images_dogs_cats = train_images_dogs_cats[0:1300] + train_images_dogs_cats[12500:13800] \n\ntest_images_dogs_cats.sort(key=natural_keys)","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:28:40.125235Z","iopub.execute_input":"2023-11-26T00:28:40.125606Z","iopub.status.idle":"2023-11-26T00:28:40.325694Z","shell.execute_reply.started":"2023-11-26T00:28:40.125577Z","shell.execute_reply":"2023-11-26T00:28:40.324730Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def prepare_data(list_of_images):\n    \"\"\"\n    Returns two arrays: \n        x is an array of resized images\n        y is an array of labels\n    \"\"\"\n    x = [] # images as arrays\n    y = [] # labels\n    \n    for image in list_of_images:\n        x.append(cv2.resize(cv2.imread(image), (img_width,img_height), interpolation=cv2.INTER_CUBIC))\n    \n    for i in list_of_images:\n        if 'dog' in i:\n            y.append(1)\n        elif 'cat' in i:\n            y.append(0)\n        #else:\n            #print('neither cat nor dog name present in images')\n            \n    return x, y","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:28:40.543202Z","iopub.execute_input":"2023-11-26T00:28:40.543882Z","iopub.status.idle":"2023-11-26T00:28:40.550132Z","shell.execute_reply.started":"2023-11-26T00:28:40.543847Z","shell.execute_reply":"2023-11-26T00:28:40.549187Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X, Y = prepare_data(train_images_dogs_cats)\nprint(K.image_data_format())","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:28:42.072670Z","iopub.execute_input":"2023-11-26T00:28:42.073369Z","iopub.status.idle":"2023-11-26T00:28:47.453665Z","shell.execute_reply.started":"2023-11-26T00:28:42.073335Z","shell.execute_reply":"2023-11-26T00:28:47.452781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# First split the data in two sets, 80% for training, 20% for Val/Test)\nX_train, X_val, Y_train, Y_val = train_test_split(X,Y, test_size=0.2, random_state=1)","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:28:47.455387Z","iopub.execute_input":"2023-11-26T00:28:47.455677Z","iopub.status.idle":"2023-11-26T00:28:47.463810Z","shell.execute_reply.started":"2023-11-26T00:28:47.455650Z","shell.execute_reply":"2023-11-26T00:28:47.462878Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"nb_train_samples = len(X_train)\nnb_validation_samples = len(X_val)\nbatch_size = 16","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:28:47.465028Z","iopub.execute_input":"2023-11-26T00:28:47.465653Z","iopub.status.idle":"2023-11-26T00:28:47.474710Z","shell.execute_reply.started":"2023-11-26T00:28:47.465617Z","shell.execute_reply":"2023-11-26T00:28:47.473937Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = models.Sequential()\n\nmodel.add(layers.Conv2D(32, (3, 3), input_shape=(img_width, img_height, 3)))\nmodel.add(layers.Activation('relu'))\nmodel.add(layers.MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(layers.Conv2D(32, (3, 3)))\nmodel.add(layers.Activation('relu'))\nmodel.add(layers.MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(layers.Conv2D(64, (3, 3)))\nmodel.add(layers.Activation('relu'))\nmodel.add(layers.MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(64))\nmodel.add(layers.Activation('relu'))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(1))\nmodel.add(layers.Activation('sigmoid'))\n\nmodel.compile(loss='binary_crossentropy',\n              optimizer='rmsprop',\n              metrics=['accuracy'])\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:28:56.185329Z","iopub.execute_input":"2023-11-26T00:28:56.186075Z","iopub.status.idle":"2023-11-26T00:28:59.079331Z","shell.execute_reply.started":"2023-11-26T00:28:56.186042Z","shell.execute_reply":"2023-11-26T00:28:59.078439Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rescale=1. / 255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True)\n\nval_datagen = ImageDataGenerator(\n    rescale=1. / 255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True)","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:29:06.668747Z","iopub.execute_input":"2023-11-26T00:29:06.669083Z","iopub.status.idle":"2023-11-26T00:29:06.674447Z","shell.execute_reply.started":"2023-11-26T00:29:06.669058Z","shell.execute_reply":"2023-11-26T00:29:06.673499Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = train_datagen.flow(np.array(X_train), Y_train, batch_size=batch_size)\nvalidation_generator = val_datagen.flow(np.array(X_val), Y_val, batch_size=batch_size)","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:29:18.291176Z","iopub.execute_input":"2023-11-26T00:29:18.291531Z","iopub.status.idle":"2023-11-26T00:29:18.524559Z","shell.execute_reply.started":"2023-11-26T00:29:18.291505Z","shell.execute_reply":"2023-11-26T00:29:18.523740Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit_generator(\n    train_generator, \n    steps_per_epoch=nb_train_samples // batch_size,\n    epochs=30,\n    validation_data=validation_generator,\n    validation_steps=nb_validation_samples // batch_size\n)","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:29:25.542263Z","iopub.execute_input":"2023-11-26T00:29:25.542624Z","iopub.status.idle":"2023-11-26T00:36:51.676145Z","shell.execute_reply.started":"2023-11-26T00:29:25.542596Z","shell.execute_reply":"2023-11-26T00:36:51.675219Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save_weights('model_wieghts.h5')\nmodel.save('model_keras.h5')","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:36:51.678530Z","iopub.execute_input":"2023-11-26T00:36:51.679006Z","iopub.status.idle":"2023-11-26T00:36:51.746431Z","shell.execute_reply.started":"2023-11-26T00:36:51.678967Z","shell.execute_reply":"2023-11-26T00:36:51.745403Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_test, Y_test = prepare_data(test_images_dogs_cats) #Y_test in this case will be []","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:36:51.747557Z","iopub.execute_input":"2023-11-26T00:36:51.747819Z","iopub.status.idle":"2023-11-26T00:37:17.635351Z","shell.execute_reply.started":"2023-11-26T00:36:51.747796Z","shell.execute_reply":"2023-11-26T00:37:17.634514Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale=1. / 255)","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:37:17.637232Z","iopub.execute_input":"2023-11-26T00:37:17.637523Z","iopub.status.idle":"2023-11-26T00:37:17.642137Z","shell.execute_reply.started":"2023-11-26T00:37:17.637498Z","shell.execute_reply":"2023-11-26T00:37:17.641236Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_generator = val_datagen.flow(np.array(X_test), batch_size=batch_size)\nprediction_probabilities = model.predict_generator(test_generator, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:37:17.643266Z","iopub.execute_input":"2023-11-26T00:37:17.643531Z","iopub.status.idle":"2023-11-26T00:38:28.357924Z","shell.execute_reply.started":"2023-11-26T00:37:17.643507Z","shell.execute_reply":"2023-11-26T00:38:28.356931Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"counter = range(1, len(test_images_dogs_cats) + 1)\nsolution = pd.DataFrame({\"id\": counter, \"label\":list(prediction_probabilities)})\ncols = ['label']\n\nfor col in cols:\n    solution[col] = solution[col].map(lambda x: str(x).lstrip('[').rstrip(']')).astype(float)\n\nsolution.to_csv(\"dogsVScats.csv\", index = False)","metadata":{"execution":{"iopub.status.busy":"2023-11-26T00:38:28.359230Z","iopub.execute_input":"2023-11-26T00:38:28.359539Z","iopub.status.idle":"2023-11-26T00:38:29.408268Z","shell.execute_reply.started":"2023-11-26T00:38:28.359513Z","shell.execute_reply":"2023-11-26T00:38:29.407474Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}