{"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":"markdown","source":"# Convolutional Neural Network","metadata":{"id":"3DR-eO17geWu"}},{"cell_type":"markdown","source":"### Importing the libraries","metadata":{"id":"EMefrVPCg-60"}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd \nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport random\nimport os","metadata":{"id":"sCV30xyVhFbE","execution":{"iopub.status.busy":"2023-08-02T12:52:23.451425Z","iopub.execute_input":"2023-08-02T12:52:23.452072Z","iopub.status.idle":"2023-08-02T12:52:23.922452Z","shell.execute_reply.started":"2023-08-02T12:52:23.452029Z","shell.execute_reply":"2023-08-02T12:52:23.921406Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.__version__\n\n\n!unzip -qq /kaggle/input/dogs-vs-cats/train.zip ","metadata":{"execution":{"iopub.status.busy":"2023-08-02T12:44:31.014848Z","iopub.execute_input":"2023-08-02T12:44:31.015502Z","iopub.status.idle":"2023-08-02T12:44:43.933463Z","shell.execute_reply.started":"2023-08-02T12:44:31.015451Z","shell.execute_reply":"2023-08-02T12:44:43.932023Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Part 1 - Data Preprocessing","metadata":{"id":"oxQxCBWyoGPE"}},{"cell_type":"code","source":"FAST_RUN = False\nIMAGE_WIDTH=128\nIMAGE_HEIGHT=128\nIMAGE_SIZE=(IMAGE_WIDTH, IMAGE_HEIGHT)\nIMAGE_CHANNELS=3","metadata":{"execution":{"iopub.status.busy":"2023-08-02T12:53:02.936132Z","iopub.execute_input":"2023-08-02T12:53:02.937637Z","iopub.status.idle":"2023-08-02T12:53:02.943246Z","shell.execute_reply.started":"2023-08-02T12:53:02.937592Z","shell.execute_reply":"2023-08-02T12:53:02.94189Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Preprocessing the Training set","metadata":{"id":"MvE-heJNo3GG"}},{"cell_type":"code","source":"!ls -l train | head -4\n\nfilenames = os.listdir(\"./train/\")\ncategories = []\nfor filename in filenames:\n    category = filename.split('.')[0]\n    if category == 'dog':\n        categories.append(1)\n    else:\n        categories.append(0)\n\ndf = pd.DataFrame({\n    'filename': filenames,\n    'category': categories\n})\n\ntotal_train = train_df.shape[0]\ntotal_validate = validate_df.shape[0]\nbatch_size=15\n\ntrain_df, validate_df = train_test_split(df, test_size=0.20, random_state=42)\ntrain_df = train_df.reset_index(drop=True)\nvalidate_df = validate_df.reset_index(drop=True)\n\ntrain_datagen = ImageDataGenerator(\n    rotation_range=15,\n    rescale=1./255,\n    shear_range=0.1,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    width_shift_range=0.1,\n    height_shift_range=0.1\n)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    train_df, \n    \"./train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical',\n    batch_size=batch_size\n)","metadata":{"id":"0koUcJMJpEBD","outputId":"f5109ce3-761d-49df-a544-74a5d755a070","execution":{"iopub.status.busy":"2023-08-02T12:53:35.389253Z","iopub.execute_input":"2023-08-02T12:53:35.389698Z","iopub.status.idle":"2023-08-02T12:53:37.645048Z","shell.execute_reply.started":"2023-08-02T12:53:35.389665Z","shell.execute_reply":"2023-08-02T12:53:37.643133Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Preprocessing the Test set","metadata":{"id":"mrCMmGw9pHys"}},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale = 1./255)\ntest_set = test_datagen.flow_from_directory('dataset/test_set',\n                                            target_size = (64, 64),\n                                            batch_size = 32,\n                                            class_mode = 'binary')","metadata":{"id":"SH4WzfOhpKc3"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Part 2 - Building the CNN","metadata":{"id":"af8O4l90gk7B"}},{"cell_type":"markdown","source":"### Initialising the CNN","metadata":{"id":"ces1gXY2lmoX"}},{"cell_type":"code","source":"cnn = tf.keras.models.Sequential()","metadata":{"id":"SAUt4UMPlhLS"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Step 1 - Convolution","metadata":{"id":"u5YJj_XMl5LF"}},{"cell_type":"code","source":"cnn.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu', input_shape=[64, 64, 3]))","metadata":{"id":"XPzPrMckl-hV"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Step 2 - Pooling","metadata":{"id":"tf87FpvxmNOJ"}},{"cell_type":"code","source":"cnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2))","metadata":{"id":"ncpqPl69mOac"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Adding a second convolutional layer","metadata":{"id":"xaTOgD8rm4mU"}},{"cell_type":"code","source":"cnn.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu'))\ncnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2))","metadata":{"id":"i_-FZjn_m8gk"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Step 3 - Flattening","metadata":{"id":"tmiEuvTunKfk"}},{"cell_type":"code","source":"cnn.add(tf.keras.layers.Flatten())","metadata":{"id":"6AZeOGCvnNZn"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Step 4 - Full Connection","metadata":{"id":"dAoSECOm203v"}},{"cell_type":"code","source":"cnn.add(tf.keras.layers.Dense(units=128, activation='relu'))","metadata":{"id":"8GtmUlLd26Nq"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Step 5 - Output Layer","metadata":{"id":"yTldFvbX28Na"}},{"cell_type":"code","source":"cnn.add(tf.keras.layers.Dense(units=1, activation='sigmoid'))","metadata":{"id":"1p_Zj1Mc3Ko_"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Part 3 - Training the CNN","metadata":{"id":"D6XkI90snSDl"}},{"cell_type":"markdown","source":"### Compiling the CNN","metadata":{"id":"vfrFQACEnc6i"}},{"cell_type":"code","source":"cnn.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])","metadata":{"id":"NALksrNQpUlJ"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Training the CNN on the Training set and evaluating it on the Test set","metadata":{"id":"ehS-v3MIpX2h"}},{"cell_type":"code","source":"cnn.fit(x = training_set, validation_data = test_set, epochs = 25)","metadata":{"id":"XUj1W4PJptta"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Part 4 - Making a single prediction","metadata":{"id":"U3PZasO0006Z"}},{"cell_type":"code","source":"import numpy as np\nfrom keras.preprocessing import image\ntest_image = image.load_img('dataset/single_prediction/cat_or_dog_1.jpg', target_size = (64, 64))\ntest_image = image.img_to_array(test_image)\ntest_image = np.expand_dims(test_image, axis = 0)\nresult = cnn.predict(test_image)\ntraining_set.class_indices\nif result[0][0] == 1:\n  prediction = 'dog'\nelse:\n  prediction = 'cat'","metadata":{"id":"gsSiWEJY1BPB"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(prediction)","metadata":{"id":"ED9KB3I54c1i"},"execution_count":null,"outputs":[]}]}