{"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\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-07-28T13:24:19.346165Z","iopub.execute_input":"2023-07-28T13:24:19.346575Z","iopub.status.idle":"2023-07-28T13:24:19.359387Z","shell.execute_reply.started":"2023-07-28T13:24:19.346544Z","shell.execute_reply":"2023-07-28T13:24:19.357918Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TEST1_DIR = 'test1'\nTRAIN_DIR = 'train'\nINPUT_DIR = '../input/dogs-vs-cats'\nOUTPUT_DIR = '/output/'","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:24:31.621405Z","iopub.execute_input":"2023-07-28T13:24:31.622046Z","iopub.status.idle":"2023-07-28T13:24:31.628306Z","shell.execute_reply.started":"2023-07-28T13:24:31.622008Z","shell.execute_reply":"2023-07-28T13:24:31.626475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd \n\nimport matplotlib.pyplot as plt\nimport matplotlib.image as img\n%matplotlib inline\nimport seaborn as sns\nfrom PIL import Image, ImageFilter, ImageEnhance\nimport cv2\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers.experimental import preprocessing\nimport os\nfrom numpy import asarray\n\nimport 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":"2023-07-28T13:24:42.860025Z","iopub.execute_input":"2023-07-28T13:24:42.860412Z","iopub.status.idle":"2023-07-28T13:24:53.526757Z","shell.execute_reply.started":"2023-07-28T13:24:42.860385Z","shell.execute_reply":"2023-07-28T13:24:53.52577Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator","metadata":{"execution":{"iopub.status.busy":"2023-07-28T14:04:46.47119Z","iopub.execute_input":"2023-07-28T14:04:46.471577Z","iopub.status.idle":"2023-07-28T14:04:46.475745Z","shell.execute_reply.started":"2023-07-28T14:04:46.47155Z","shell.execute_reply":"2023-07-28T14:04:46.474857Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TRAIN_DIR_PATH = './train'\nfile_names = os.listdir(TRAIN_DIR_PATH)\nprint('There are {} number of images in directory.'.format(len(file_names)))","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:10:55.266692Z","iopub.execute_input":"2023-07-28T13:10:55.267026Z","iopub.status.idle":"2023-07-28T13:10:55.283305Z","shell.execute_reply.started":"2023-07-28T13:10:55.266997Z","shell.execute_reply":"2023-07-28T13:10:55.281449Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-07-28T13:11:22.360085Z","iopub.execute_input":"2023-07-28T13:11:22.360519Z","iopub.status.idle":"2023-07-28T13:11:22.365788Z","shell.execute_reply.started":"2023-07-28T13:11:22.360485Z","shell.execute_reply":"2023-07-28T13:11:22.364729Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# トレーニングデータを用意する","metadata":{}},{"cell_type":"code","source":"#filenames = os.listdir(\"../input/train/train\")\nfilenames = os.listdir(TRAIN_DIR_PATH)\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\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:11:32.122539Z","iopub.execute_input":"2023-07-28T13:11:32.122925Z","iopub.status.idle":"2023-07-28T13:11:32.178088Z","shell.execute_reply.started":"2023-07-28T13:11:32.122894Z","shell.execute_reply":"2023-07-28T13:11:32.176406Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.tail()","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:12:13.151676Z","iopub.execute_input":"2023-07-28T13:12:13.152068Z","iopub.status.idle":"2023-07-28T13:12:13.163719Z","shell.execute_reply.started":"2023-07-28T13:12:13.152036Z","shell.execute_reply":"2023-07-28T13:12:13.16249Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['category'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:12:30.721457Z","iopub.execute_input":"2023-07-28T13:12:30.72183Z","iopub.status.idle":"2023-07-28T13:12:31.016969Z","shell.execute_reply.started":"2023-07-28T13:12:30.721802Z","shell.execute_reply":"2023-07-28T13:12:31.015917Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cat = [file for file in file_names if file[:3]=='cat'] # cat images\nprint(\"Images for cat =\",len(cat))\ndog = [file for file in file_names if file[:3]=='dog'] # dog images\nprint(\"Images for dog =\",len(dog))","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:27:31.355479Z","iopub.execute_input":"2023-07-28T13:27:31.355859Z","iopub.status.idle":"2023-07-28T13:27:31.371653Z","shell.execute_reply.started":"2023-07-28T13:27:31.35583Z","shell.execute_reply":"2023-07-28T13:27:31.370141Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2 \nimport matplotlib.pyplot as plt\nimport matplotlib.image as img\nimport random\n\nplt.figure(figsize = (18,9))\nindex = random.randint(1,12000)\nfor i, c in enumerate(range(index, index + 5), start=1):\n    im = img.imread('./train/'+cat[c])\n    plt.subplot(2,5,i)\n    plt.imshow(im)\n    \nfor i, c in enumerate(range(index,index + 5), start=6):\n    im = img.imread('./train/'+dog[c])\n    plt.subplot(2,5,i)\n    plt.imshow(im)","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:27:36.202228Z","iopub.execute_input":"2023-07-28T13:27:36.202655Z","iopub.status.idle":"2023-07-28T13:27:38.428655Z","shell.execute_reply.started":"2023-07-28T13:27:36.202624Z","shell.execute_reply":"2023-07-28T13:27:38.427765Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filenames = os.listdir(TRAIN_DIR)\nfilenames[:5]","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:36:46.517421Z","iopub.execute_input":"2023-07-28T13:36:46.517859Z","iopub.status.idle":"2023-07-28T13:36:46.536883Z","shell.execute_reply.started":"2023-07-28T13:36:46.517828Z","shell.execute_reply":"2023-07-28T13:36:46.534679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = [1 if filename.startswith('dog') else 0 for filename in filenames]\nlabels[:5]","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:37:02.070781Z","iopub.execute_input":"2023-07-28T13:37:02.071148Z","iopub.status.idle":"2023-07-28T13:37:02.084975Z","shell.execute_reply.started":"2023-07-28T13:37:02.071121Z","shell.execute_reply":"2023-07-28T13:37:02.082915Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.DataFrame({\n    'filename': filenames,\n    'category': labels\n})\n\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:37:17.269883Z","iopub.execute_input":"2023-07-28T13:37:17.270205Z","iopub.status.idle":"2023-07-28T13:37:17.285997Z","shell.execute_reply.started":"2023-07-28T13:37:17.270182Z","shell.execute_reply":"2023-07-28T13:37:17.284598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, BatchNormalization\n\nmodel = Sequential()\n\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNELS)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(512, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(2, activation='softmax')) # 2 because we have cat and dog classes\n\nmodel.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:56:46.390236Z","iopub.execute_input":"2023-07-28T13:56:46.390709Z","iopub.status.idle":"2023-07-28T13:56:46.891989Z","shell.execute_reply.started":"2023-07-28T13:56:46.390673Z","shell.execute_reply":"2023-07-28T13:56:46.890386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ReduceLROnPlateau","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:58:06.116583Z","iopub.execute_input":"2023-07-28T13:58:06.116987Z","iopub.status.idle":"2023-07-28T13:58:06.125302Z","shell.execute_reply.started":"2023-07-28T13:58:06.116957Z","shell.execute_reply":"2023-07-28T13:58:06.121922Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"earlystop = EarlyStopping(patience=10)","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:58:09.334821Z","iopub.execute_input":"2023-07-28T13:58:09.335166Z","iopub.status.idle":"2023-07-28T13:58:09.340123Z","shell.execute_reply.started":"2023-07-28T13:58:09.335141Z","shell.execute_reply":"2023-07-28T13:58:09.339342Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=2, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:58:12.016237Z","iopub.execute_input":"2023-07-28T13:58:12.016614Z","iopub.status.idle":"2023-07-28T13:58:12.023218Z","shell.execute_reply.started":"2023-07-28T13:58:12.016586Z","shell.execute_reply":"2023-07-28T13:58:12.02152Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"callbacks = [earlystop, learning_rate_reduction]","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:58:15.855487Z","iopub.execute_input":"2023-07-28T13:58:15.855868Z","iopub.status.idle":"2023-07-28T13:58:15.861103Z","shell.execute_reply.started":"2023-07-28T13:58:15.855837Z","shell.execute_reply":"2023-07-28T13:58:15.859944Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# データを用意する","metadata":{}},{"cell_type":"code","source":"df[\"category\"] = df[\"category\"].replace({0: 'cat', 1: 'dog'}) \n\n","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:41:59.852926Z","iopub.execute_input":"2023-07-28T13:41:59.853286Z","iopub.status.idle":"2023-07-28T13:41:59.862157Z","shell.execute_reply.started":"2023-07-28T13:41:59.853261Z","shell.execute_reply":"2023-07-28T13:41:59.860742Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:43:14.837936Z","iopub.execute_input":"2023-07-28T13:43:14.838315Z","iopub.status.idle":"2023-07-28T13:43:15.06311Z","shell.execute_reply.started":"2023-07-28T13:43:14.838288Z","shell.execute_reply":"2023-07-28T13:43:15.061345Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_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)\ntrain_df['category'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:43:41.647578Z","iopub.execute_input":"2023-07-28T13:43:41.649126Z","iopub.status.idle":"2023-07-28T13:43:41.825868Z","shell.execute_reply.started":"2023-07-28T13:43:41.64907Z","shell.execute_reply":"2023-07-28T13:43:41.824875Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validate_df['category'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:44:30.287551Z","iopub.execute_input":"2023-07-28T13:44:30.287946Z","iopub.status.idle":"2023-07-28T13:44:30.460521Z","shell.execute_reply.started":"2023-07-28T13:44:30.287915Z","shell.execute_reply":"2023-07-28T13:44:30.4589Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"total_train = train_df.shape[0]\ntotal_validate = validate_df.shape[0]\nbatch_size=15","metadata":{"execution":{"iopub.status.busy":"2023-07-28T13:44:53.322902Z","iopub.execute_input":"2023-07-28T13:44:53.324258Z","iopub.status.idle":"2023-07-28T13:44:53.330125Z","shell.execute_reply.started":"2023-07-28T13:44:53.324201Z","shell.execute_reply":"2023-07-28T13:44:53.328212Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_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    #\"../input/train/train/\", \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":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validation_datagen = ImageDataGenerator(rescale=1./255)\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    validate_df, \n    #\"../input/train/train/\", \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":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"example_df = train_df.sample(n=1).reset_index(drop=True)\nexample_generator = train_datagen.flow_from_dataframe(\n    example_df, \n    #\"../input/train/train/\", \n    \"./train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical'\n)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(12, 12))\nfor i in range(0, 15):\n    plt.subplot(5, 3, i+1)\n    for X_batch, Y_batch in example_generator:\n        image = X_batch[0]\n        plt.imshow(image)\n        break\nplt.tight_layout()\nplt.show()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Fit Model","metadata":{}},{"cell_type":"code","source":"epochs=3 \n#if FAST_RUN else 50\nhistory = model.fit(\n    train_generator, \n    epochs=epochs,\n    validation_data=validation_generator,\n    validation_steps=total_validate//batch_size,\n    steps_per_epoch=total_train//batch_size,\n    callbacks=callbacks\n)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save_weights(\"model.h5\")","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 12))\nax1.plot(history.history['loss'], color='b', label=\"Training loss\")\nax1.plot(history.history['val_loss'], color='r', label=\"validation loss\")\nax1.set_xticks(np.arange(1, epochs, 1))\nax1.set_yticks(np.arange(0, 1, 0.1))\n\nax2.plot(history.history['accuracy'], color='b', label=\"Training accuracy\")\nax2.plot(history.history['val_accuracy'], color='r',label=\"Validation accuracy\")\nax2.set_xticks(np.arange(1, epochs, 1))\nax2.set_yticks(np.arange(0, 1, 0.1))\n\nlegend = plt.legend(loc='best', shadow=True)\nplt.tight_layout()\nplt.show()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#test_filenames = os.listdir(\"../input/test1/test1\")\ntest_filenames = os.listdir(\"./test1\")\ntest_df = pd.DataFrame({\n    'filename': test_filenames\n})\nnb_samples = test_df.shape[0]","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_gen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_gen.flow_from_dataframe(\n    test_df, \n    #\"../input/test1/test1/\", \n    \"./test1/\", \n    x_col='filename',\n    y_col=None,\n    class_mode=None,\n    target_size=IMAGE_SIZE,\n    batch_size=batch_size,\n    shuffle=False\n)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predict = model.predict(test_generator, steps=np.ceil(nb_samples/batch_size))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df['category'] = np.argmax(predict, axis=-1)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label_map = dict((v,k) for k,v in train_generator.class_indices.items())\ntest_df['category'] = test_df['category'].replace(label_map)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df['category'] = test_df['category'].replace({ 'dog': 1, 'cat': 0 })","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df['category'].value_counts().plot.bar()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_test = test_df.head(18)\nsample_test.head()\nplt.figure(figsize=(12, 24))\nfor index, row in sample_test.iterrows():\n    filename = row['filename']\n    category = row['category']\n    #img = load_img(\"../input/test1/test1/\"+filename, target_size=IMAGE_SIZE)\n    img = load_img(\"./test1/\"+filename, target_size=IMAGE_SIZE)\n    plt.subplot(6, 3, index+1)\n    plt.imshow(img)\n    plt.xlabel(filename + '(' + \"{}\".format(category) + ')' )\nplt.tight_layout()\nplt.show()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df = test_df.copy()\nsubmission_df['id'] = submission_df['filename'].str.split('.').str[0]\nsubmission_df['label'] = submission_df['category']\nsubmission_df.drop(['filename', 'category'], axis=1, inplace=True)\nsubmission_df.to_csv('submission.csv', index=False)","metadata":{},"execution_count":null,"outputs":[]}]}