{"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-21T13:40:37.361148Z","iopub.execute_input":"2023-07-21T13:40:37.361612Z","iopub.status.idle":"2023-07-21T13:40:37.371799Z","shell.execute_reply.started":"2023-07-21T13:40:37.361571Z","shell.execute_reply":"2023-07-21T13:40:37.370703Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# zipファイルの解凍\n!unzip /kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip\n!unzip /kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:40:37.374348Z","iopub.execute_input":"2023-07-21T13:40:37.375275Z","iopub.status.idle":"2023-07-21T13:40:56.347696Z","shell.execute_reply.started":"2023-07-21T13:40:37.375240Z","shell.execute_reply":"2023-07-21T13:40:56.346511Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# フォルダの作製\n!mkdir data\n!mkdir data/train\n!mkdir data/train/cats\n!mkdir data/train/dogs\n!mkdir data/vali\n!mkdir data/vali/cats\n!mkdir data/vali/dogs\n\nprint(\"finish\")","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:40:56.349768Z","iopub.execute_input":"2023-07-21T13:40:56.350165Z","iopub.status.idle":"2023-07-21T13:41:03.438692Z","shell.execute_reply.started":"2023-07-21T13:40:56.350129Z","shell.execute_reply":"2023-07-21T13:41:03.437536Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 学習用画像枚数（変更可。合計は12500以下にすること）\ntrain_img = 6000\nvali_img = 3000\n\nprint(\"finish\")","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:41:03.441871Z","iopub.execute_input":"2023-07-21T13:41:03.442540Z","iopub.status.idle":"2023-07-21T13:41:03.449568Z","shell.execute_reply.started":"2023-07-21T13:41:03.442500Z","shell.execute_reply":"2023-07-21T13:41:03.448504Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# データの振り分け先指定\n# train内にdogとcatの画像が混合しているためフォルダに応じて振り分ける\n# 移動元のフォルダ\noriginal_dataset_dir = \"/kaggle/working/train\"\n# 移動先のtrain_catフォルダ\ntrain_cats_dir = \"/kaggle/working/data/train/cats\"\n# 移動先のtrain_dogフォルダ\ntrain_dogs_dir = \"/kaggle/working/data/train/dogs\"\n\nprint(\"finish\")","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:41:03.451290Z","iopub.execute_input":"2023-07-21T13:41:03.452127Z","iopub.status.idle":"2023-07-21T13:41:03.463259Z","shell.execute_reply.started":"2023-07-21T13:41:03.452094Z","shell.execute_reply":"2023-07-21T13:41:03.461892Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 画像振り分け\nimport shutil\nfnames = [\"cat.{}.jpg\".format(i) for i in range(train_img)]\n\nfor fname in fnames:\n    from_data = original_dataset_dir + \"/\" + fname\n    to_data = train_cats_dir + \"/\" + fname\n    shutil.copyfile(from_data, to_data)\n    \nfnames = [\"dog.{}.jpg\".format(i) for i in range(train_img)]\n\nfor fname in fnames:\n    from_data = original_dataset_dir + \"/\" + fname\n    to_data = train_dogs_dir + \"/\" + fname\n    shutil.copyfile(from_data, to_data)\n    \nprint(\"finish\")","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:41:03.465019Z","iopub.execute_input":"2023-07-21T13:41:03.465360Z","iopub.status.idle":"2023-07-21T13:41:04.686339Z","shell.execute_reply.started":"2023-07-21T13:41:03.465328Z","shell.execute_reply":"2023-07-21T13:41:04.685212Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"original_dataset_dir = \"/kaggle/working/train\"\n# 移動先のvalidation_catフォルダ\nvali_cats_dir = \"/kaggle/working/data/vali/cats\"\n# 移動先のvalidation_catフォルダ\nvali_dogs_dir = \"/kaggle/working/data/vali/dogs\"\n\nprint(\"finish\")","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:41:04.687950Z","iopub.execute_input":"2023-07-21T13:41:04.688633Z","iopub.status.idle":"2023-07-21T13:41:04.696483Z","shell.execute_reply.started":"2023-07-21T13:41:04.688594Z","shell.execute_reply":"2023-07-21T13:41:04.695492Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fnames = [\"cat.{}.jpg\".format(i+train_img) for i in range(vali_img)]\n\nfor fname in fnames:\n    from_data = original_dataset_dir + \"/\" + fname\n    to_data = vali_cats_dir + \"/\" + fname\n    shutil.copyfile(from_data, to_data)\n    \nfnames = [\"dog.{}.jpg\".format(i+train_img) for i in range(vali_img)]\n\nfor fname in fnames:\n    from_data = original_dataset_dir + \"/\" + fname\n    to_data = vali_dogs_dir + \"/\" + fname\n    shutil.copyfile(from_data, to_data)\n    \nprint(\"finish\")","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:41:04.698030Z","iopub.execute_input":"2023-07-21T13:41:04.699087Z","iopub.status.idle":"2023-07-21T13:41:05.564064Z","shell.execute_reply.started":"2023-07-21T13:41:04.699051Z","shell.execute_reply":"2023-07-21T13:41:05.563051Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 画像枚数の確認\nprint(\"train cat:{}\".format(len(os.listdir(train_cats_dir))))\nprint(\"train dog:{}\".format(len(os.listdir(train_dogs_dir))))\n\nprint(\"vali cat:{}\".format(len(os.listdir(vali_cats_dir))))\nprint(\"vali dog:{}\".format(len(os.listdir(vali_dogs_dir))))\n\n# train cat:2000\n# train dog:2000\n# vali cat:1000\n# vali dog:1000","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:41:05.565419Z","iopub.execute_input":"2023-07-21T13:41:05.566227Z","iopub.status.idle":"2023-07-21T13:41:05.585649Z","shell.execute_reply.started":"2023-07-21T13:41:05.566190Z","shell.execute_reply":"2023-07-21T13:41:05.584568Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport os\nimport math\nimport urllib.request\nimport zipfile\n\nfrom keras.models import Sequential, load_model, Model\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense\nfrom keras.layers import Activation, BatchNormalization, Input\nfrom tensorflow.keras.optimizers import Adam\n# from keras.optimizers import adam_v2\n# from keras.optimizers import adam_v2, sgd_experimental\nfrom keras.utils import np_utils\nfrom keras.callbacks import EarlyStopping\nfrom keras.applications.vgg16 import VGG16\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"execution":{"iopub.status.busy":"2023-07-21T16:48:04.164671Z","iopub.execute_input":"2023-07-21T16:48:04.165372Z","iopub.status.idle":"2023-07-21T16:48:04.174859Z","shell.execute_reply.started":"2023-07-21T16:48:04.165338Z","shell.execute_reply":"2023-07-21T16:48:04.173556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = VGG16(include_top=False, weights=\"imagenet\")\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:41:06.272068Z","iopub.execute_input":"2023-07-21T13:41:06.272457Z","iopub.status.idle":"2023-07-21T13:41:11.817425Z","shell.execute_reply.started":"2023-07-21T13:41:06.272419Z","shell.execute_reply":"2023-07-21T13:41:11.814342Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_vgg16 = VGG16(include_top=False, weights=\"imagenet\", input_tensor=Input(shape=(224,224,3)))\nmodel_vgg16.layers","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:41:11.820140Z","iopub.execute_input":"2023-07-21T13:41:11.821520Z","iopub.status.idle":"2023-07-21T13:41:12.405750Z","shell.execute_reply.started":"2023-07-21T13:41:11.821453Z","shell.execute_reply":"2023-07-21T13:41:12.404554Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_slass = 2\nbatch_size = 128\n\ntrain_dir = \"/kaggle/working/data/train\"\nvalid_dir = \"/kaggle/working/data/vali\"\n\n# データ拡張しながら，テンソル画像データのバッチを生成\ntrain_data_generator = ImageDataGenerator(rescale=1.0/255,\n                                          rotation_range=45,\n                                          width_shift_range=0.2,\n                                          height_shift_range=0.2,\n                                          shear_range=math.pi/4,\n                                          zoom_range=0.5,\n                                          horizontal_flip=True)\n\nvalid_data_generator = ImageDataGenerator(rescale=1.0/255)\n\n# ディレクトリからデータを生成\ntrain_generator = train_data_generator.flow_from_directory(\n    train_dir,\n    target_size=(224,224),\n    batch_size=batch_size,\n    class_mode=\"binary\",\n    shuffle=False\n)\n\nvalid_generator = valid_data_generator.flow_from_directory(\n    valid_dir,\n    target_size=(224,224),\n    batch_size=batch_size,\n    class_mode=\"binary\",\n    shuffle=False\n)\n","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:41:12.407262Z","iopub.execute_input":"2023-07-21T13:41:12.408849Z","iopub.status.idle":"2023-07-21T13:41:13.041565Z","shell.execute_reply.started":"2023-07-21T13:41:12.408791Z","shell.execute_reply":"2023-07-21T13:41:13.040525Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# VGG16をインポート\nmodel_vgg16 = VGG16(include_top=False, weights=\"imagenet\", input_tensor=Input(shape=(224,224,3)))\n\n# 全結合層を作成\nx = model_vgg16.output\nx = Flatten()(x)\nx = Dense(256)(x)\nx = Activation(\"relu\")(x)\nx = Dropout(0.5)(x)\nprediction = Dense(1, activation=\"sigmoid\")(x)\n\n# モデル合体\nmodel = Model(inputs=model_vgg16.input, outputs=prediction)","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:41:13.045775Z","iopub.execute_input":"2023-07-21T13:41:13.048187Z","iopub.status.idle":"2023-07-21T13:41:13.523915Z","shell.execute_reply.started":"2023-07-21T13:41:13.048153Z","shell.execute_reply":"2023-07-21T13:41:13.522968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 浅い層の重みはそのまま使いたいので、block4_pool(14層目)までの重みの更新をキャンセル\nfor layer in model_vgg16.layers[:15]:\n  layer.trainable=False\n\n# 学習の設定\nmodel.compile(loss=\"binary_crossentropy\",\n              optimizer=Adam(learning_rate=0.0001),\n              metrics=[\"accuracy\"])\n\n# model.compile(loss=\"binary_crossentropy\",\n#               optimizer=sgd_experimental.SGD(learning_rate=0.001, momentum=0.9),\n#               metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:41:13.528608Z","iopub.execute_input":"2023-07-21T13:41:13.530891Z","iopub.status.idle":"2023-07-21T13:41:13.555214Z","shell.execute_reply.started":"2023-07-21T13:41:13.530855Z","shell.execute_reply":"2023-07-21T13:41:13.553876Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 学習\nhistory = model.fit(train_generator,\n                    epochs=50,\n                    verbose=1,\n                    validation_data=valid_generator,\n                    callbacks=[EarlyStopping(patience=10)])\n\n# モデル保存\nmodel.save(\"/kaggle/working/data/CNN_VGG16.h5\")","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:41:13.559602Z","iopub.execute_input":"2023-07-21T13:41:13.561888Z","iopub.status.idle":"2023-07-21T16:45:35.448059Z","shell.execute_reply.started":"2023-07-21T13:41:13.561853Z","shell.execute_reply":"2023-07-21T16:45:35.446995Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# lossとaccuracyを可視化\nprint(\"-\"*100)\nplt.figure(1, figsize=(13,4))\nplt.subplots_adjust(wspace=0.5)\n\n# 学習曲線\nplt.subplot(1, 2, 1)\nplt.plot(history.history[\"loss\"], label=\"train\")\nplt.plot(history.history[\"val_loss\"], label=\"valid\")\nplt.title(\"train and valid loss\")\nplt.xlabel(\"epoch\")\nplt.ylabel(\"loss\")\nplt.legend()\nplt.grid()\n\n# 精度表示\nplt.subplot(1, 2, 2)\nplt.plot(history.history[\"accuracy\"], label=\"train\")\nplt.plot(history.history[\"val_accuracy\"], label=\"valid\")\nplt.title(\"train and valid accuracy\")\nplt.xlabel(\"epoch\")\nplt.ylabel(\"accuracy\")\nplt.legend()\nplt.grid()\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-07-21T16:45:35.449753Z","iopub.execute_input":"2023-07-21T16:45:35.450150Z","iopub.status.idle":"2023-07-21T16:45:35.994092Z","shell.execute_reply.started":"2023-07-21T16:45:35.450115Z","shell.execute_reply":"2023-07-21T16:45:35.993129Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import keras.utils as image\nfrom keras.utils import load_img, img_to_array\nimport re\nimport csv\nimport glob\n\n# テストデータのパスを取得\np = re.compile(r'\\d+')\nimcount = 1\ntest_list = glob.glob('/kaggle/working/test/*.jpg')\ntest_list = sorted(test_list,key=lambda s: int(p.search(s).group()))\n\n#モデルの読み込み\nmodel = load_model(\"/kaggle/working/data/CNN_VGG16.h5\")\n\n#csv書き込み（テストデータ1～テストデータ6250）\nwith open('../working/submission.csv', 'w') as f:\n  writer= csv.writer(f, lineterminator='\\n')\n  writer.writerow(['id', 'label'])\n  for i in range(6250):\n    j = test_list[i]\n    img = image.load_img(j, target_size=(224, 224))\n    x = img_to_array(img)\n    x = np.expand_dims(x, axis=0)\n    x = x / 255.0\n    result_predict = model.predict(x)\n    writer.writerow([imcount, result_predict[0][0]])\n    imcount += 1\n    print(i)\n\nprint(\"finish\")","metadata":{"execution":{"iopub.status.busy":"2023-07-21T16:51:20.316002Z","iopub.execute_input":"2023-07-21T16:51:20.316386Z","iopub.status.idle":"2023-07-21T16:59:07.826261Z","shell.execute_reply.started":"2023-07-21T16:51:20.316354Z","shell.execute_reply":"2023-07-21T16:59:07.825306Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#csv書き込み（テストデータ6250～テストデータ12500）\nwith open('../working/submission.csv', 'a') as f:\n  writer= csv.writer(f, lineterminator='\\n')\n  for i in range(6250, 12500):\n    j = test_list[i]\n    img = image.load_img(j, target_size=(224, 224))\n    x = img_to_array(img)\n    x = np.expand_dims(x, axis=0)\n    x = x / 255.0\n    result_predict = model.predict(x)\n    writer.writerow([imcount, result_predict[0][0]])\n    imcount += 1\n    print(i)\n\nprint(\"finish\")","metadata":{"execution":{"iopub.status.busy":"2023-07-21T17:01:38.624138Z","iopub.execute_input":"2023-07-21T17:01:38.624536Z","iopub.status.idle":"2023-07-21T17:09:30.345572Z","shell.execute_reply.started":"2023-07-21T17:01:38.624504Z","shell.execute_reply":"2023-07-21T17:09:30.344546Z"},"trusted":true},"execution_count":null,"outputs":[]}]}