{"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\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, Dense, Dropout, Flatten, MaxPooling2D\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport matplotlib.pyplot as plt\n\ngpus = tf.config.list_physical_devices('GPU')\nif gpus:\n    for gpu in gpus:\n        tf.config.experimental.set_memory_growth(gpu, True)\nlogical_gpus = tf.config.list_logical_devices('GPU')\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-06-20T16:00:28.460088Z","iopub.execute_input":"2023-06-20T16:00:28.460513Z","iopub.status.idle":"2023-06-20T16:00:28.471191Z","shell.execute_reply.started":"2023-06-20T16:00:28.460474Z","shell.execute_reply":"2023-06-20T16:00:28.469705Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Unpack the existing archives","metadata":{}},{"cell_type":"code","source":"!unzip -qq /kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip\n!unzip -qq /kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip","metadata":{"execution":{"iopub.status.busy":"2023-06-20T15:43:00.043791Z","iopub.execute_input":"2023-06-20T15:43:00.044610Z","iopub.status.idle":"2023-06-20T15:43:18.766826Z","shell.execute_reply.started":"2023-06-20T15:43:00.044576Z","shell.execute_reply":"2023-06-20T15:43:18.765542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Let's create separate subdirectories, we will need this in the future","metadata":{}},{"cell_type":"code","source":"os.mkdir(\"train/cats\")\nos.mkdir(\"train/dogs\")\nos.mkdir(\"test/test\")\nos.mkdir(\"valid\")\nos.mkdir(\"valid/cats\")\nos.mkdir(\"valid/dogs\")","metadata":{"execution":{"iopub.status.busy":"2023-06-20T15:43:18.768611Z","iopub.execute_input":"2023-06-20T15:43:18.769043Z","iopub.status.idle":"2023-06-20T15:43:18.776274Z","shell.execute_reply.started":"2023-06-20T15:43:18.768999Z","shell.execute_reply":"2023-06-20T15:43:18.775213Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Move the images to the appropriate subdirectories","metadata":{}},{"cell_type":"code","source":"! mv train/dog*.jpg train/dogs\n! mv train/cat*.jpg train/cats\n! mv test/*.jpg test/test","metadata":{"execution":{"iopub.status.busy":"2023-06-20T15:43:18.779845Z","iopub.execute_input":"2023-06-20T15:43:18.780186Z","iopub.status.idle":"2023-06-20T15:43:23.094122Z","shell.execute_reply.started":"2023-06-20T15:43:18.780155Z","shell.execute_reply":"2023-06-20T15:43:23.092688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Let's move random images to the folder with the translation validation","metadata":{}},{"cell_type":"code","source":"import random\nimport shutil\n\ndef move_random_files(A, B, N):\n    files = os.listdir(A)\n    random_files = random.sample(files, N)\n    for file in random_files:\n        file_path = os.path.join(A, file)\n        shutil.move(file_path, B)\n\nmove_random_files(\"train/cats\", \"valid/cats\", 400)\nmove_random_files(\"train/dogs\", \"valid/dogs\", 400)","metadata":{"execution":{"iopub.status.busy":"2023-06-20T16:13:54.421133Z","iopub.execute_input":"2023-06-20T16:13:54.421534Z","iopub.status.idle":"2023-06-20T16:13:54.482259Z","shell.execute_reply.started":"2023-06-20T16:13:54.421506Z","shell.execute_reply":"2023-06-20T16:13:54.481353Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Let's create data generators","metadata":{}},{"cell_type":"code","source":"train_dir = \"train/\"\ntest_dir = \"test/\"\nvalid_dir = \"valid/\"\n\n# the generator for training images includes augmentation so that the input images are never repeated, which contributes to the stability of the model\ntrain_datagen = ImageDataGenerator(rescale = 1./255, \n                                  rotation_range = 20,\n                                  width_shift_range = 0.1,\n                                  height_shift_range = 0.1,\n                                  shear_range = 0.1,\n                                  zoom_range = 0.1,\n                                  horizontal_flip = True,\n                                  fill_mode = \"nearest\")\n\n# The generator for test data does not include augmentation, only normalization is done\ntest_datagen = ImageDataGenerator(rescale = 1./255)\n\n# We indicate the sources of information to the generators\ntrain_generator = train_datagen.flow_from_directory(\n                                                    train_dir,\n                                                    target_size = (128,128),\n                                                    batch_size = 256,\n                                                    class_mode = \"binary\")\n\ntest_generator = test_datagen.flow_from_directory(\n                                                    test_dir,\n                                                    target_size = (128,128),\n                                                    batch_size = 128,\n                                                    class_mode = None,\n                                                    shuffle = False)\n\nvalid_generator = test_datagen.flow_from_directory(\n                                                    valid_dir,\n                                                    target_size = (128,128),\n                                                    batch_size = 128,\n                                                    class_mode = \"binary\",\n                                                    shuffle = False)","metadata":{"execution":{"iopub.status.busy":"2023-06-20T15:55:42.433868Z","iopub.execute_input":"2023-06-20T15:55:42.434250Z","iopub.status.idle":"2023-06-20T15:55:44.062090Z","shell.execute_reply.started":"2023-06-20T15:55:42.434215Z","shell.execute_reply":"2023-06-20T15:55:44.061132Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### let's build a model","metadata":{}},{"cell_type":"code","source":"#  We implement a simple convolutional model\nmodel = Sequential([Conv2D(16, 3, activation = \"relu\", input_shape = (128,128, 3)),\n                    MaxPooling2D(2),\n                    Conv2D(32, 3, activation = \"relu\"),\n                    MaxPooling2D(2),\n                    Conv2D(64, 3, activation = \"relu\"),\n                    MaxPooling2D(2),\n                    Conv2D(128, 3, activation = \"relu\"),\n                    MaxPooling2D(2),\n                    Flatten(),\n                    Dense(512, activation = \"relu\"),\n                    Dropout(0.3),\n                    Dense(1, activation = \"sigmoid\")])\nmodel.compile(loss = \"binary_crossentropy\",\n              optimizer = \"adam\",\n              metrics = [\"accuracy\"])\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-06-20T15:49:01.402139Z","iopub.execute_input":"2023-06-20T15:49:01.402576Z","iopub.status.idle":"2023-06-20T15:49:01.533771Z","shell.execute_reply.started":"2023-06-20T15:49:01.402539Z","shell.execute_reply":"2023-06-20T15:49:01.533020Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Starting the learning process\n# we will study only on 10 * 256 images per epoch\nhistory = model.fit(train_generator, steps_per_epoch = 10, epochs = 15, validation_data = valid_generator, verbose = 0 )","metadata":{"execution":{"iopub.status.busy":"2023-06-20T16:00:50.986629Z","iopub.execute_input":"2023-06-20T16:00:50.986994Z","iopub.status.idle":"2023-06-20T16:02:09.343559Z","shell.execute_reply.started":"2023-06-20T16:00:50.986965Z","shell.execute_reply":"2023-06-20T16:02:09.342575Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_accuracy = history.history['accuracy']\ntrain_loss = history.history['loss']\nval_accuracy = history.history['val_accuracy']\nval_loss = history.history['val_loss']\n\n# accuracy\nplt.figure(figsize=(8, 8))\nplt.subplot(2, 1, 1)\nplt.plot(train_accuracy, label='Training Accuracy')\nplt.plot(val_accuracy, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.ylabel('Accuracy')\nplt.title('Training and Validation Accuracy')\n\n# loss\nplt.subplot(2, 1, 2)\nplt.plot(train_loss, label='Training Loss')\nplt.plot(val_loss, label='Validation Loss')\nplt.legend(loc='lower right')\nplt.ylabel('Loss')\nplt.title('Training and Validation Loss')\nplt.xlabel('epoch')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-06-20T16:02:41.207151Z","iopub.execute_input":"2023-06-20T16:02:41.207553Z","iopub.status.idle":"2023-06-20T16:02:41.693736Z","shell.execute_reply.started":"2023-06-20T16:02:41.207521Z","shell.execute_reply":"2023-06-20T16:02:41.692105Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Saving the model for future use\nmodel.save(\"model_cat_vs_dogs.h5\")","metadata":{"execution":{"iopub.status.busy":"2023-06-20T15:45:25.707601Z","iopub.status.idle":"2023-06-20T15:45:25.708525Z","shell.execute_reply.started":"2023-06-20T15:45:25.708251Z","shell.execute_reply":"2023-06-20T15:45:25.708275Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.models import load_model\nmodel = load_model(\"model_cat_vs_dogs.h5\")","metadata":{"execution":{"iopub.status.busy":"2023-06-20T15:45:25.712872Z","iopub.status.idle":"2023-06-20T15:45:25.715035Z","shell.execute_reply.started":"2023-06-20T15:45:25.714766Z","shell.execute_reply":"2023-06-20T15:45:25.714798Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_list = model.predict(test_generator)\npred_list = np.array(pred_list)\n\nid_list = [ ]\nfor f in os.listdir(test_dir + \"/test\"):\n        _id = int(f.split('.')[0])\n        id_list.append(_id)\n# Creating a DataFrame with the IDs and predictions\nres = pd.DataFrame({\n    'id': id_list,\n    'label': pred_list.flatten()\n})\n\n# Sorting the DataFrame by ID and resetting the index\nres.sort_values(by='id', inplace=True)\nres.reset_index(drop=True, inplace=True)\n\n# Saving the DataFrame to a CSV file\nres.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-06-20T15:45:25.718706Z","iopub.status.idle":"2023-06-20T15:45:25.719359Z","shell.execute_reply.started":"2023-06-20T15:45:25.719125Z","shell.execute_reply":"2023-06-20T15:45:25.719145Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## An example of how our model works","metadata":{}},{"cell_type":"code","source":"import matplotlib.pyplot as plt\ntest_examples = next(test_generator)\nfor img in test_examples:\n    predict = model.predict(np.expand_dims(img, axis = 0), verbose = 0)[0][0]\n    if predict >= 0.5:\n        print(\"It seems like it's a dog! Estimation :\", np.round(predict,2) * 100, \"%\")\n    else:\n        print(\"It seems like it's a cat! Estimation :\", np.round(1 - predict,2) * 100, \"%\")\n    plt.imshow(img)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2023-06-20T15:45:25.720865Z","iopub.status.idle":"2023-06-20T15:45:25.728783Z","shell.execute_reply.started":"2023-06-20T15:45:25.728590Z","shell.execute_reply":"2023-06-20T15:45:25.728611Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}