{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":5441,"databundleVersionId":38425,"sourceType":"competition"}],"dockerImageVersionId":30746,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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":"2024-07-25T05:52:21.218460Z","iopub.execute_input":"2024-07-25T05:52:21.219764Z","iopub.status.idle":"2024-07-25T05:52:21.654018Z","shell.execute_reply.started":"2024-07-25T05:52:21.219721Z","shell.execute_reply":"2024-07-25T05:52:21.652927Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 1.データセットの準備 \n# データセットがZIP形式なので解凍して画像を正しいディレクトリに配置するのだが，ファイル名を利用してdog,catのディレクトリに配置した． 出力から，25000データある犬猫画像が正確に12500ずつ分けれたことが分かる．\n","metadata":{}},{"cell_type":"code","source":"import sys\nprint(sys.version)","metadata":{"execution":{"iopub.status.busy":"2024-07-25T05:52:21.656066Z","iopub.execute_input":"2024-07-25T05:52:21.656566Z","iopub.status.idle":"2024-07-25T05:52:21.662203Z","shell.execute_reply.started":"2024-07-25T05:52:21.656533Z","shell.execute_reply":"2024-07-25T05:52:21.660880Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport os\nimport shutil\nimport glob\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom tensorflow.keras.optimizers import Adam\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2024-07-25T05:52:21.663738Z","iopub.execute_input":"2024-07-25T05:52:21.664218Z","iopub.status.idle":"2024-07-25T05:52:36.346164Z","shell.execute_reply.started":"2024-07-25T05:52:21.664178Z","shell.execute_reply":"2024-07-25T05:52:36.345122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#zipファイルの解凍\nimport shutil\nimport zipfile\nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip') as exiting_zip:\n    exiting_zip.extractall()\n\nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip') as exiting_zip:\n    exiting_zip.extractall()","metadata":{"execution":{"iopub.status.busy":"2024-07-25T05:52:36.347505Z","iopub.execute_input":"2024-07-25T05:52:36.348237Z","iopub.status.idle":"2024-07-25T05:52:53.517418Z","shell.execute_reply.started":"2024-07-25T05:52:36.348207Z","shell.execute_reply":"2024-07-25T05:52:53.516048Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 犬・猫の画像をそれぞれのフォルダに移動\ndog_dir = '/kaggle/working/train/dog'\ncat_dir = '/kaggle/working/train/cat'\nos.makedirs(dog_dir, exist_ok=True)\nos.makedirs(cat_dir, exist_ok=True)\n\nfiles = glob.glob('/kaggle/working/train/*.jpg')\nfor file in files:\n    file_name = os.path.basename(file)\n    if 'cat' in file_name:\n        shutil.move(file, '/kaggle/working/train/cat/' + file_name)\n    else:\n        shutil.move(file, '/kaggle/working/train/dog/' + file_name)","metadata":{"execution":{"iopub.status.busy":"2024-07-25T05:52:53.521165Z","iopub.execute_input":"2024-07-25T05:52:53.521917Z","iopub.status.idle":"2024-07-25T05:52:54.329274Z","shell.execute_reply.started":"2024-07-25T05:52:53.521878Z","shell.execute_reply":"2024-07-25T05:52:54.328002Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ２．画像ジェネレータの設定\n# ここでは、ImageDataGeneratorを使用して画像データの前処理を行い、訓練データと検証データのジェネレータを作成する。","metadata":{}},{"cell_type":"code","source":"# データの前処理\ntrain_datagen = ImageDataGenerator(\n    rescale=1.0/255,\n    rotation_range=40,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    fill_mode='nearest',\n    validation_split=0.2\n)\n\n# ディレクトリの設定\ntrain_dir = '/kaggle/working/train'\ntest_dir = '/kaggle/working/test'\n\n# ジェネレータの設定\ntrain_generator = train_datagen.flow_from_directory(\n    train_dir,\n    target_size=(150, 150),\n    batch_size=46,\n    class_mode='binary',\n    subset='training'\n)\n\ntest_generator = train_datagen.flow_from_directory(\n    train_dir,\n    target_size=(150, 150),\n    batch_size=46,\n    class_mode='binary',\n    subset='validation'\n)","metadata":{"execution":{"iopub.status.busy":"2024-07-25T05:52:54.330693Z","iopub.execute_input":"2024-07-25T05:52:54.331045Z","iopub.status.idle":"2024-07-25T05:52:54.870250Z","shell.execute_reply.started":"2024-07-25T05:52:54.331015Z","shell.execute_reply":"2024-07-25T05:52:54.868775Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# モデル構築\n# ここでは、モデルの構築を行う。 Kerasを使用してCNN（畳み込みニューラルネットワーク）モデルを構築し、コンパイルする。モデルは画像分類タスクに適用され、2クラス分類を行う。\n# 各層の説明\n\n# 1.Conv2D（畳み込み層）は、画像の空間的な特徴を捉えるために使用する。32個の3x3フィルターを使用して、入力画像から特徴マップを抽出できる。 この層を追加し、フィルター数を64,128と増やすことでより多くのパターンを学習できる。\n# 2.MaxPooling2D（最大プーリング層）は、空間的な次元を縮小し、計算量を減らし、特徴の不変性を向上させることが出来る。2x2のプーリングサイズを使用して、特徴マップのサイズを半分に縮小する。 この層を追加し、特徴マップのサイズをさらに縮小できる。\n# 3.Flatten（平坦化層）は、畳み込み層とプーリング層で抽出された2D特徴マップを1Dベクトルに変換する。この変換の後に全結合層に入力することが出来る。\n# 4.Dense（全結合層）は、分類を行うために必要で、複雑なパターンを学習することが出来る。\n# 5.Dropout（ドロップアウト層）は、過学習を防ぐための層\n# 6.Dense（出力層）は、分類において最終的な出力を行うための層であり、2クラス分類問題に適していると言える。","metadata":{}},{"cell_type":"code","source":"# モデルの構築\nmodel = Sequential([\n    Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)),\n    MaxPooling2D(2, 2),\n    Conv2D(64, (3, 3), activation='relu'),\n    MaxPooling2D(2, 2),\n    Conv2D(128, (3, 3), activation='relu'),\n    MaxPooling2D(2, 2),\n    Conv2D(128, (3, 3), activation='relu'),\n    MaxPooling2D(2, 2),\n    Flatten(),\n    Dense(512, activation='relu'),\n    Dropout(0.5),\n    Dense(1, activation='sigmoid')\n])","metadata":{"execution":{"iopub.status.busy":"2024-07-25T05:52:54.872234Z","iopub.execute_input":"2024-07-25T05:52:54.872782Z","iopub.status.idle":"2024-07-25T05:52:55.066751Z","shell.execute_reply.started":"2024-07-25T05:52:54.872739Z","shell.execute_reply":"2024-07-25T05:52:55.065348Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# モデルのコンパイル\nmodel.compile(loss='binary_crossentropy',\n              optimizer=Adam(learning_rate=0.001),\n              metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-07-25T05:52:55.068371Z","iopub.execute_input":"2024-07-25T05:52:55.068846Z","iopub.status.idle":"2024-07-25T05:52:55.086866Z","shell.execute_reply.started":"2024-07-25T05:52:55.068796Z","shell.execute_reply":"2024-07-25T05:52:55.085671Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ４．モデルの学習\n# ここでは、先ほど構築したモデルの学習を行う。学習には訓練用データと検証用データのジェネレータを使用する。","metadata":{}},{"cell_type":"code","source":"steps_per_epoch = train_generator.samples // 46\nvalidation_steps = test_generator.samples // 46\n\n# モデルの訓練\nhistory = model.fit(\n    train_generator,\n    steps_per_epoch=steps_per_epoch,\n    epochs=10,  # 訓練回数の指定\n    validation_data=test_generator,\n    validation_steps=validation_steps\n)","metadata":{"execution":{"iopub.status.busy":"2024-07-25T05:52:55.088414Z","iopub.execute_input":"2024-07-25T05:52:55.089223Z","iopub.status.idle":"2024-07-25T06:39:40.515038Z","shell.execute_reply.started":"2024-07-25T05:52:55.089180Z","shell.execute_reply":"2024-07-25T06:39:40.513665Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ５．モデルの評価\n# モデルを評価してAccuracyなどを出力し、最終的にはモデルの保存を行った。","metadata":{}},{"cell_type":"code","source":"# モデルの保存\nmodel.save('cats_and_dogs_classifier.h5')","metadata":{"execution":{"iopub.status.busy":"2024-07-25T06:39:40.516891Z","iopub.execute_input":"2024-07-25T06:39:40.517256Z","iopub.status.idle":"2024-07-25T06:39:40.640788Z","shell.execute_reply.started":"2024-07-25T06:39:40.517226Z","shell.execute_reply":"2024-07-25T06:39:40.639388Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 訓練と検証の損失値をプロット\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, 'bo', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-07-25T06:39:40.642409Z","iopub.execute_input":"2024-07-25T06:39:40.642912Z","iopub.status.idle":"2024-07-25T06:39:41.229023Z","shell.execute_reply.started":"2024-07-25T06:39:40.642880Z","shell.execute_reply":"2024-07-25T06:39:41.227867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport shutil\n\n# テストデータのディレクトリパス\ntest_dir = '/kaggle/working/test'\ntemp_test_dir = '/kaggle/working/test/test_date'\n\n# 仮のサブディレクトリを作成\nif not os.path.exists(temp_test_dir):\n    os.makedirs(temp_test_dir)\n\n# 画像を仮のサブディレクトリに移動\nfor filename in os.listdir(test_dir):\n    if filename.endswith(('.jpg', '.png', '.jpeg')):  # 対応する画像フォーマットを指定\n        shutil.move(os.path.join(test_dir, filename), os.path.join(temp_test_dir, filename))\n\n# ディレクトリの内容を確認\nfor root, dirs, files in os.walk(test_dir):\n    print(f\"Root: {root}\")\n    print(f\"Directories: {dirs}\")\n    print(f\"Files: {files}\")\n    print(\"-------------------\")\n","metadata":{"execution":{"iopub.status.busy":"2024-07-25T06:39:41.230435Z","iopub.execute_input":"2024-07-25T06:39:41.230809Z","iopub.status.idle":"2024-07-25T06:39:41.698077Z","shell.execute_reply.started":"2024-07-25T06:39:41.230779Z","shell.execute_reply":"2024-07-25T06:39:41.696843Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ６．提出ファイルの準備\n# ここでは、テストデータに対してモデルの予測を実行し、Kaggle提出用のファイルを作成する。 先ほど保存したモデルを用いて、テストデータの予測を行い、結果をsubmission.csvに入力し、提出ファイルを完成させる。","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport numpy as np\nimport pandas as pd\n\n# テストデータジェネレータの設定\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntest_generator = test_datagen.flow_from_directory(\n    test_dir,\n    target_size=(150, 150),\n    batch_size=32,\n    class_mode=None,\n    shuffle=False\n)\n\n# 予測の実行\nsteps = int(np.ceil(test_generator.samples / test_generator.batch_size))\npredictions = model.predict(test_generator, steps=steps)\n\n# 予測結果を0または1に変換\npredicted_classes = (predictions > 0.5).astype(int).flatten()\n\n# 提出用データフレームの作成\nfilenames = test_generator.filenames\nresults = pd.DataFrame({'id': [int(f.split('/')[1].split('.')[0]) for f in filenames], 'label': predicted_classes})\nresults = results.sort_values(by='id')\n\n# 提出ファイルの保存\nsubmission_path = '/kaggle/working/submission.csv'\nresults.to_csv(submission_path, index=False)\n\nprint(f'Submission file saved to {submission_path}')","metadata":{"execution":{"iopub.status.busy":"2024-07-25T06:39:41.699681Z","iopub.execute_input":"2024-07-25T06:39:41.700139Z","iopub.status.idle":"2024-07-25T06:41:08.555005Z","shell.execute_reply.started":"2024-07-25T06:39:41.700100Z","shell.execute_reply":"2024-07-25T06:41:08.553319Z"},"trusted":true},"execution_count":null,"outputs":[]}]}