{"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","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-28T10:23:46.332681Z","iopub.execute_input":"2021-07-28T10:23:46.333049Z","iopub.status.idle":"2021-07-28T10:24:03.715736Z","shell.execute_reply.started":"2021-07-28T10:23:46.332970Z","shell.execute_reply":"2021-07-28T10:24:03.714902Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd train","metadata":{"execution":{"iopub.status.busy":"2021-07-28T10:26:36.895087Z","iopub.execute_input":"2021-07-28T10:26:36.895413Z","iopub.status.idle":"2021-07-28T10:26:36.903003Z","shell.execute_reply.started":"2021-07-28T10:26:36.895386Z","shell.execute_reply":"2021-07-28T10:26:36.902025Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir cats","metadata":{"execution":{"iopub.status.busy":"2021-07-28T10:26:51.985798Z","iopub.execute_input":"2021-07-28T10:26:51.986126Z","iopub.status.idle":"2021-07-28T10:26:52.618718Z","shell.execute_reply.started":"2021-07-28T10:26:51.986098Z","shell.execute_reply":"2021-07-28T10:26:52.617654Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir dogs","metadata":{"execution":{"iopub.status.busy":"2021-07-28T10:27:02.454051Z","iopub.execute_input":"2021-07-28T10:27:02.454377Z","iopub.status.idle":"2021-07-28T10:27:03.128293Z","shell.execute_reply.started":"2021-07-28T10:27:02.454345Z","shell.execute_reply":"2021-07-28T10:27:03.127247Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil\nimport glob\nimport os\n\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-28T10:27:40.068259Z","iopub.execute_input":"2021-07-28T10:27:40.068705Z","iopub.status.idle":"2021-07-28T10:27:40.933092Z","shell.execute_reply.started":"2021-07-28T10:27:40.068667Z","shell.execute_reply":"2021-07-28T10:27:40.932148Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd ../","metadata":{"execution":{"iopub.status.busy":"2021-07-28T10:27:58.018998Z","iopub.execute_input":"2021-07-28T10:27:58.019315Z","iopub.status.idle":"2021-07-28T10:27:58.026504Z","shell.execute_reply.started":"2021-07-28T10:27:58.019287Z","shell.execute_reply":"2021-07-28T10:27:58.025492Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir valid","metadata":{"execution":{"iopub.status.busy":"2021-07-28T10:28:13.989912Z","iopub.execute_input":"2021-07-28T10:28:13.990230Z","iopub.status.idle":"2021-07-28T10:28:14.662636Z","shell.execute_reply.started":"2021-07-28T10:28:13.990201Z","shell.execute_reply":"2021-07-28T10:28:14.661467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd valid","metadata":{"execution":{"iopub.status.busy":"2021-07-28T10:28:22.142021Z","iopub.execute_input":"2021-07-28T10:28:22.142374Z","iopub.status.idle":"2021-07-28T10:28:22.147780Z","shell.execute_reply.started":"2021-07-28T10:28:22.142339Z","shell.execute_reply":"2021-07-28T10:28:22.146930Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir cats","metadata":{"execution":{"iopub.status.busy":"2021-07-28T10:28:33.465211Z","iopub.execute_input":"2021-07-28T10:28:33.465565Z","iopub.status.idle":"2021-07-28T10:28:34.142785Z","shell.execute_reply.started":"2021-07-28T10:28:33.465529Z","shell.execute_reply":"2021-07-28T10:28:34.141688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir dogs","metadata":{"execution":{"iopub.status.busy":"2021-07-28T10:28:49.087133Z","iopub.execute_input":"2021-07-28T10:28:49.087468Z","iopub.status.idle":"2021-07-28T10:28:49.715771Z","shell.execute_reply.started":"2021-07-28T10:28:49.087432Z","shell.execute_reply":"2021-07-28T10:28:49.714692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd ../","metadata":{"execution":{"iopub.status.busy":"2021-07-28T10:29:02.865891Z","iopub.execute_input":"2021-07-28T10:29:02.866215Z","iopub.status.idle":"2021-07-28T10:29:02.871940Z","shell.execute_reply.started":"2021-07-28T10:29:02.866183Z","shell.execute_reply":"2021-07-28T10:29:02.870913Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\nimport numpy as np\n\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-28T10:29:46.356283Z","iopub.execute_input":"2021-07-28T10:29:46.356655Z","iopub.status.idle":"2021-07-28T10:29:46.517380Z","shell.execute_reply.started":"2021-07-28T10:29:46.356622Z","shell.execute_reply":"2021-07-28T10:29:46.516346Z"},"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', 224, 224)\n    resize('train/cats/cat.' + str(num) + '.jpg', 'train/cats/cat.' + str(num) + '.jpg', 224, 224)\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-28T10:30:28.776255Z","iopub.execute_input":"2021-07-28T10:30:28.776587Z","iopub.status.idle":"2021-07-28T10:32:15.945724Z","shell.execute_reply.started":"2021-07-28T10:30:28.776558Z","shell.execute_reply":"2021-07-28T10:32:15.944745Z"},"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-28T10:33:47.187724Z","iopub.execute_input":"2021-07-28T10:33:47.188054Z","iopub.status.idle":"2021-07-28T10:33:51.159888Z","shell.execute_reply.started":"2021-07-28T10:33:47.188025Z","shell.execute_reply":"2021-07-28T10:33:51.158841Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data_dir = 'train'\nvalid_data_dir = 'valid'","metadata":{"execution":{"iopub.status.busy":"2021-07-28T10:34:20.321177Z","iopub.execute_input":"2021-07-28T10:34:20.321538Z","iopub.status.idle":"2021-07-28T10:34:20.325422Z","shell.execute_reply.started":"2021-07-28T10:34:20.321493Z","shell.execute_reply":"2021-07-28T10:34:20.324549Z"},"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=(224, 224), batch_size=64, class_mode=\"binary\")\nvalid_generator = valid_datagen.flow_from_directory(\n    directory=valid_data_dir, target_size=(224, 224), batch_size=64, class_mode=\"binary\")","metadata":{"execution":{"iopub.status.busy":"2021-07-28T10:35:31.017493Z","iopub.execute_input":"2021-07-28T10:35:31.017855Z","iopub.status.idle":"2021-07-28T10:35:32.121094Z","shell.execute_reply.started":"2021-07-28T10:35:31.017826Z","shell.execute_reply":"2021-07-28T10:35:32.120261Z"},"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=(224, 224, 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-28T10:38:03.253634Z","iopub.execute_input":"2021-07-28T10:38:03.254029Z","iopub.status.idle":"2021-07-28T10:38:05.473556Z","shell.execute_reply.started":"2021-07-28T10:38:03.253978Z","shell.execute_reply":"2021-07-28T10:38:05.472777Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2021-07-28T10:38:21.206249Z","iopub.execute_input":"2021-07-28T10:38:21.206603Z","iopub.status.idle":"2021-07-28T10:38:21.219453Z","shell.execute_reply.started":"2021-07-28T10:38:21.206571Z","shell.execute_reply":"2021-07-28T10:38:21.218649Z"},"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 / 64, \n                    validation_steps=5000/64)","metadata":{"execution":{"iopub.status.busy":"2021-07-28T10:39:02.179438Z","iopub.execute_input":"2021-07-28T10:39:02.179812Z","iopub.status.idle":"2021-07-28T16:30:49.964223Z","shell.execute_reply.started":"2021-07-28T10:39:02.179781Z","shell.execute_reply":"2021-07-28T16:30:49.963170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save(\"model.h5\")","metadata":{"execution":{"iopub.status.busy":"2021-07-28T16:31:33.004869Z","iopub.execute_input":"2021-07-28T16:31:33.005213Z","iopub.status.idle":"2021-07-28T16:31:33.127687Z","shell.execute_reply.started":"2021-07-28T16:31:33.005181Z","shell.execute_reply":"2021-07-28T16:31:33.126832Z"},"trusted":true},"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":{"iopub.status.busy":"2021-07-28T16:32:00.251341Z","iopub.execute_input":"2021-07-28T16:32:00.251695Z","iopub.status.idle":"2021-07-28T16:32:00.590058Z","shell.execute_reply.started":"2021-07-28T16:32:00.251663Z","shell.execute_reply":"2021-07-28T16:32:00.589292Z"},"trusted":true},"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-28T16:32:42.365690Z","iopub.execute_input":"2021-07-28T16:32:42.366016Z","iopub.status.idle":"2021-07-28T16:32:42.372496Z","shell.execute_reply.started":"2021-07-28T16:32:42.365986Z","shell.execute_reply":"2021-07-28T16:32:42.371545Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"new_model = load_model('model.h5')","metadata":{"execution":{"iopub.status.busy":"2021-07-28T16:33:00.223079Z","iopub.execute_input":"2021-07-28T16:33:00.223497Z","iopub.status.idle":"2021-07-28T16:33:00.425394Z","shell.execute_reply.started":"2021-07-28T16:33:00.223457Z","shell.execute_reply":"2021-07-28T16:33:00.424507Z"},"trusted":true},"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=(224, 224))\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":{"iopub.status.busy":"2021-07-28T16:33:39.144564Z","iopub.execute_input":"2021-07-28T16:33:39.144904Z","iopub.status.idle":"2021-07-28T16:41:25.770360Z","shell.execute_reply.started":"2021-07-28T16:33:39.144869Z","shell.execute_reply":"2021-07-28T16:41:25.769572Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"result_num = []\n\nfor num in range(1, 12501):\n    result_num.append(num)","metadata":{"execution":{"iopub.status.busy":"2021-07-28T16:42:01.702724Z","iopub.execute_input":"2021-07-28T16:42:01.703080Z","iopub.status.idle":"2021-07-28T16:42:01.710034Z","shell.execute_reply.started":"2021-07-28T16:42:01.703048Z","shell.execute_reply":"2021-07-28T16:42:01.708817Z"},"trusted":true},"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":{"iopub.status.busy":"2021-07-28T16:42:22.859486Z","iopub.execute_input":"2021-07-28T16:42:22.859831Z","iopub.status.idle":"2021-07-28T16:42:25.011985Z","shell.execute_reply.started":"2021-07-28T16:42:22.859801Z","shell.execute_reply":"2021-07-28T16:42:25.011069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df","metadata":{"execution":{"iopub.status.busy":"2021-07-28T16:42:47.244068Z","iopub.execute_input":"2021-07-28T16:42:47.244391Z","iopub.status.idle":"2021-07-28T16:42:47.262249Z","shell.execute_reply.started":"2021-07-28T16:42:47.244359Z","shell.execute_reply":"2021-07-28T16:42:47.261544Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2021-07-28T16:43:20.004972Z","iopub.execute_input":"2021-07-28T16:43:20.005287Z","iopub.status.idle":"2021-07-28T16:43:20.037357Z","shell.execute_reply.started":"2021-07-28T16:43:20.005257Z","shell.execute_reply":"2021-07-28T16:43:20.036592Z"},"trusted":true},"execution_count":null,"outputs":[]}]}