{"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":"import numpy as np \nimport pandas as pd \nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.utils import img_to_array, load_img\nimport os\nimport glob \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-09-17T10:18:32.876743Z","iopub.execute_input":"2023-09-17T10:18:32.877105Z","iopub.status.idle":"2023-09-17T10:18:40.507239Z","shell.execute_reply.started":"2023-09-17T10:18:32.877070Z","shell.execute_reply":"2023-09-17T10:18:40.506172Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_path = \"../input/dogs-vs-cats/test1.zip\"\ntest_path = \"../input/dogs-vs-cats/train.zip\"\n\nfiles = \"/kaggle/working/\"\n\nimport zipfile\n\nwith zipfile.ZipFile(train_path, 'r') as zipp:\n    zipp.extractall(files)\n    \nwith zipfile.ZipFile(test_path, 'r') as zipp:\n    zipp.extractall(files)","metadata":{"execution":{"iopub.status.busy":"2023-09-17T10:18:40.509357Z","iopub.execute_input":"2023-09-17T10:18:40.510254Z","iopub.status.idle":"2023-09-17T10:18:55.032694Z","shell.execute_reply.started":"2023-09-17T10:18:40.510218Z","shell.execute_reply":"2023-09-17T10:18:55.031754Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image = []\nlabel = []\nbase_dir = '/kaggle/working'\ntrain_path_content = os.listdir(f'{base_dir}/train')\nprint(f'train_size: {len(train_path_content)}')\ntrain_dir = os.path.join(base_dir, 'train')\n\ntrain_imgs = glob.glob(os.path.join(train_dir, \"*\"))\nfor img in train_imgs:\n    image_name = os.path.splitext(os.path.basename(img))[0]\n    if 'cat' in image_name:\n    # move it to directory /content/train/cats\n        image.append(img)\n        label.append('cat')\n    elif 'dog' in image_name:\n    # move it to directory /content/train/dogs\n        image.append(img)\n        label.append('dog')\ndf = pd.DataFrame({'path':image,'label':label})     ","metadata":{"execution":{"iopub.status.busy":"2023-09-17T10:18:55.034185Z","iopub.execute_input":"2023-09-17T10:18:55.034888Z","iopub.status.idle":"2023-09-17T10:18:55.287155Z","shell.execute_reply.started":"2023-09-17T10:18:55.034853Z","shell.execute_reply":"2023-09-17T10:18:55.286266Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df","metadata":{"execution":{"iopub.status.busy":"2023-09-17T10:18:55.289951Z","iopub.execute_input":"2023-09-17T10:18:55.290381Z","iopub.status.idle":"2023-09-17T10:18:55.314478Z","shell.execute_reply.started":"2023-09-17T10:18:55.290349Z","shell.execute_reply":"2023-09-17T10:18:55.313624Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ninput_shape = (150, 150)\n\n# Define the data generator\ndatagen = ImageDataGenerator(rescale=1./255,\n                            rotation_range=40,\n                            width_shift_range=0.2,\n                            height_shift_range=0.2,\n                            shear_range=0.2,\n                            zoom_range=0.2,\n                            horizontal_flip=True,\n                            fill_mode='nearest',\n                            validation_split=0.2)\n\n\ntrain_generator = datagen.flow_from_dataframe(dataframe=df,\n                                              x_col='path',\n                                              y_col='label',\n                                              subset='training',\n                                              target_size=input_shape,\n                                              batch_size=16,\n                                              class_mode='binary')\n\nval_generator = datagen.flow_from_dataframe(dataframe=df,\n                                            x_col='path',\n                                            y_col='label',\n                                            subset='validation',\n                                            target_size=input_shape,\n                                            batch_size=16,\n                                            class_mode='binary')","metadata":{"execution":{"iopub.status.busy":"2023-09-17T10:19:10.205531Z","iopub.execute_input":"2023-09-17T10:19:10.205900Z","iopub.status.idle":"2023-09-17T10:19:10.710251Z","shell.execute_reply.started":"2023-09-17T10:19:10.205871Z","shell.execute_reply":"2023-09-17T10:19:10.709355Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_model():\n\n    model = tf.keras.models.Sequential([\n    tf.keras.layers.Conv2D(32, (3, 3), input_shape=(150, 150, 3)),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Activation('LeakyReLU'),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    tf.keras.layers.Conv2D(64, (3, 3)),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Activation('LeakyReLU'),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    tf.keras.layers.Conv2D(128, (3, 3)),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Activation('LeakyReLU'),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    tf.keras.layers.Conv2D(128, (3, 3)),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Activation('LeakyReLU'),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    tf.keras.layers.Conv2D(128, (3, 3)),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Activation('LeakyReLU'),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(512, activation='LeakyReLU'),\n    tf.keras.layers.Dropout(0.5),\n    tf.keras.layers.Dense(1, activation='sigmoid')\n  ])\n\n\n    model.compile(optimizer = RMSprop(learning_rate=0.0001),\n                loss = 'binary_crossentropy',\n                metrics = ['accuracy'])\n\n  \n    return model","metadata":{"execution":{"iopub.status.busy":"2023-09-17T10:19:16.112044Z","iopub.execute_input":"2023-09-17T10:19:16.112409Z","iopub.status.idle":"2023-09-17T10:19:16.124411Z","shell.execute_reply.started":"2023-09-17T10:19:16.112379Z","shell.execute_reply":"2023-09-17T10:19:16.123391Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = create_model()\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-09-17T10:19:25.610642Z","iopub.execute_input":"2023-09-17T10:19:25.611247Z","iopub.status.idle":"2023-09-17T10:19:28.795203Z","shell.execute_reply.started":"2023-09-17T10:19:25.611205Z","shell.execute_reply":"2023-09-17T10:19:28.794473Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(train_generator,\n                    epochs=50,\n                    validation_data=val_generator)","metadata":{"execution":{"iopub.status.busy":"2023-09-17T10:19:32.498379Z","iopub.execute_input":"2023-09-17T10:19:32.499305Z","iopub.status.idle":"2023-09-17T13:00:26.210079Z","shell.execute_reply.started":"2023-09-17T10:19:32.499268Z","shell.execute_reply":"2023-09-17T13:00:26.209074Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":" test_filenames = os.listdir(\"/kaggle/working/test1\")\ntest_df = pd.DataFrame({\n    'filename': test_filenames\n})\nnb_samples = test_df.shape[0]\n\ntest_gen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_gen.flow_from_dataframe(\n    test_df, \n    \"./test1/\", \n    x_col='filename',\n    y_col=None,\n    class_mode=None,\n    target_size=(150,150),\n    batch_size=16,\n    shuffle=False\n)","metadata":{"execution":{"iopub.status.busy":"2023-09-17T13:00:26.352671Z","iopub.execute_input":"2023-09-17T13:00:26.353232Z","iopub.status.idle":"2023-09-17T13:00:26.491102Z","shell.execute_reply.started":"2023-09-17T13:00:26.353195Z","shell.execute_reply":"2023-09-17T13:00:26.490235Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predict = model.predict(test_generator)","metadata":{"execution":{"iopub.status.busy":"2023-09-17T13:00:47.199881Z","iopub.execute_input":"2023-09-17T13:00:47.202182Z","iopub.status.idle":"2023-09-17T13:01:07.358749Z","shell.execute_reply.started":"2023-09-17T13:00:47.202148Z","shell.execute_reply":"2023-09-17T13:01:07.357751Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc=history.history['accuracy']\nval_acc=history.history['val_accuracy']\nloss=history.history['loss']\nval_loss=history.history['val_loss']\n\nepochs=range(len(acc)) # Get number of epochs\n\n\nplt.plot(epochs, acc, 'r', \"Training Accuracy\")\nplt.plot(epochs, val_acc, 'b', \"Validation Accuracy\")\nplt.title('Training and validation accuracy')\nplt.show()\nprint(\"\")\n\nplt.plot(epochs, loss, 'r', \"Training Loss\")\nplt.plot(epochs, val_loss, 'b', \"Validation Loss\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-17T13:03:23.470627Z","iopub.execute_input":"2023-09-17T13:03:23.471563Z","iopub.status.idle":"2023-09-17T13:03:23.958392Z","shell.execute_reply.started":"2023-09-17T13:03:23.471531Z","shell.execute_reply":"2023-09-17T13:03:23.957441Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df['category'] = np.argmax(predict, axis=-1)\nlabel_map = dict((category,filename) for filename,category in train_generator.class_indices.items())\ntest_df['category'] = test_df['category'].replace(label_map)\ntest_df['category'] = test_df['category'].replace({ 'dog': 1, 'cat': 0 })","metadata":{"execution":{"iopub.status.busy":"2023-09-17T13:01:07.402652Z","iopub.execute_input":"2023-09-17T13:01:07.402969Z","iopub.status.idle":"2023-09-17T13:01:07.421455Z","shell.execute_reply.started":"2023-09-17T13:01:07.402945Z","shell.execute_reply":"2023-09-17T13:01:07.420636Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df.to_csv('submission.csv')","metadata":{"execution":{"iopub.status.busy":"2023-09-17T13:03:30.109536Z","iopub.execute_input":"2023-09-17T13:03:30.109910Z","iopub.status.idle":"2023-09-17T13:03:30.153738Z","shell.execute_reply.started":"2023-09-17T13:03:30.109879Z","shell.execute_reply":"2023-09-17T13:03:30.152816Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}