{"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-30T23:52:24.150016Z","iopub.execute_input":"2023-07-30T23:52:24.150480Z","iopub.status.idle":"2023-07-30T23:52:24.161938Z","shell.execute_reply.started":"2023-07-30T23:52:24.150446Z","shell.execute_reply":"2023-07-30T23:52:24.161134Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# データ準備","metadata":{}},{"cell_type":"markdown","source":"zipファイルを展開\n使用するディレクトリの作成\n作成したディレクトリに画像を移動","metadata":{}},{"cell_type":"code","source":"import zipfile\n\n# train.zipの展開\nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip', 'r') as zip_ref:\n    zip_ref.extractall('/kaggle/working/train')\n\n# test.zipの展開\nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip', 'r') as zip_ref:\n    zip_ref.extractall('/kaggle/working/test')","metadata":{"execution":{"iopub.status.busy":"2023-07-30T23:52:24.163846Z","iopub.execute_input":"2023-07-30T23:52:24.164239Z","iopub.status.idle":"2023-07-30T23:52:41.493960Z","shell.execute_reply.started":"2023-07-30T23:52:24.164208Z","shell.execute_reply":"2023-07-30T23:52:41.492676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ライブラリのインポート(globライブラリを用いてファイル検索)\nimport glob\n\n# ファイル一覧を取得\nimages = glob.glob('/kaggle/working/train/train/*.jpg')\n\n# ファイル名を確認(先頭3枚)\nprint(images[:3])","metadata":{"execution":{"iopub.status.busy":"2023-07-30T23:52:41.495496Z","iopub.execute_input":"2023-07-30T23:52:41.495927Z","iopub.status.idle":"2023-07-30T23:52:41.570916Z","shell.execute_reply.started":"2023-07-30T23:52:41.495887Z","shell.execute_reply":"2023-07-30T23:52:41.569842Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 画像表示に必要なモジュールをインポート\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\n# 画像の表示\nimage_sample = images[0]\nimg = Image.open(image_sample)\nprint('filename:{}, size:{}'.format(image_sample, img.size))\nplt.imshow(img)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-07-30T23:52:41.573854Z","iopub.execute_input":"2023-07-30T23:52:41.574575Z","iopub.status.idle":"2023-07-30T23:52:42.009566Z","shell.execute_reply.started":"2023-07-30T23:52:41.574535Z","shell.execute_reply":"2023-07-30T23:52:42.007855Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os \n\n# train用フォルダ作成(学習データ)\nos.makedirs('/kaggle/working/images/train/dog', exist_ok=True)\nos.makedirs('/kaggle/working/images/train/cat', exist_ok=True)\n\n# val用フォルダ作成(検証データ)\nos.makedirs('/kaggle/working/images/val/dog', exist_ok=True)\nos.makedirs('/kaggle/working/images/val/cat', exist_ok=True)\n\n# test用フォルダ作成(テストデータ)\nos.makedirs('/kaggle/working/images/test/test', exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T23:52:42.011370Z","iopub.execute_input":"2023-07-30T23:52:42.012025Z","iopub.status.idle":"2023-07-30T23:52:42.019890Z","shell.execute_reply.started":"2023-07-30T23:52:42.011985Z","shell.execute_reply":"2023-07-30T23:52:42.018332Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"※val(検証：validation)：学習の途中でモデルの良し悪しを確かめるための検証データ","metadata":{}},{"cell_type":"code","source":"# 画像のファイルパスを取得\nimages_dog = glob.glob('/kaggle/working/train/train/dog.*.jpg')\nimages_cat = glob.glob('/kaggle/working/train/train/cat.*.jpg')\nimages_test = glob.glob('/kaggle/working/test/test/*.jpg')","metadata":{"execution":{"iopub.status.busy":"2023-07-30T23:52:42.022013Z","iopub.execute_input":"2023-07-30T23:52:42.022477Z","iopub.status.idle":"2023-07-30T23:52:42.165255Z","shell.execute_reply.started":"2023-07-30T23:52:42.022436Z","shell.execute_reply":"2023-07-30T23:52:42.164255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# trainフォルダのファイルを8:2に分割(train, val)\nidx_test_start = int(len(images_cat) * 0.8)\n\nimages_val_dog = images_dog[idx_test_start:]\nimages_val_cat = images_cat[idx_test_start:]\n\nimages_train_dog = images_dog[:idx_test_start]\nimages_train_cat = images_cat[:idx_test_start]","metadata":{"execution":{"iopub.status.busy":"2023-07-30T23:52:42.166874Z","iopub.execute_input":"2023-07-30T23:52:42.167331Z","iopub.status.idle":"2023-07-30T23:52:42.177230Z","shell.execute_reply.started":"2023-07-30T23:52:42.167281Z","shell.execute_reply":"2023-07-30T23:52:42.175900Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil\n\n# 一括でファイルを移動する関数を作成\ndef move_files(file_list, target_dir):\n    for file in file_list:\n        shutil.move(file, target_dir)\n\n# ファイル移動\nmove_files(images_train_dog, '/kaggle/working/images/train/dog/')\nmove_files(images_train_cat, '/kaggle/working/images/train/cat/')\nmove_files(images_val_dog, '/kaggle/working/images/val/dog/')\nmove_files(images_val_cat, '/kaggle/working/images/val/cat/')\nmove_files(images_test, '/kaggle/working/images/test/test/')","metadata":{"execution":{"iopub.status.busy":"2023-07-30T23:52:42.179877Z","iopub.execute_input":"2023-07-30T23:52:42.180838Z","iopub.status.idle":"2023-07-30T23:52:43.884562Z","shell.execute_reply.started":"2023-07-30T23:52:42.180784Z","shell.execute_reply":"2023-07-30T23:52:43.883009Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 学習の準備","metadata":{}},{"cell_type":"markdown","source":"学習回数 各データを順番に入力しモデルのパラメータを更新していく際、全ての学習データを一通り使用した状態を1エポック（epoch）、1サイクルを回した回数をエポック数と言う\nバッチサイズ 一般的に1回のパラメータの更新はいくつかのデータをまとめて入力して行う。この時まとめて入力するデータ数のことをバッチサイズと言う\n画像サイズ 入力層の画像の幅（width）と高さ（height）","metadata":{}},{"cell_type":"code","source":"#分類するクラス\nclasses = ['cat', 'dog']\nnb_classes = len(classes)\n \n# データのディレクトリ\ntrain_data_dir = '/kaggle/working/images/train'\nvalidation_data_dir = '/kaggle/working/images/val'\ntest_data_dir = '/kaggle/working/images/test'\n\n# 学習回数(submissionファイル提出時にスコアが一番優秀だった5を採用)\nepochs = 5\n\n# バッチサイズ\nbatch_size = 1024\n\n# 画像サイズ\nimg_width, img_height = 224, 224","metadata":{"execution":{"iopub.status.busy":"2023-07-30T23:52:43.886511Z","iopub.execute_input":"2023-07-30T23:52:43.886880Z","iopub.status.idle":"2023-07-30T23:52:43.892931Z","shell.execute_reply.started":"2023-07-30T23:52:43.886850Z","shell.execute_reply":"2023-07-30T23:52:43.891722Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ImageDataGeneratorの作成","metadata":{}},{"cell_type":"markdown","source":"train、val、testデータそれぞれのImageDataGeneratorを作成する ※ImageDataGenerator：画像の読み込みを一括ではなく逐次的に行い、メモリ負荷を軽減することができる（データの合計サイズが大きい場合はメモリにデータが乗り切らない場合があるため）","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# 学習データのImageDataGenerator作成\ntrain_datagen = ImageDataGenerator(rescale=1.0 / 255)  # rescaleで各画素のスケールを0～255から0～1に変換して正規化\ntrain_generator = train_datagen.flow_from_directory(\n    directory=train_data_dir,\n    target_size=(img_width, img_height),\n    color_mode='rgb',\n    classes=classes,\n    class_mode='categorical',\n    batch_size=batch_size\n)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T23:52:43.896327Z","iopub.execute_input":"2023-07-30T23:52:43.896734Z","iopub.status.idle":"2023-07-30T23:52:53.472411Z","shell.execute_reply.started":"2023-07-30T23:52:43.896704Z","shell.execute_reply":"2023-07-30T23:52:53.471185Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 検証データのImageDataGenerator作成\nvalidation_datagen = ImageDataGenerator(rescale=1.0 / 255) # rescaleで各画素のスケールを0～255から0～1に変換して正規化\nvalidation_generator = validation_datagen.flow_from_directory(\n    directory=validation_data_dir,\n    target_size=(img_width, img_height),\n    color_mode='rgb',\n    classes=classes,\n    class_mode='categorical',\n    batch_size=batch_size\n)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T23:52:53.473677Z","iopub.execute_input":"2023-07-30T23:52:53.474409Z","iopub.status.idle":"2023-07-30T23:52:53.582293Z","shell.execute_reply.started":"2023-07-30T23:52:53.474377Z","shell.execute_reply":"2023-07-30T23:52:53.581135Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 評価データのImageDataGenerator作成\ntest_datagen = ImageDataGenerator(rescale=1.0 / 255) # rescaleで各画素のスケールを0～255から0～1に変換して正規化\ntest_generator = test_datagen.flow_from_directory(\n    directory=test_data_dir,\n    target_size=(img_width, img_height),\n    class_mode=None,\n    shuffle=False \n)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T23:52:53.583619Z","iopub.execute_input":"2023-07-30T23:52:53.584253Z","iopub.status.idle":"2023-07-30T23:52:54.115594Z","shell.execute_reply.started":"2023-07-30T23:52:53.584220Z","shell.execute_reply":"2023-07-30T23:52:54.114086Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 学習済みモデル","metadata":{}},{"cell_type":"markdown","source":"学習済みモデルVGG16を読み込む。最終層は差し替えるため、include_top=Falseと指定して読み込まないように","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.applications.vgg16 import VGG16\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Input, Flatten, Dense\n\ninput_tensor = Input(shape=(img_width, img_height, 3))\nVGG16 = VGG16(include_top=False, weights='imagenet', input_tensor=input_tensor)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T23:52:54.117103Z","iopub.execute_input":"2023-07-30T23:52:54.117441Z","iopub.status.idle":"2023-07-30T23:52:57.648780Z","shell.execute_reply.started":"2023-07-30T23:52:54.117413Z","shell.execute_reply":"2023-07-30T23:52:57.647610Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# モデルの作成","metadata":{}},{"cell_type":"markdown","source":"転移学習を行うため、VGG16のパラメータは凍結し、最終層に全結合層を追加","metadata":{}},{"cell_type":"code","source":"# VGG16のパラメータを凍結(すべての層を凍結)\nfor layer in VGG16.layers:\n    layer.trainable = False ","metadata":{"execution":{"iopub.status.busy":"2023-07-30T23:52:57.651044Z","iopub.execute_input":"2023-07-30T23:52:57.651716Z","iopub.status.idle":"2023-07-30T23:52:57.657966Z","shell.execute_reply.started":"2023-07-30T23:52:57.651671Z","shell.execute_reply":"2023-07-30T23:52:57.656786Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 差し替え用の新しい層を追加\nmodel = Sequential()\nmodel.add(VGG16)\nmodel.add(Flatten())\nmodel.add(Dense(nb_classes, activation='softmax'))","metadata":{"execution":{"iopub.status.busy":"2023-07-30T23:52:57.659360Z","iopub.execute_input":"2023-07-30T23:52:57.660167Z","iopub.status.idle":"2023-07-30T23:52:57.802450Z","shell.execute_reply.started":"2023-07-30T23:52:57.660136Z","shell.execute_reply":"2023-07-30T23:52:57.801408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary() #構築したモデルの概要を表示","metadata":{"execution":{"iopub.status.busy":"2023-07-30T23:52:57.803762Z","iopub.execute_input":"2023-07-30T23:52:57.804295Z","iopub.status.idle":"2023-07-30T23:52:57.825933Z","shell.execute_reply.started":"2023-07-30T23:52:57.804253Z","shell.execute_reply":"2023-07-30T23:52:57.824662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras import optimizers\n#モデルをコンパイルして学習方法を指定。\n#損失関数にクロスエントロピー・最適化アルゴリズムにAdam・学習中の評価指標にaccuracyを設定\nmodel.compile(loss='categorical_crossentropy',\n              optimizer=optimizers.Adam(learning_rate=1e-3),\n              metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2023-07-30T23:52:57.827291Z","iopub.execute_input":"2023-07-30T23:52:57.827603Z","iopub.status.idle":"2023-07-30T23:52:57.851540Z","shell.execute_reply.started":"2023-07-30T23:52:57.827575Z","shell.execute_reply":"2023-07-30T23:52:57.850557Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 学習","metadata":{}},{"cell_type":"markdown","source":"引数：学習データとステップ数（1エポックあたり何回パラメータの更新を行うかを表す数。全データ数/バッチサイズ）、エポック数、検証データ","metadata":{}},{"cell_type":"code","source":"# 学習\nsteps_per_epoch = int(len(train_generator.classes) / batch_size) \nhistory = model.fit(\n    x=train_generator,  # 学習データ\n    steps_per_epoch=steps_per_epoch,  # ステップ数\n    epochs=epochs,  # エポック数\n    validation_data=validation_generator  # 検証データ\n)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T23:52:57.852915Z","iopub.execute_input":"2023-07-30T23:52:57.853602Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# グラフ描画(2画面)\nplt.figure(figsize=(8, 4))\n\n# epochごとのlossを表示\nplt.subplot(1, 2, 1)\nplt.plot(range(1, epochs+1), history.history['loss'], '-o')\nplt.plot(range(1, epochs+1), history.history['val_loss'], '-o')\nplt.title('loss_transition')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.grid()\nplt.legend(['loss', 'val_loss'], loc='best')\n\n# epochごとのaccuracyを表示\nplt.subplot(1, 2, 2)\nplt.plot(range(1, epochs+1), history.history['accuracy'], '-o')\nplt.plot(range(1, epochs+1), history.history['val_accuracy'], '-o')\nplt.title('accuracy_transition')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.grid()\nplt.legend(['accuracy', 'val_accuracy'], loc='best')\n\n# グラフ表示\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"※loss：学習データで予測した場合の損失関数 ※accuracy：学習データにて、正しく予測できた画像数の割合","metadata":{}},{"cell_type":"markdown","source":"# 評価","metadata":{}},{"cell_type":"markdown","source":"valデータを用いてモデル精度を評価","metadata":{}},{"cell_type":"code","source":"model.evaluate(validation_generator)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 訓練したモデルを用いてテストデータの予測を実施\nimport numpy as np\np = model.predict(test_generator)\npred = np.argmax(p, axis=1)\npred","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 結果を提出できるよう修正","metadata":{}},{"cell_type":"code","source":"pred_pd = pd.DataFrame(p)\n# id列を作成\npred_pd.insert(0, 'id', range(1, len(pred_pd) + 1))\npred_pd.columns\npred_pd = pred_pd.drop([0], axis=1)\npred_pd = pred_pd.rename(columns={1: 'label'})\npred_pd","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 結果の保存","metadata":{}},{"cell_type":"markdown","source":"notebookから提出できないため、notebookをRun Allで実行し、生成されたsubmissionファイルを一度ダウンロードして提出することでScore算出が可能","metadata":{}},{"cell_type":"code","source":"sub = pd.read_csv('/kaggle/input/dogs-vs-cats-redux-kernels-edition/sample_submission.csv') # ひな形ファイルを読み込む\nprint(sub.shape)\n# subのlabel列をtest_predictedのlabel列で上書きする\nsub['label'] = pred_pd['label']\n# 結果を表示\nsub\nsub.to_csv('submission.csv', index=False) # 変換したファイルを保存","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}