{"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":"2021-07-16T10:36:22.420893Z","iopub.execute_input":"2021-07-16T10:36:22.421266Z","iopub.status.idle":"2021-07-16T10:36:22.438726Z","shell.execute_reply.started":"2021-07-16T10:36:22.421187Z","shell.execute_reply":"2021-07-16T10:36:22.437507Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import zipfile\nwith zipfile.ZipFile('../input/dogs-vs-cats-redux-kernels-edition/test.zip') as existing_zip:\n    existing_zip.extractall()\nwith zipfile.ZipFile('../input/dogs-vs-cats-redux-kernels-edition/train.zip') as existing_zip:\n    existing_zip.extractall()","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:37:20.976755Z","iopub.execute_input":"2021-07-16T10:37:20.977076Z","iopub.status.idle":"2021-07-16T10:37:38.543746Z","shell.execute_reply.started":"2021-07-16T10:37:20.977047Z","shell.execute_reply":"2021-07-16T10:37:38.541993Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd train","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:38:07.814300Z","iopub.execute_input":"2021-07-16T10:38:07.814654Z","iopub.status.idle":"2021-07-16T10:38:07.822393Z","shell.execute_reply.started":"2021-07-16T10:38:07.814625Z","shell.execute_reply":"2021-07-16T10:38:07.821245Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir cats","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:38:08.778236Z","iopub.execute_input":"2021-07-16T10:38:08.778784Z","iopub.status.idle":"2021-07-16T10:38:09.507990Z","shell.execute_reply.started":"2021-07-16T10:38:08.778733Z","shell.execute_reply":"2021-07-16T10:38:09.506758Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir dogs","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:38:10.314391Z","iopub.execute_input":"2021-07-16T10:38:10.314794Z","iopub.status.idle":"2021-07-16T10:38:11.004351Z","shell.execute_reply.started":"2021-07-16T10:38:10.314761Z","shell.execute_reply":"2021-07-16T10:38:11.003158Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil\nimport glob\nimport os\n\ndef move_glob(dst_path, pathname, recursive=True):\n    for p in glob.glob(pathname, recursive=recursive):\n        shutil.move(p, dst_path)\n\nmove_glob('./dogs', 'dog*.jpg')\nmove_glob('./cats', 'cat*.jpg')","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:38:12.216934Z","iopub.execute_input":"2021-07-16T10:38:12.217269Z","iopub.status.idle":"2021-07-16T10:38:13.141017Z","shell.execute_reply.started":"2021-07-16T10:38:12.217239Z","shell.execute_reply":"2021-07-16T10:38:13.140131Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd ../","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:38:15.223200Z","iopub.execute_input":"2021-07-16T10:38:15.223592Z","iopub.status.idle":"2021-07-16T10:38:15.233570Z","shell.execute_reply.started":"2021-07-16T10:38:15.223556Z","shell.execute_reply":"2021-07-16T10:38:15.230974Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir valid","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:38:16.986978Z","iopub.execute_input":"2021-07-16T10:38:16.987331Z","iopub.status.idle":"2021-07-16T10:38:17.664029Z","shell.execute_reply.started":"2021-07-16T10:38:16.987299Z","shell.execute_reply":"2021-07-16T10:38:17.662804Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd valid","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:38:18.486601Z","iopub.execute_input":"2021-07-16T10:38:18.486981Z","iopub.status.idle":"2021-07-16T10:38:18.503681Z","shell.execute_reply.started":"2021-07-16T10:38:18.486947Z","shell.execute_reply":"2021-07-16T10:38:18.502525Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir dogs","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:38:19.466270Z","iopub.execute_input":"2021-07-16T10:38:19.466678Z","iopub.status.idle":"2021-07-16T10:38:20.143359Z","shell.execute_reply.started":"2021-07-16T10:38:19.466645Z","shell.execute_reply":"2021-07-16T10:38:20.142161Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir cats","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:38:21.103670Z","iopub.execute_input":"2021-07-16T10:38:21.104002Z","iopub.status.idle":"2021-07-16T10:38:21.784631Z","shell.execute_reply.started":"2021-07-16T10:38:21.103971Z","shell.execute_reply":"2021-07-16T10:38:21.783460Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd ..","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:38:23.769673Z","iopub.execute_input":"2021-07-16T10:38:23.769995Z","iopub.status.idle":"2021-07-16T10:38:23.775819Z","shell.execute_reply.started":"2021-07-16T10:38:23.769964Z","shell.execute_reply":"2021-07-16T10:38:23.774901Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\nimport numpy as np\n\ndef resize(src_file, dst_file, width, height):\n    \"\"\"\n    画像ファイルを与えられたサイズにサイズ変換する関数\n    アス比は固定、左上に寄せる、余った部分はゼロで埋める\n\n    Returns\n    -------\n    ret_scale : float\n    拡大/縮小した倍率\n    \"\"\"\n\n    src_img = cv2.imread(src_file)\n    h, w, c = src_img.shape\n    # dst_img = cv2.resize(src_img, dsize=(width, height))\n\n    # アス比固定, padding\n    scale_w = width / w\n    scale_h = height / h\n\n    ret_scale = 1.0\n    # Down Convert\n    if(scale_w < 1.0 or scale_h < 1.0):\n        if(scale_w < scale_h): \n            resize_img = cv2.resize(src_img, dsize=None, fx=scale_w, fy=scale_w, interpolation = cv2.INTER_AREA)\n            ret_scale = scale_w\n        else:\n            resize_img = cv2.resize(src_img, dsize=None, fx=scale_h, fy=scale_h, interpolation = cv2.INTER_AREA)\n            ret_scale = scale_h\n    else:\n        resize_img = src_img\n\n    # dst_img 生成\n    dst_img = np.zeros((height, width, 3), dtype = np.uint8)\n\n    # dst_imgにresize_imgを合成\n    top = 0\n    left = 0\n    #dst_img[top:height + top, left:width + left] = resize_img\n    h, w, c = resize_img.shape\n    dst_img[0:h, 0:w] = resize_img\n\n    cv2.imwrite(dst_file, dst_img)\n\n    return ret_scale","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:38:25.506167Z","iopub.execute_input":"2021-07-16T10:38:25.506546Z","iopub.status.idle":"2021-07-16T10:38:25.837595Z","shell.execute_reply.started":"2021-07-16T10:38:25.506509Z","shell.execute_reply":"2021-07-16T10:38:25.836659Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for num in range(0, 12500):\n    resize('train/dogs/dog.' + str(num) + '.jpg', 'train/dogs/dog.' + str(num) + '.jpg', 216, 216)\n    resize('train/cats/cat.' + str(num) + '.jpg', 'train/cats/cat.' + str(num) + '.jpg', 216, 216)\n\nfor num in range(2500):\n    move_glob('valid/cats', 'train/cats/cat.'+ str(num) +'.jpg')\n    move_glob('valid/dogs', 'train/dogs/dog.'+ str(num) +'.jpg')","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:38:28.532157Z","iopub.execute_input":"2021-07-16T10:38:28.532565Z","iopub.status.idle":"2021-07-16T10:40:14.426278Z","shell.execute_reply.started":"2021-07-16T10:38:28.532535Z","shell.execute_reply":"2021-07-16T10:40:14.425428Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras import optimizers, regularizers\nfrom tensorflow.keras.layers import Dense, Flatten, Dropout\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D\nimport os\nimport datetime\nimport tensorflow as tf","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:40:27.469438Z","iopub.execute_input":"2021-07-16T10:40:27.469758Z","iopub.status.idle":"2021-07-16T10:40:27.474315Z","shell.execute_reply.started":"2021-07-16T10:40:27.469729Z","shell.execute_reply":"2021-07-16T10:40:27.473520Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data_dir = 'train'\nvalid_data_dir = 'valid'\nbs = 128","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:40:29.138114Z","iopub.execute_input":"2021-07-16T10:40:29.138469Z","iopub.status.idle":"2021-07-16T10:40:29.144615Z","shell.execute_reply.started":"2021-07-16T10:40:29.138433Z","shell.execute_reply":"2021-07-16T10:40:29.143652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rescale=1.0/255, rotation_range=90, horizontal_flip=True, channel_shift_range=50.)\nvalid_datagen = ImageDataGenerator(rescale=1.0/255)\n\ntrain_generator = train_datagen.flow_from_directory(\n    directory=train_data_dir, target_size=(216, 216), batch_size=bs, class_mode=\"binary\")\nvalid_generator = valid_datagen.flow_from_directory(\n    directory=valid_data_dir, target_size=(216, 216), batch_size=bs, class_mode=\"binary\")","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:40:35.049267Z","iopub.execute_input":"2021-07-16T10:40:35.049643Z","iopub.status.idle":"2021-07-16T10:40:36.317811Z","shell.execute_reply.started":"2021-07-16T10:40:35.049611Z","shell.execute_reply":"2021-07-16T10:40:36.316939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(64, kernel_size=(5, 5),\n          activation=\"relu\", kernel_regularizer=regularizers.l2(0.0001), input_shape=(216, 216, 3)))\n\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(128, kernel_size=(5, 5),\n          kernel_regularizer=regularizers.l2(0.0001), activation=\"relu\"))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(128, kernel_size=(5, 5),\n          kernel_regularizer=regularizers.l2(0.0001), activation=\"relu\"))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(128, kernel_size=(5, 5),\n          kernel_regularizer=regularizers.l2(0.0001), activation=\"relu\"))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(256, activation=\"relu\"))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1, activation=\"sigmoid\"))\n\nopt = optimizers.Adam(learning_rate=0.0001)\nmodel.compile(loss=\"binary_crossentropy\",\n              optimizer=opt, metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:40:39.007579Z","iopub.execute_input":"2021-07-16T10:40:39.007909Z","iopub.status.idle":"2021-07-16T10:40:41.153031Z","shell.execute_reply.started":"2021-07-16T10:40:39.007879Z","shell.execute_reply":"2021-07-16T10:40:41.151960Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:40:41.605914Z","iopub.execute_input":"2021-07-16T10:40:41.606225Z","iopub.status.idle":"2021-07-16T10:40:41.619486Z","shell.execute_reply.started":"2021-07-16T10:40:41.606195Z","shell.execute_reply":"2021-07-16T10:40:41.618007Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(train_generator, \n                    epochs=80, \n                    verbose=1, \n                    validation_data=(valid_generator), \n                    steps_per_epoch=20000 / bs, \n                    validation_steps=5000/bs)","metadata":{"execution":{"iopub.status.busy":"2021-07-16T10:40:46.131701Z","iopub.execute_input":"2021-07-16T10:40:46.132113Z","iopub.status.idle":"2021-07-16T10:41:51.205529Z","shell.execute_reply.started":"2021-07-16T10:40:46.132079Z","shell.execute_reply":"2021-07-16T10:41:51.203412Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save(\"model.h5\")","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nloss = history.history[\"loss\"]\nval_loss = history.history[\"val_loss\"]\n\nlearning_count = len(loss)+1\n\nplt.plot(range(1,learning_count),loss,marker = \"+\",label = \"loss\")\nplt.plot(range(1,learning_count),val_loss,marker = \"+\",label = \"val_loss\")\nplt.legend(loc = \"best\",fontsize = 10)\nplt.xlabel(\"learning_count\")\nplt.ylabel(\"loss\")\nplt.show()\n\naccuracy = history.history[\"accuracy\"]\nval_accuracy = history.history[\"val_accuracy\"]\n\nlearning_count = len(loss)+1\n\nplt.plot(range(1,learning_count),accuracy,marker = \"+\",label = \"accuracy\")\nplt.plot(range(1,learning_count),val_accuracy,marker = \"+\",label = \"val_accuracy\")\nplt.legend(loc = \"best\",fontsize = 10)\nplt.xlabel(\"learning_count\")\nplt.ylabel(\"accuracy\")\nplt.show()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.models import load_model","metadata":{"execution":{"iopub.status.busy":"2021-07-16T05:51:36.228798Z","iopub.execute_input":"2021-07-16T05:51:36.229209Z","iopub.status.idle":"2021-07-16T05:51:36.234256Z","shell.execute_reply.started":"2021-07-16T05:51:36.229158Z","shell.execute_reply":"2021-07-16T05:51:36.233402Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"new_model = load_model('model.h5')","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"result = []\n\nfor num in range(1, 12501):\n    # 予測したい画像のパス\n    TESTPATH = \"test/\" + str(num) + \".jpg\"\n\n    # 予測モデルに入力できるように画像を配列に落とし込む\n    img = image.load_img(TESTPATH, target_size=(216, 216))\n    x = image.img_to_array(img)\n    x = np.expand_dims(x, axis=0)\n    x = x / 255.0\n    # 予測\n    result_predict = new_model.predict(x)\n    # print(result_predict)\n    result.append(result_predict)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"result_num = []\n\nfor num in range(1, 12501):\n    result_num.append(num)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_res = pd.DataFrame([result])\ndf_res = df_res.T\nfor col in df_res:\n    df_res[col] = df_res[col].astype(\n        str).str.replace(\"[\", \"\").str.replace(\"]\", \"\")\ndf = pd.read_csv('../input/dogs-vs-cats-redux-kernels-edition/sample_submission.csv')\ndf['label'] = df_res","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df","metadata":{"execution":{"iopub.status.busy":"2021-07-16T05:40:15.954376Z","iopub.execute_input":"2021-07-16T05:40:15.95479Z","iopub.status.idle":"2021-07-16T05:40:16.710953Z","shell.execute_reply.started":"2021-07-16T05:40:15.954758Z","shell.execute_reply":"2021-07-16T05:40:16.709688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.to_csv(\"submission.csv\", index=False)","metadata":{},"execution_count":null,"outputs":[]}]}