{"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":"# 1. About CNN","metadata":{}},{"cell_type":"markdown","source":"CNN - Convolutional Neural Networks                    \nCNN is a neural network model that is mainly used to process images or image data and includes a preprocessing task called convolution.","metadata":{}},{"cell_type":"markdown","source":"# 2. About cat & dog dataset","metadata":{}},{"cell_type":"markdown","source":"The dataset provide 25000 cats and dogs images to classify.","metadata":{}},{"cell_type":"code","source":"''' importing library''' \n\nimport numpy as np\nimport sys\nimport tensorflow as tf\nimport os\nimport sys\nimport pandas as pd\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n\n%matplotlib inline\nimport matplotlib.image as img\nimport matplotlib.pyplot as plt","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-05-14T03:58:05.780411Z","iopub.execute_input":"2022-05-14T03:58:05.781403Z","iopub.status.idle":"2022-05-14T03:58:11.794431Z","shell.execute_reply.started":"2022-05-14T03:58:05.781284Z","shell.execute_reply":"2022-05-14T03:58:11.793693Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''setting seed'''\nseed = 0\nnp.random.seed(seed)\ntf.random.set_seed(3)","metadata":{"execution":{"iopub.status.busy":"2022-05-14T03:58:11.795996Z","iopub.execute_input":"2022-05-14T03:58:11.796232Z","iopub.status.idle":"2022-05-14T03:58:11.802260Z","shell.execute_reply.started":"2022-05-14T03:58:11.796198Z","shell.execute_reply":"2022-05-14T03:58:11.801528Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import zipfile\n\nzip_files = ['test1', 'train']\n\nfor zip_file in zip_files:\n    with zipfile.ZipFile(\"../input/dogs-vs-cats/{}.zip\".format(zip_file),\"r\") as z:\n        z.extractall(\".\")\n        print(\"{} unzipped\".format(zip_file))","metadata":{"execution":{"iopub.status.busy":"2022-05-14T03:58:11.803648Z","iopub.execute_input":"2022-05-14T03:58:11.803901Z","iopub.status.idle":"2022-05-14T03:58:28.065257Z","shell.execute_reply.started":"2022-05-14T03:58:11.803866Z","shell.execute_reply":"2022-05-14T03:58:28.064482Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''test1, train Data is in current working folder'''\nprint(os.listdir('../working'))","metadata":{"execution":{"iopub.status.busy":"2022-05-14T03:58:28.067394Z","iopub.execute_input":"2022-05-14T03:58:28.067658Z","iopub.status.idle":"2022-05-14T03:58:28.072842Z","shell.execute_reply.started":"2022-05-14T03:58:28.067621Z","shell.execute_reply":"2022-05-14T03:58:28.072023Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_FOLDER_PATH = \"../working/train\"\nFILE_NAMES = os.listdir(IMAGE_FOLDER_PATH)\nWIDTH = 150\nHEIGHT = 150","metadata":{"execution":{"iopub.status.busy":"2022-05-14T03:58:28.074399Z","iopub.execute_input":"2022-05-14T03:58:28.074937Z","iopub.status.idle":"2022-05-14T03:58:28.096992Z","shell.execute_reply.started":"2022-05-14T03:58:28.074898Z","shell.execute_reply":"2022-05-14T03:58:28.096282Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"FILE_NAMES[0:5]","metadata":{"execution":{"iopub.status.busy":"2022-05-14T03:58:28.098121Z","iopub.execute_input":"2022-05-14T03:58:28.098854Z","iopub.status.idle":"2022-05-14T03:58:28.107633Z","shell.execute_reply.started":"2022-05-14T03:58:28.098817Z","shell.execute_reply":"2022-05-14T03:58:28.106611Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# empty list\ntargets = list()\nfull_paths = list()\ntrain_cats_dir = list()\ntrain_dogs_dir = list()\n\n# finding each file's target\nfor file_name in FILE_NAMES:\n    target = file_name.split(\".\")[0] # target name\n    full_path = os.path.join(IMAGE_FOLDER_PATH, file_name)\n    \n    if(target == \"dog\"):\n        train_dogs_dir.append(full_path)\n    if(target == \"cat\"):\n        train_cats_dir.append(full_path)\n    \n    full_paths.append(full_path)\n    targets.append(target)\n\ndataset = pd.DataFrame() # make dataframe\ndataset['image_path'] = full_paths # file path\ndataset['target'] = targets # file's target\n    ","metadata":{"execution":{"iopub.status.busy":"2022-05-14T03:58:28.109020Z","iopub.execute_input":"2022-05-14T03:58:28.109380Z","iopub.status.idle":"2022-05-14T03:58:28.204041Z","shell.execute_reply.started":"2022-05-14T03:58:28.109341Z","shell.execute_reply":"2022-05-14T03:58:28.203274Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset.head(10)","metadata":{"execution":{"iopub.status.busy":"2022-05-14T03:58:28.205392Z","iopub.execute_input":"2022-05-14T03:58:28.205637Z","iopub.status.idle":"2022-05-14T03:58:28.219007Z","shell.execute_reply.started":"2022-05-14T03:58:28.205604Z","shell.execute_reply":"2022-05-14T03:58:28.218148Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"total data counts:\", dataset['target'].count())\ncounts = dataset['target'].value_counts()\nprint(counts)","metadata":{"execution":{"iopub.status.busy":"2022-05-14T03:58:28.220543Z","iopub.execute_input":"2022-05-14T03:58:28.220847Z","iopub.status.idle":"2022-05-14T03:58:28.235793Z","shell.execute_reply.started":"2022-05-14T03:58:28.220808Z","shell.execute_reply":"2022-05-14T03:58:28.234721Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## cat data","metadata":{}},{"cell_type":"code","source":"rows = 4\ncols = 4\naxes = []\nfig=plt.figure(figsize=(10,10))\ni = 0\n\nfor a in range(rows*cols):\n    b = img.imread(train_cats_dir[i])\n    axes.append(fig.add_subplot(rows,cols,a+1))\n    plt.imshow(b)\n    i+=1\nfig.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-05-14T03:58:28.239854Z","iopub.execute_input":"2022-05-14T03:58:28.240124Z","iopub.status.idle":"2022-05-14T03:58:30.819894Z","shell.execute_reply.started":"2022-05-14T03:58:28.240088Z","shell.execute_reply":"2022-05-14T03:58:30.817248Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## dog data","metadata":{}},{"cell_type":"code","source":"rows = 4\ncols = 4\naxes = []\nfig=plt.figure(figsize=(10,10))\ni = 0\n\nfor a in range(rows*cols):\n    b = img.imread(train_dogs_dir[i])\n    axes.append(fig.add_subplot(rows,cols,a+1))\n    plt.imshow(b)\n    i+=1\nfig.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-05-14T03:58:30.821813Z","iopub.execute_input":"2022-05-14T03:58:30.822107Z","iopub.status.idle":"2022-05-14T03:58:32.793581Z","shell.execute_reply.started":"2022-05-14T03:58:30.822067Z","shell.execute_reply":"2022-05-14T03:58:32.792835Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 3. Data preprocessing","metadata":{}},{"cell_type":"markdown","source":"## Reason for rescaling\n\n* The brightness of each pixel is between 0 and 255.\n* Keras performs optimally when data's value is between 0 and 1.\n* This process is called data normalization.","metadata":{}},{"cell_type":"code","source":"# Each image file consists of a number from 0 to 255.\ntmp = img.imread(train_cats_dir[0])\ntmp = tmp.astype(int)\ntmp0 = tmp[0].astype(int)\n\nfor x in tmp0:\n    for i in x:\n        sys.stdout.write('%d\\t' % i)\n    sys.stdout.write('\\n')","metadata":{"execution":{"iopub.status.busy":"2022-05-14T06:29:29.478959Z","iopub.execute_input":"2022-05-14T06:29:29.479214Z","iopub.status.idle":"2022-05-14T06:29:29.555018Z","shell.execute_reply.started":"2022-05-14T06:29:29.479186Z","shell.execute_reply":"2022-05-14T06:29:29.554250Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## data split\nTo prevent overfitting, the data should be divided into train data and test data.                   \n\n* [about overfitting](https://en.wikipedia.org/wiki/Overfitting)","metadata":{}},{"cell_type":"code","source":"dataset_train, dataset_test = train_test_split(dataset, test_size=0.2, random_state=seed)","metadata":{"execution":{"iopub.status.busy":"2022-05-14T03:58:32.810477Z","iopub.execute_input":"2022-05-14T03:58:32.810799Z","iopub.status.idle":"2022-05-14T03:58:32.883466Z","shell.execute_reply.started":"2022-05-14T03:58:32.810757Z","shell.execute_reply":"2022-05-14T03:58:32.882529Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## ImageDataGenerator\n\nWhen there is little data to train, we have to use **ImageDataGenerator** \nto increase the number of data.         \nIt is recommended to use only scaling for **test data**.\n\n* rescale = 1./255 : change the value between 0 and 1 \n* rotation_range = 15 : Random rotation within 15 degrees\n* shear_range = 0.1 : shear range 10%\n* zoom_range = 0.2 : zoom range 20%\n* horizontal_flip = True : Randomly flip horizontally.\n* width_shift_range = 0.1 : Randomly move the original image horizontally within 10% of the width\n* height_shift_range=0.1 : Randomly move the original image vertically within 10% of the width\n\n* [about ImageDataGenerator_kor.ver](https://keras.io/ko/preprocessing/image/)\n* [about ImageDataGenerator_Image change process_kor.ver](https://tykimos.github.io/2017/06/10/CNN_Data_Augmentation/)            \n\n\n","metadata":{}},{"cell_type":"markdown","source":"## flow_from_dataframe\n\nSave the image data data to the pandas data frame and send it to the ImageDataGenerator.       \n* dataframe: Dataframe must consist of file path and target\n* x_col: column in 'dataframe' that contains the filenames\n* y_col: column in 'dataframe' that has the target data.\n* target_size: image size\n* class_mode: \"binary\" -> binary classification, \"categorical\" -> categorical classification (the data should be one-hot encoded label)\n* batch_size: size of data batch","metadata":{}},{"cell_type":"code","source":"train_datagen=ImageDataGenerator(\nrotation_range=15,\nrescale=1./255,\nshear_range=0.1,\nzoom_range=0.2,\nhorizontal_flip=True,\nwidth_shift_range=0.1,\nheight_shift_range=0.1)\n\ntrain_datagenerator=train_datagen.flow_from_dataframe(dataframe=dataset_train,\n                                                     x_col=\"image_path\",\n                                                     y_col=\"target\",\n                                                     target_size=(WIDTH, HEIGHT),\n                                                     class_mode=\"binary\",\n                                                     batch_size=150)","metadata":{"execution":{"iopub.status.busy":"2022-05-14T03:58:32.885901Z","iopub.execute_input":"2022-05-14T03:58:32.886137Z","iopub.status.idle":"2022-05-14T03:58:33.102033Z","shell.execute_reply.started":"2022-05-14T03:58:32.886109Z","shell.execute_reply":"2022-05-14T03:58:33.101199Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale=1./255)\ntest_datagenerator=test_datagen.flow_from_dataframe(dataframe=dataset_test,\n                                                   x_col=\"image_path\",\n                                                   y_col=\"target\",\n                                                   target_size=(WIDTH, HEIGHT),\n                                                   class_mode=\"binary\",\n                                                   batch_size=150)","metadata":{"execution":{"iopub.status.busy":"2022-05-14T03:58:33.103556Z","iopub.execute_input":"2022-05-14T03:58:33.104037Z","iopub.status.idle":"2022-05-14T03:58:33.168687Z","shell.execute_reply.started":"2022-05-14T03:58:33.103994Z","shell.execute_reply":"2022-05-14T03:58:33.167726Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 4. CNN model","metadata":{}},{"cell_type":"code","source":"model = Sequential() # implement model layer \nmodel.add(Conv2D(32, kernel_size=(3,3), input_shape=(WIDTH, HEIGHT, 3), activation='relu'))\nmodel.add(Conv2D(64, kernel_size=(3,3), activation = 'relu'))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1, activation='sigmoid'))","metadata":{"execution":{"iopub.status.busy":"2022-05-14T03:59:12.074554Z","iopub.status.idle":"2022-05-14T03:59:12.075100Z","shell.execute_reply.started":"2022-05-14T03:59:12.074925Z","shell.execute_reply":"2022-05-14T03:59:12.074944Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-05-14T03:59:18.515983Z","iopub.execute_input":"2022-05-14T03:59:18.516244Z","iopub.status.idle":"2022-05-14T03:59:18.526242Z","shell.execute_reply.started":"2022-05-14T03:59:18.516216Z","shell.execute_reply":"2022-05-14T03:59:18.525278Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(loss=\"binary_crossentropy\", optimizer='adam', metrics=['accuracy'])\nprint(\"[INFO]: model compiled...\")","metadata":{"execution":{"iopub.status.busy":"2022-05-14T03:59:21.948956Z","iopub.execute_input":"2022-05-14T03:59:21.949497Z","iopub.status.idle":"2022-05-14T03:59:21.963113Z","shell.execute_reply.started":"2022-05-14T03:59:21.949458Z","shell.execute_reply":"2022-05-14T03:59:21.962221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"modelHistory=model.fit(train_datagenerator,\n                       epochs=50,\n                       validation_data=test_datagenerator,\n                       validation_steps=dataset_test.shape[0]/150,\n                       steps_per_epoch=dataset_train.shape[0]/150)","metadata":{"execution":{"iopub.status.busy":"2022-05-14T03:59:24.599179Z","iopub.execute_input":"2022-05-14T03:59:24.599778Z","iopub.status.idle":"2022-05-14T06:15:09.115064Z","shell.execute_reply.started":"2022-05-14T03:59:24.599739Z","shell.execute_reply":"2022-05-14T06:15:09.114302Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc = modelHistory.history['accuracy']\nval_acc = modelHistory.history['val_accuracy']\nloss = modelHistory.history['loss']\nval_loss = modelHistory.history['val_loss']\n\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, 'bo', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs, loss, 'go', label='Training Loss')\nplt.plot(epochs, val_loss, 'g', label='Validation Loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()\n\n","metadata":{"execution":{"iopub.status.busy":"2022-05-14T06:24:25.956339Z","iopub.execute_input":"2022-05-14T06:24:25.956625Z","iopub.status.idle":"2022-05-14T06:24:26.327247Z","shell.execute_reply.started":"2022-05-14T06:24:25.956592Z","shell.execute_reply":"2022-05-14T06:24:26.326587Z"},"trusted":true},"execution_count":null,"outputs":[]}]}