{"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":"2022-07-23T05:23:48.340609Z","iopub.execute_input":"2022-07-23T05:23:48.341422Z","iopub.status.idle":"2022-07-23T05:23:48.371175Z","shell.execute_reply.started":"2022-07-23T05:23:48.341327Z","shell.execute_reply":"2022-07-23T05:23:48.370236Z"},"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":"2022-07-23T05:23:48.373253Z","iopub.execute_input":"2022-07-23T05:23:48.374014Z","iopub.status.idle":"2022-07-23T05:24:06.506251Z","shell.execute_reply.started":"2022-07-23T05:23:48.373971Z","shell.execute_reply":"2022-07-23T05:24:06.505166Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd train","metadata":{"execution":{"iopub.status.busy":"2022-07-23T05:24:06.508128Z","iopub.execute_input":"2022-07-23T05:24:06.508741Z","iopub.status.idle":"2022-07-23T05:24:06.515529Z","shell.execute_reply.started":"2022-07-23T05:24:06.508702Z","shell.execute_reply":"2022-07-23T05:24:06.514509Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir cats","metadata":{"execution":{"iopub.status.busy":"2022-07-23T05:24:06.518304Z","iopub.execute_input":"2022-07-23T05:24:06.518916Z","iopub.status.idle":"2022-07-23T05:24:07.179524Z","shell.execute_reply.started":"2022-07-23T05:24:06.518875Z","shell.execute_reply":"2022-07-23T05:24:07.178323Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir dogs","metadata":{"execution":{"iopub.status.busy":"2022-07-23T05:24:07.181270Z","iopub.execute_input":"2022-07-23T05:24:07.181882Z","iopub.status.idle":"2022-07-23T05:24:07.838969Z","shell.execute_reply.started":"2022-07-23T05:24:07.181838Z","shell.execute_reply":"2022-07-23T05:24:07.837712Z"},"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":"2022-07-23T05:24:07.840810Z","iopub.execute_input":"2022-07-23T05:24:07.841220Z","iopub.status.idle":"2022-07-23T05:24:08.769734Z","shell.execute_reply.started":"2022-07-23T05:24:07.841178Z","shell.execute_reply":"2022-07-23T05:24:08.768749Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd ../","metadata":{"execution":{"iopub.status.busy":"2022-07-23T05:24:08.771241Z","iopub.execute_input":"2022-07-23T05:24:08.771592Z","iopub.status.idle":"2022-07-23T05:24:08.780115Z","shell.execute_reply.started":"2022-07-23T05:24:08.771554Z","shell.execute_reply":"2022-07-23T05:24:08.779154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir valid","metadata":{"execution":{"iopub.status.busy":"2022-07-23T05:24:08.781910Z","iopub.execute_input":"2022-07-23T05:24:08.782260Z","iopub.status.idle":"2022-07-23T05:24:09.442978Z","shell.execute_reply.started":"2022-07-23T05:24:08.782226Z","shell.execute_reply":"2022-07-23T05:24:09.441832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd valid","metadata":{"execution":{"iopub.status.busy":"2022-07-23T05:24:09.447682Z","iopub.execute_input":"2022-07-23T05:24:09.448058Z","iopub.status.idle":"2022-07-23T05:24:09.460134Z","shell.execute_reply.started":"2022-07-23T05:24:09.448005Z","shell.execute_reply":"2022-07-23T05:24:09.457228Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir cats","metadata":{"execution":{"iopub.status.busy":"2022-07-23T05:24:09.464260Z","iopub.execute_input":"2022-07-23T05:24:09.465737Z","iopub.status.idle":"2022-07-23T05:24:10.327262Z","shell.execute_reply.started":"2022-07-23T05:24:09.465701Z","shell.execute_reply":"2022-07-23T05:24:10.323624Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir dogs","metadata":{"execution":{"iopub.status.busy":"2022-07-23T05:24:10.330541Z","iopub.execute_input":"2022-07-23T05:24:10.330917Z","iopub.status.idle":"2022-07-23T05:24:11.079724Z","shell.execute_reply.started":"2022-07-23T05:24:10.330877Z","shell.execute_reply":"2022-07-23T05:24:11.078280Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd ../","metadata":{"execution":{"iopub.status.busy":"2022-07-23T05:24:11.082294Z","iopub.execute_input":"2022-07-23T05:24:11.083073Z","iopub.status.idle":"2022-07-23T05:24:11.089418Z","shell.execute_reply.started":"2022-07-23T05:24:11.083020Z","shell.execute_reply":"2022-07-23T05:24:11.088303Z"},"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":"2022-07-23T05:24:11.090924Z","iopub.execute_input":"2022-07-23T05:24:11.091801Z","iopub.status.idle":"2022-07-23T05:24:11.310294Z","shell.execute_reply.started":"2022-07-23T05:24:11.091704Z","shell.execute_reply":"2022-07-23T05:24:11.309440Z"},"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":"2022-07-23T05:24:11.311792Z","iopub.execute_input":"2022-07-23T05:24:11.312165Z","iopub.status.idle":"2022-07-23T05:25:53.715599Z","shell.execute_reply.started":"2022-07-23T05:24:11.312128Z","shell.execute_reply":"2022-07-23T05:25:53.714604Z"},"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\nfrom tensorflow.keras.optimizers import Adam\nimport os\nimport datetime\nimport tensorflow as tf","metadata":{"execution":{"iopub.status.busy":"2022-07-23T05:25:53.716879Z","iopub.execute_input":"2022-07-23T05:25:53.717242Z","iopub.status.idle":"2022-07-23T05:25:59.382464Z","shell.execute_reply.started":"2022-07-23T05:25:53.717207Z","shell.execute_reply":"2022-07-23T05:25:59.381482Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data_dir = 'train'\nvalid_data_dir = 'valid'","metadata":{"execution":{"iopub.status.busy":"2022-07-23T05:25:59.384095Z","iopub.execute_input":"2022-07-23T05:25:59.384797Z","iopub.status.idle":"2022-07-23T05:25:59.389730Z","shell.execute_reply.started":"2022-07-23T05:25:59.384756Z","shell.execute_reply":"2022-07-23T05:25:59.388942Z"},"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":"2022-07-23T05:25:59.390919Z","iopub.execute_input":"2022-07-23T05:25:59.391448Z","iopub.status.idle":"2022-07-23T05:26:00.584250Z","shell.execute_reply.started":"2022-07-23T05:25:59.391409Z","shell.execute_reply":"2022-07-23T05:26:00.583184Z"},"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":"2022-07-23T05:26:00.585855Z","iopub.execute_input":"2022-07-23T05:26:00.586276Z","iopub.status.idle":"2022-07-23T05:26:03.516078Z","shell.execute_reply.started":"2022-07-23T05:26:00.586235Z","shell.execute_reply":"2022-07-23T05:26:03.515030Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-07-23T05:26:03.517654Z","iopub.execute_input":"2022-07-23T05:26:03.518257Z","iopub.status.idle":"2022-07-23T05:26:03.526266Z","shell.execute_reply.started":"2022-07-23T05:26:03.518218Z","shell.execute_reply":"2022-07-23T05:26:03.525216Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(train_generator, \n                    epochs=10, \n                    verbose=1, \n                    validation_data=(valid_generator), \n                    steps_per_epoch=20000 / 64, \n                    validation_steps=5000/64)","metadata":{"execution":{"iopub.status.busy":"2022-07-23T05:26:03.528172Z","iopub.execute_input":"2022-07-23T05:26:03.528670Z","iopub.status.idle":"2022-07-23T06:08:54.748666Z","shell.execute_reply.started":"2022-07-23T05:26:03.528633Z","shell.execute_reply":"2022-07-23T06:08:54.747569Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save(\"model.h5\")","metadata":{"execution":{"iopub.status.busy":"2022-07-23T06:08:54.750323Z","iopub.execute_input":"2022-07-23T06:08:54.750927Z","iopub.status.idle":"2022-07-23T06:08:54.852941Z","shell.execute_reply.started":"2022-07-23T06:08:54.750887Z","shell.execute_reply":"2022-07-23T06:08:54.851984Z"},"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":"2022-07-23T06:08:54.854772Z","iopub.execute_input":"2022-07-23T06:08:54.855191Z","iopub.status.idle":"2022-07-23T06:08:55.228534Z","shell.execute_reply.started":"2022-07-23T06:08:54.855129Z","shell.execute_reply":"2022-07-23T06:08:55.227652Z"},"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":"2022-07-23T06:08:55.229958Z","iopub.execute_input":"2022-07-23T06:08:55.230333Z","iopub.status.idle":"2022-07-23T06:08:55.235290Z","shell.execute_reply.started":"2022-07-23T06:08:55.230297Z","shell.execute_reply":"2022-07-23T06:08:55.234264Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"new_model = load_model('model.h5')","metadata":{"execution":{"iopub.status.busy":"2022-07-23T06:08:55.241565Z","iopub.execute_input":"2022-07-23T06:08:55.241900Z","iopub.status.idle":"2022-07-23T06:08:55.413718Z","shell.execute_reply.started":"2022-07-23T06:08:55.241864Z","shell.execute_reply":"2022-07-23T06:08:55.412624Z"},"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":"2022-07-23T06:08:55.415095Z","iopub.execute_input":"2022-07-23T06:08:55.415480Z","iopub.status.idle":"2022-07-23T06:17:05.129704Z","shell.execute_reply.started":"2022-07-23T06:08:55.415442Z","shell.execute_reply":"2022-07-23T06:17:05.128763Z"},"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":"2022-07-23T06:17:05.131288Z","iopub.execute_input":"2022-07-23T06:17:05.131615Z","iopub.status.idle":"2022-07-23T06:17:05.138212Z","shell.execute_reply.started":"2022-07-23T06:17:05.131580Z","shell.execute_reply":"2022-07-23T06:17:05.137156Z"},"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":"2022-07-23T06:17:05.139889Z","iopub.execute_input":"2022-07-23T06:17:05.140542Z","iopub.status.idle":"2022-07-23T06:17:06.521838Z","shell.execute_reply.started":"2022-07-23T06:17:05.140507Z","shell.execute_reply":"2022-07-23T06:17:06.520890Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df","metadata":{"execution":{"iopub.status.busy":"2022-07-23T06:17:06.525606Z","iopub.execute_input":"2022-07-23T06:17:06.526157Z","iopub.status.idle":"2022-07-23T06:17:06.541644Z","shell.execute_reply.started":"2022-07-23T06:17:06.526118Z","shell.execute_reply":"2022-07-23T06:17:06.540535Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2022-07-23T06:17:06.543148Z","iopub.execute_input":"2022-07-23T06:17:06.543526Z","iopub.status.idle":"2022-07-23T06:17:06.571835Z","shell.execute_reply.started":"2022-07-23T06:17:06.543478Z","shell.execute_reply":"2022-07-23T06:17:06.570842Z"},"trusted":true},"execution_count":null,"outputs":[]}]}