{"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-22T07:54:04.458962Z","iopub.execute_input":"2022-07-22T07:54:04.459704Z","iopub.status.idle":"2022-07-22T07:54:04.484957Z","shell.execute_reply.started":"2022-07-22T07:54:04.459592Z","shell.execute_reply":"2022-07-22T07:54:04.483957Z"},"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-22T07:54:11.951319Z","iopub.execute_input":"2022-07-22T07:54:11.951675Z","iopub.status.idle":"2022-07-22T07:54:29.871717Z","shell.execute_reply.started":"2022-07-22T07:54:11.951626Z","shell.execute_reply":"2022-07-22T07:54:29.866337Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd train","metadata":{"execution":{"iopub.status.busy":"2022-07-22T07:54:34.672472Z","iopub.execute_input":"2022-07-22T07:54:34.672827Z","iopub.status.idle":"2022-07-22T07:54:34.678841Z","shell.execute_reply.started":"2022-07-22T07:54:34.672798Z","shell.execute_reply":"2022-07-22T07:54:34.677809Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir cats","metadata":{"execution":{"iopub.status.busy":"2022-07-22T07:54:36.832602Z","iopub.execute_input":"2022-07-22T07:54:36.833246Z","iopub.status.idle":"2022-07-22T07:54:37.510667Z","shell.execute_reply.started":"2022-07-22T07:54:36.833214Z","shell.execute_reply":"2022-07-22T07:54:37.509464Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir dogs","metadata":{"execution":{"iopub.status.busy":"2022-07-22T07:54:41.633433Z","iopub.execute_input":"2022-07-22T07:54:41.633819Z","iopub.status.idle":"2022-07-22T07:54:42.312845Z","shell.execute_reply.started":"2022-07-22T07:54:41.633779Z","shell.execute_reply":"2022-07-22T07:54:42.311602Z"},"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-22T07:54:47.031950Z","iopub.execute_input":"2022-07-22T07:54:47.032573Z","iopub.status.idle":"2022-07-22T07:54:47.962382Z","shell.execute_reply.started":"2022-07-22T07:54:47.032537Z","shell.execute_reply":"2022-07-22T07:54:47.961387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd ../","metadata":{"execution":{"iopub.status.busy":"2022-07-22T07:54:54.674454Z","iopub.execute_input":"2022-07-22T07:54:54.675076Z","iopub.status.idle":"2022-07-22T07:54:54.680999Z","shell.execute_reply.started":"2022-07-22T07:54:54.675041Z","shell.execute_reply":"2022-07-22T07:54:54.680075Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir valid","metadata":{"execution":{"iopub.status.busy":"2022-07-22T07:55:04.960646Z","iopub.execute_input":"2022-07-22T07:55:04.961252Z","iopub.status.idle":"2022-07-22T07:55:05.639828Z","shell.execute_reply.started":"2022-07-22T07:55:04.961197Z","shell.execute_reply":"2022-07-22T07:55:05.638469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd valid","metadata":{"execution":{"iopub.status.busy":"2022-07-22T07:55:13.013841Z","iopub.execute_input":"2022-07-22T07:55:13.014466Z","iopub.status.idle":"2022-07-22T07:55:13.020598Z","shell.execute_reply.started":"2022-07-22T07:55:13.014429Z","shell.execute_reply":"2022-07-22T07:55:13.019563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir cats","metadata":{"execution":{"iopub.status.busy":"2022-07-22T07:55:19.235340Z","iopub.execute_input":"2022-07-22T07:55:19.235736Z","iopub.status.idle":"2022-07-22T07:55:19.918953Z","shell.execute_reply.started":"2022-07-22T07:55:19.235704Z","shell.execute_reply":"2022-07-22T07:55:19.917713Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mkdir dogs","metadata":{"execution":{"iopub.status.busy":"2022-07-22T07:55:28.284409Z","iopub.execute_input":"2022-07-22T07:55:28.284807Z","iopub.status.idle":"2022-07-22T07:55:29.088289Z","shell.execute_reply.started":"2022-07-22T07:55:28.284772Z","shell.execute_reply":"2022-07-22T07:55:29.087061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd ../","metadata":{"execution":{"iopub.status.busy":"2022-07-22T07:55:35.792931Z","iopub.execute_input":"2022-07-22T07:55:35.793303Z","iopub.status.idle":"2022-07-22T07:55:35.800813Z","shell.execute_reply.started":"2022-07-22T07:55:35.793269Z","shell.execute_reply":"2022-07-22T07:55:35.799603Z"},"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-22T07:55:52.462477Z","iopub.execute_input":"2022-07-22T07:55:52.462845Z","iopub.status.idle":"2022-07-22T07:55:52.500725Z","shell.execute_reply.started":"2022-07-22T07:55:52.462815Z","shell.execute_reply":"2022-07-22T07:55:52.499755Z"},"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-22T07:56:07.624711Z","iopub.execute_input":"2022-07-22T07:56:07.625670Z","iopub.status.idle":"2022-07-22T07:57:52.395975Z","shell.execute_reply.started":"2022-07-22T07:56:07.625607Z","shell.execute_reply":"2022-07-22T07:57:52.394826Z"},"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-22T07:57:56.950259Z","iopub.execute_input":"2022-07-22T07:57:56.950596Z","iopub.status.idle":"2022-07-22T07:58:01.716228Z","shell.execute_reply.started":"2022-07-22T07:57:56.950568Z","shell.execute_reply":"2022-07-22T07:58:01.715181Z"},"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-22T07:58:04.820611Z","iopub.execute_input":"2022-07-22T07:58:04.822026Z","iopub.status.idle":"2022-07-22T07:58:04.827369Z","shell.execute_reply.started":"2022-07-22T07:58:04.821974Z","shell.execute_reply":"2022-07-22T07:58:04.826115Z"},"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-22T07:58:16.885339Z","iopub.execute_input":"2022-07-22T07:58:16.886307Z","iopub.status.idle":"2022-07-22T07:58:17.969876Z","shell.execute_reply.started":"2022-07-22T07:58:16.886261Z","shell.execute_reply":"2022-07-22T07:58:17.968957Z"},"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-22T07:58:21.074081Z","iopub.execute_input":"2022-07-22T07:58:21.074426Z","iopub.status.idle":"2022-07-22T07:58:23.703374Z","shell.execute_reply.started":"2022-07-22T07:58:21.074398Z","shell.execute_reply":"2022-07-22T07:58:23.702423Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-07-22T07:58:42.646478Z","iopub.execute_input":"2022-07-22T07:58:42.646851Z","iopub.status.idle":"2022-07-22T07:58:42.655602Z","shell.execute_reply.started":"2022-07-22T07:58:42.646819Z","shell.execute_reply":"2022-07-22T07:58:42.653207Z"},"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-22T07:58:46.135015Z","iopub.execute_input":"2022-07-22T07:58:46.135396Z","iopub.status.idle":"2022-07-22T08:43:14.414332Z","shell.execute_reply.started":"2022-07-22T07:58:46.135366Z","shell.execute_reply":"2022-07-22T08:43:14.413359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save(\"model.h5\")","metadata":{"execution":{"iopub.status.busy":"2022-07-22T08:43:36.788632Z","iopub.execute_input":"2022-07-22T08:43:36.789573Z","iopub.status.idle":"2022-07-22T08:43:36.900434Z","shell.execute_reply.started":"2022-07-22T08:43:36.789526Z","shell.execute_reply":"2022-07-22T08:43:36.899180Z"},"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-22T08:43:39.669753Z","iopub.execute_input":"2022-07-22T08:43:39.670135Z","iopub.status.idle":"2022-07-22T08:43:40.063341Z","shell.execute_reply.started":"2022-07-22T08:43:39.670106Z","shell.execute_reply":"2022-07-22T08:43:40.062480Z"},"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-22T08:43:48.752952Z","iopub.execute_input":"2022-07-22T08:43:48.753295Z","iopub.status.idle":"2022-07-22T08:43:48.759109Z","shell.execute_reply.started":"2022-07-22T08:43:48.753266Z","shell.execute_reply":"2022-07-22T08:43:48.757955Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"new_model = load_model('model.h5')","metadata":{"execution":{"iopub.status.busy":"2022-07-22T08:43:52.722554Z","iopub.execute_input":"2022-07-22T08:43:52.723052Z","iopub.status.idle":"2022-07-22T08:43:53.024538Z","shell.execute_reply.started":"2022-07-22T08:43:52.723008Z","shell.execute_reply":"2022-07-22T08:43:53.023154Z"},"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-22T08:43:54.978315Z","iopub.execute_input":"2022-07-22T08:43:54.978783Z","iopub.status.idle":"2022-07-22T08:52:49.243137Z","shell.execute_reply.started":"2022-07-22T08:43:54.978739Z","shell.execute_reply":"2022-07-22T08:52:49.242055Z"},"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-22T08:53:04.221102Z","iopub.execute_input":"2022-07-22T08:53:04.221442Z","iopub.status.idle":"2022-07-22T08:53:04.227955Z","shell.execute_reply.started":"2022-07-22T08:53:04.221414Z","shell.execute_reply":"2022-07-22T08:53:04.226722Z"},"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-22T08:53:07.029673Z","iopub.execute_input":"2022-07-22T08:53:07.030298Z","iopub.status.idle":"2022-07-22T08:53:09.079886Z","shell.execute_reply.started":"2022-07-22T08:53:07.030266Z","shell.execute_reply":"2022-07-22T08:53:09.078867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df","metadata":{"execution":{"iopub.status.busy":"2022-07-22T08:53:37.875478Z","iopub.execute_input":"2022-07-22T08:53:37.876115Z","iopub.status.idle":"2022-07-22T08:53:37.895386Z","shell.execute_reply.started":"2022-07-22T08:53:37.876075Z","shell.execute_reply":"2022-07-22T08:53:37.894439Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2022-07-22T08:53:46.488749Z","iopub.execute_input":"2022-07-22T08:53:46.489321Z","iopub.status.idle":"2022-07-22T08:53:46.537369Z","shell.execute_reply.started":"2022-07-22T08:53:46.489278Z","shell.execute_reply":"2022-07-22T08:53:46.536175Z"},"trusted":true},"execution_count":null,"outputs":[]}]}