{"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-25T10:47:05.576112Z","iopub.execute_input":"2023-07-25T10:47:05.576515Z","iopub.status.idle":"2023-07-25T10:47:05.614585Z","shell.execute_reply.started":"2023-07-25T10:47:05.576481Z","shell.execute_reply":"2023-07-25T10:47:05.613608Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-25T10:47:05.616388Z","iopub.execute_input":"2023-07-25T10:47:05.616700Z","iopub.status.idle":"2023-07-25T10:47:22.663076Z","shell.execute_reply.started":"2023-07-25T10:47:05.616674Z","shell.execute_reply":"2023-07-25T10:47:22.662143Z"},"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-25T10:47:22.664171Z","iopub.execute_input":"2023-07-25T10:47:22.664717Z","iopub.status.idle":"2023-07-25T10:47:22.735621Z","shell.execute_reply.started":"2023-07-25T10:47:22.664684Z","shell.execute_reply":"2023-07-25T10:47:22.734645Z"},"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-25T10:47:22.737493Z","iopub.execute_input":"2023-07-25T10:47:22.738482Z","iopub.status.idle":"2023-07-25T10:47:23.142359Z","shell.execute_reply.started":"2023-07-25T10:47:22.738447Z","shell.execute_reply":"2023-07-25T10:47:23.141036Z"},"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/dog', exist_ok=True)\nos.makedirs('/kaggle/working/images/test/cat', exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2023-07-25T10:47:23.144176Z","iopub.execute_input":"2023-07-25T10:47:23.144624Z","iopub.status.idle":"2023-07-25T10:47:23.152931Z","shell.execute_reply.started":"2023-07-25T10:47:23.144583Z","shell.execute_reply":"2023-07-25T10:47:23.151648Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 犬・猫ごとのファイルパス一覧を取得\nimages_dog = glob.glob('/kaggle/working/train/train/dog.*.jpg')\nimages_cat = glob.glob('/kaggle/working/train/train/cat.*.jpg')","metadata":{"execution":{"iopub.status.busy":"2023-07-25T10:47:23.154645Z","iopub.execute_input":"2023-07-25T10:47:23.155100Z","iopub.status.idle":"2023-07-25T10:47:23.266577Z","shell.execute_reply.started":"2023-07-25T10:47:23.155058Z","shell.execute_reply":"2023-07-25T10:47:23.265616Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ファイルを分割(train, val, test)\nidx_test_start = int(len(images_cat) * 0.71)\nidx_val_start = int(idx_test_start * 0.71)\n\nimages_test_dog = images_dog[:idx_val_start]\nimages_test_cat = images_cat[:idx_val_start]\n\nimages_val_dog = images_dog[idx_val_start:idx_test_start]\nimages_val_cat = images_cat[idx_val_start: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-25T10:47:23.268209Z","iopub.execute_input":"2023-07-25T10:47:23.268894Z","iopub.status.idle":"2023-07-25T10:47:23.279046Z","shell.execute_reply.started":"2023-07-25T10:47:23.268849Z","shell.execute_reply":"2023-07-25T10:47:23.277532Z"},"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_dog, '/kaggle/working/images/test/dog/')\nmove_files(images_test_cat, '/kaggle/working/images/test/cat/')","metadata":{"execution":{"iopub.status.busy":"2023-07-25T10:47:23.280229Z","iopub.execute_input":"2023-07-25T10:47:23.280544Z","iopub.status.idle":"2023-07-25T10:47:24.388231Z","shell.execute_reply.started":"2023-07-25T10:47:23.280519Z","shell.execute_reply":"2023-07-25T10:47:24.386389Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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# 学習回数\nepochs = 1\n\n# バッチサイズ\nbatch_size = 1024\n\n# 画像サイズ\nimg_width, img_height = 224, 224","metadata":{"execution":{"iopub.status.busy":"2023-07-25T10:47:24.390369Z","iopub.execute_input":"2023-07-25T10:47:24.391046Z","iopub.status.idle":"2023-07-25T10:47:24.397979Z","shell.execute_reply.started":"2023-07-25T10:47:24.391001Z","shell.execute_reply":"2023-07-25T10:47:24.396938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-25T10:47:24.401230Z","iopub.execute_input":"2023-07-25T10:47:24.401599Z","iopub.status.idle":"2023-07-25T10:47:33.473958Z","shell.execute_reply.started":"2023-07-25T10:47:24.401569Z","shell.execute_reply":"2023-07-25T10:47:33.472866Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 検証データのImageDataGenerator作成\nvalidation_datagen = ImageDataGenerator(rescale=1.0 / 255) \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-25T10:47:33.475348Z","iopub.execute_input":"2023-07-25T10:47:33.476176Z","iopub.status.idle":"2023-07-25T10:47:33.589987Z","shell.execute_reply.started":"2023-07-25T10:47:33.476143Z","shell.execute_reply":"2023-07-25T10:47:33.589093Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 評価データのImageDataGenerator作成\ntest_datagen = ImageDataGenerator(rescale=1.0 / 255) \ntest_generator = test_datagen.flow_from_directory(\n    directory=test_data_dir,\n    target_size=(img_width, img_height),\n    color_mode='rgb',\n    classes=classes,\n    class_mode='categorical',\n    shuffle=False  # シャッフルしない\n)","metadata":{"execution":{"iopub.status.busy":"2023-07-25T10:47:33.591160Z","iopub.execute_input":"2023-07-25T10:47:33.591461Z","iopub.status.idle":"2023-07-25T10:47:33.837933Z","shell.execute_reply.started":"2023-07-25T10:47:33.591434Z","shell.execute_reply":"2023-07-25T10:47:33.836955Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-25T10:47:33.839164Z","iopub.execute_input":"2023-07-25T10:47:33.839958Z","iopub.status.idle":"2023-07-25T10:47:36.477344Z","shell.execute_reply.started":"2023-07-25T10:47:33.839894Z","shell.execute_reply":"2023-07-25T10:47:36.476291Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# VGG16のパラメータを凍結(すべての層を凍結)\nfor layer in VGG16.layers:\n    layer.trainable = False ","metadata":{"execution":{"iopub.status.busy":"2023-07-25T10:47:36.479407Z","iopub.execute_input":"2023-07-25T10:47:36.479725Z","iopub.status.idle":"2023-07-25T10:47:36.484557Z","shell.execute_reply.started":"2023-07-25T10:47:36.479698Z","shell.execute_reply":"2023-07-25T10:47:36.483821Z"},"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-25T10:47:36.485632Z","iopub.execute_input":"2023-07-25T10:47:36.486100Z","iopub.status.idle":"2023-07-25T10:47:37.287696Z","shell.execute_reply.started":"2023-07-25T10:47:36.486072Z","shell.execute_reply":"2023-07-25T10:47:37.286499Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2023-07-25T10:47:37.289384Z","iopub.execute_input":"2023-07-25T10:47:37.290109Z","iopub.status.idle":"2023-07-25T10:47:37.312565Z","shell.execute_reply.started":"2023-07-25T10:47:37.290063Z","shell.execute_reply":"2023-07-25T10:47:37.311478Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras import optimizers\n\nmodel.compile(loss='categorical_crossentropy',\n              optimizer=optimizers.Adam(learning_rate=1e-3),\n              metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2023-07-25T10:47:37.313679Z","iopub.execute_input":"2023-07-25T10:47:37.315209Z","iopub.status.idle":"2023-07-25T10:47:37.339429Z","shell.execute_reply.started":"2023-07-25T10:47:37.315169Z","shell.execute_reply":"2023-07-25T10:47:37.338550Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-25T10:47:37.340642Z","iopub.execute_input":"2023-07-25T10:47:37.341047Z","iopub.status.idle":"2023-07-25T11:35:03.217317Z","shell.execute_reply.started":"2023-07-25T10:47:37.341010Z","shell.execute_reply":"2023-07-25T11:35:03.216414Z"},"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":{"execution":{"iopub.status.busy":"2023-07-25T11:35:03.218424Z","iopub.execute_input":"2023-07-25T11:35:03.218753Z","iopub.status.idle":"2023-07-25T11:35:03.714051Z","shell.execute_reply.started":"2023-07-25T11:35:03.218724Z","shell.execute_reply":"2023-07-25T11:35:03.712938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.evaluate(test_generator)","metadata":{"execution":{"iopub.status.busy":"2023-07-25T11:35:03.715248Z","iopub.execute_input":"2023-07-25T11:35:03.715583Z","iopub.status.idle":"2023-07-25T12:27:28.317098Z","shell.execute_reply.started":"2023-07-25T11:35:03.715554Z","shell.execute_reply":"2023-07-25T12:27:28.315489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 正解のラベル一覧を作成。\ntrue = test_generator.classes\ntrue","metadata":{"execution":{"iopub.status.busy":"2023-07-25T12:27:28.319496Z","iopub.execute_input":"2023-07-25T12:27:28.319949Z","iopub.status.idle":"2023-07-25T12:27:28.332401Z","shell.execute_reply.started":"2023-07-25T12:27:28.319898Z","shell.execute_reply":"2023-07-25T12:27:28.331105Z"},"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":{"execution":{"iopub.status.busy":"2023-07-25T12:27:28.334013Z","iopub.execute_input":"2023-07-25T12:27:28.334687Z","iopub.status.idle":"2023-07-25T13:19:50.751083Z","shell.execute_reply.started":"2023-07-25T12:27:28.334647Z","shell.execute_reply":"2023-07-25T13:19:50.749812Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 混同行列表示\nfrom tensorflow.math import confusion_matrix\nconfusion_matrix(true, pred)","metadata":{"execution":{"iopub.status.busy":"2023-07-25T13:19:50.752656Z","iopub.execute_input":"2023-07-25T13:19:50.753001Z","iopub.status.idle":"2023-07-25T13:19:50.757705Z","shell.execute_reply.started":"2023-07-25T13:19:50.752973Z","shell.execute_reply":"2023-07-25T13:19:50.756581Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-07-25T13:19:50.759308Z","iopub.execute_input":"2023-07-25T13:19:50.759770Z","iopub.status.idle":"2023-07-25T13:19:50.819951Z","shell.execute_reply.started":"2023-07-25T13:19:50.759738Z","shell.execute_reply":"2023-07-25T13:19:50.819134Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-07-25T13:19:50.821296Z","iopub.execute_input":"2023-07-25T13:19:50.821627Z","iopub.status.idle":"2023-07-25T13:19:50.957365Z","shell.execute_reply.started":"2023-07-25T13:19:50.821600Z","shell.execute_reply":"2023-07-25T13:19:50.956485Z"},"trusted":true},"execution_count":null,"outputs":[]}]}