{"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-28T14:19:11.486565Z","iopub.execute_input":"2023-07-28T14:19:11.487594Z","iopub.status.idle":"2023-07-28T14:19:11.522255Z","shell.execute_reply.started":"2023-07-28T14:19:11.487549Z","shell.execute_reply":"2023-07-28T14:19:11.510050Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"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-28T14:19:11.524326Z","iopub.execute_input":"2023-07-28T14:19:11.524650Z","iopub.status.idle":"2023-07-28T14:19:36.175636Z","shell.execute_reply.started":"2023-07-28T14:19:11.524618Z","shell.execute_reply":"2023-07-28T14:19:36.174325Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-07-28T14:19:36.177800Z","iopub.execute_input":"2023-07-28T14:19:36.178677Z","iopub.status.idle":"2023-07-28T14:19:36.187463Z","shell.execute_reply.started":"2023-07-28T14:19:36.178621Z","shell.execute_reply":"2023-07-28T14:19:36.186515Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"フォルダの作製","metadata":{}},{"cell_type":"code","source":"!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-28T14:19:36.190585Z","iopub.execute_input":"2023-07-28T14:19:36.191336Z","iopub.status.idle":"2023-07-28T14:19:43.448059Z","shell.execute_reply.started":"2023-07-28T14:19:36.191302Z","shell.execute_reply":"2023-07-28T14:19:43.446698Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**画像の分別**\ntrain内にdogとcatの画像が混合しているためフォルダに応じて振り分ける","metadata":{}},{"cell_type":"code","source":"# 学習用画像枚数（変更可。合計は12500以下にすること）\ntrain_img = 11000\nvali_img = 1500\n\nprint(\"finish\")","metadata":{"execution":{"iopub.status.busy":"2023-07-28T14:19:43.449753Z","iopub.execute_input":"2023-07-28T14:19:43.450267Z","iopub.status.idle":"2023-07-28T14:19:43.456441Z","shell.execute_reply.started":"2023-07-28T14:19:43.450225Z","shell.execute_reply":"2023-07-28T14:19:43.455397Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 移動元のフォルダ\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-28T14:23:27.887609Z","iopub.execute_input":"2023-07-28T14:23:27.888015Z","iopub.status.idle":"2023-07-28T14:23:27.894090Z","shell.execute_reply.started":"2023-07-28T14:23:27.887964Z","shell.execute_reply":"2023-07-28T14:23:27.892804Z"},"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-28T14:23:30.996458Z","iopub.execute_input":"2023-07-28T14:23:30.996833Z","iopub.status.idle":"2023-07-28T14:23:34.840540Z","shell.execute_reply.started":"2023-07-28T14:23:30.996803Z","shell.execute_reply":"2023-07-28T14:23:34.839286Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 移動元のフォルダ\noriginal_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-28T14:23:38.172781Z","iopub.execute_input":"2023-07-28T14:23:38.173158Z","iopub.status.idle":"2023-07-28T14:23:38.179515Z","shell.execute_reply.started":"2023-07-28T14:23:38.173128Z","shell.execute_reply":"2023-07-28T14:23:38.178216Z"},"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-28T14:23:42.837303Z","iopub.execute_input":"2023-07-28T14:23:42.837745Z","iopub.status.idle":"2023-07-28T14:23:43.328813Z","shell.execute_reply.started":"2023-07-28T14:23:42.837708Z","shell.execute_reply":"2023-07-28T14:23:43.327692Z"},"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))))","metadata":{"execution":{"iopub.status.busy":"2023-07-28T14:23:47.332181Z","iopub.execute_input":"2023-07-28T14:23:47.332549Z","iopub.status.idle":"2023-07-28T14:23:47.356963Z","shell.execute_reply.started":"2023-07-28T14:23:47.332519Z","shell.execute_reply":"2023-07-28T14:23:47.355954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"ライブラリのインポート","metadata":{}},{"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\nimport tensorflow as tf","metadata":{"execution":{"iopub.status.busy":"2023-07-28T14:23:49.795966Z","iopub.execute_input":"2023-07-28T14:23:49.796740Z","iopub.status.idle":"2023-07-28T14:23:49.805959Z","shell.execute_reply.started":"2023-07-28T14:23:49.796705Z","shell.execute_reply":"2023-07-28T14:23:49.804926Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"VGG16モデルの取得","metadata":{}},{"cell_type":"code","source":"# モデルの取得\nmodel = VGG16(include_top=False, weights=\"imagenet\")\n# モデル構造の確認\nmodel.summary()\n","metadata":{"execution":{"iopub.status.busy":"2023-07-28T14:23:54.997322Z","iopub.execute_input":"2023-07-28T14:23:54.997710Z","iopub.status.idle":"2023-07-28T14:23:55.372488Z","shell.execute_reply.started":"2023-07-28T14:23:54.997680Z","shell.execute_reply":"2023-07-28T14:23:55.371682Z"},"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-28T14:23:58.229826Z","iopub.execute_input":"2023-07-28T14:23:58.230227Z","iopub.status.idle":"2023-07-28T14:23:58.554991Z","shell.execute_reply.started":"2023-07-28T14:23:58.230194Z","shell.execute_reply":"2023-07-28T14:23:58.553906Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"学習データの作成","metadata":{}},{"cell_type":"code","source":"num_slass = 2\nbatch_size = 128\n\n# 学習データのパス\ntrain_dir = \"/kaggle/working/data/train\"\nvalid_dir = \"/kaggle/working/data/vali\"\n\n# データ拡張しながら，テンソル画像データのバッチを生成\n# データ拡張\ntrain_data_generator = ImageDataGenerator(rescale=1.0/255,\n                                          rotation_range=45,\n                                          horizontal_flip=True,\n                                          vertical_flip=True,\n                                          width_shift_range=0.2,\n                                          height_shift_range=0.2,\n                                          shear_range=math.pi/4,\n                                          zoom_range=0.5)\n\nvalid_data_generator = ImageDataGenerator(rescale=1.0/255)\n\n# ディレクトリからデータを生成\n# 画像サイズはVGG16モデルにならい、(224.224)\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-28T14:24:01.006795Z","iopub.execute_input":"2023-07-28T14:24:01.007207Z","iopub.status.idle":"2023-07-28T14:24:01.781431Z","shell.execute_reply.started":"2023-07-28T14:24:01.007176Z","shell.execute_reply":"2023-07-28T14:24:01.780505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"モデル構築\n新しく全結合層を作成し、VGG16と合体させる","metadata":{}},{"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)\n","metadata":{"execution":{"iopub.status.busy":"2023-07-28T14:24:07.964670Z","iopub.execute_input":"2023-07-28T14:24:07.965284Z","iopub.status.idle":"2023-07-28T14:24:08.413641Z","shell.execute_reply.started":"2023-07-28T14:24:07.965243Z","shell.execute_reply":"2023-07-28T14:24:08.412326Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"ファインチューニング","metadata":{}},{"cell_type":"code","source":"# block4_pool(14層目)までの重みの更新をキャンセルし、浅い層の重みはそのまま使用する\nfor layer in model_vgg16.layers[:15]:\n  layer.trainable=False\n\n# 学習の設定\n# 損失はコンペのスコアと同様にクロスエントロピー損失を使用\nmodel.compile(loss=\"binary_crossentropy\",\n              optimizer=Adam(learning_rate=0.0001),\n              metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2023-07-28T14:24:19.023491Z","iopub.execute_input":"2023-07-28T14:24:19.023892Z","iopub.status.idle":"2023-07-28T14:24:19.037857Z","shell.execute_reply.started":"2023-07-28T14:24:19.023862Z","shell.execute_reply":"2023-07-28T14:24:19.036910Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"学習","metadata":{}},{"cell_type":"code","source":"# 学習\nhistory = model.fit(train_generator,\n                    epochs=10,\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-28T14:24:21.264192Z","iopub.execute_input":"2023-07-28T14:24:21.264962Z","iopub.status.idle":"2023-07-28T15:24:15.927429Z","shell.execute_reply.started":"2023-07-28T14:24:21.264909Z","shell.execute_reply":"2023-07-28T15:24:15.926329Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"lossとaccuracyを可視化","metadata":{}},{"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()\n","metadata":{"execution":{"iopub.status.busy":"2023-07-28T15:24:23.727387Z","iopub.execute_input":"2023-07-28T15:24:23.727761Z","iopub.status.idle":"2023-07-28T15:24:24.350920Z","shell.execute_reply.started":"2023-07-28T15:24:23.727731Z","shell.execute_reply":"2023-07-28T15:24:24.349956Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"submission.csvの書き出し","metadata":{}},{"cell_type":"code","source":"import keras.utils as image\nfrom keras.utils import load_img, img_to_array\nimport re\nimport csv\nimport glob\nfrom keras import models\n# テストデータのパスを取得\np = re.compile(r'\\d+')\nimcount = 1\ntest_list = glob.glob('/kaggle/working/test/*.jpg')\n# 画像パスをソートする\ntest_list = sorted(test_list,key=lambda s: int(p.search(s).group()))\n\n#モデルの読み込み\n# model_vgg = models.load_model('/kaggle/working/data/CNN_VGG16.h5')\n# print(\"load model\")\n\n#csv書き込み（テストデータ1～テストデータ6250）\nwith open('/kaggle/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    # 画像パスの取得\n    j = test_list[i]\n    # 画像読み込み\n    img = image.load_img(j, target_size=(224, 224))\n    # PIL 形式から ndarray に変換する\n    x = img_to_array(img)\n    # 次元の追加\n    x = np.expand_dims(x, axis=0)\n    # 正規化\n    x = x / 255.0\n    # 学習したモデルを用いて予測\n    result_predict = model.predict(x)\n    # csvファイルに書き込み\n    writer.writerow([imcount, result_predict[0][0]])\n    imcount += 1\n    print(result_predict[0][0])\n\nprint(\"finish\")","metadata":{"execution":{"iopub.status.busy":"2023-07-28T15:24:31.466081Z","iopub.execute_input":"2023-07-28T15:24:31.466567Z","iopub.status.idle":"2023-07-28T15:32:06.386594Z","shell.execute_reply.started":"2023-07-28T15:24:31.466523Z","shell.execute_reply":"2023-07-28T15:32:06.385651Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#csv書き込み（テストデータ6250～テストデータ12500）\nwith open('/kaggle/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-28T15:38:20.130571Z","iopub.execute_input":"2023-07-28T15:38:20.130992Z","iopub.status.idle":"2023-07-28T15:45:56.486778Z","shell.execute_reply.started":"2023-07-28T15:38:20.130947Z","shell.execute_reply":"2023-07-28T15:45:56.485686Z"},"trusted":true},"execution_count":null,"outputs":[]}]}