{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":28755,"isInternetEnabled":false,"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\n\n# Use the kagglehub client library to attach Kaggle resources like competitions, datasets, and models to your session\n# Learn more about kagglehub: https://github.com/Kaggle/kagglehub/blob/main/README.md\n\nimport kagglehub\n# kagglehub.dataset_download('<owner>/<dataset-slug>')","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-07-24T08:06:48.170424Z","iopub.execute_input":"2026-07-24T08:06:48.170786Z","iopub.status.idle":"2026-07-24T08:06:51.185011Z","shell.execute_reply.started":"2026-07-24T08:06:48.170745Z","shell.execute_reply":"2026-07-24T08:06:51.184251Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport zipfile\nimport pandas as pd\nimport tensorflow as tf\n\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import (\n    Conv2D,\n    MaxPooling2D,\n    GlobalAveragePooling2D,\n    Dense,\n    Dropout\n)\n\ninput_dir = \"/kaggle/input/competitions/dogs-vs-cats-redux-kernels-edition\"\ntrain_dir = \"/kaggle/working/train/train\"\ntest_dir = \"/kaggle/working/test/test\"\n\nos.makedirs(\"/kaggle/working/train\", exist_ok=True)\nos.makedirs(\"/kaggle/working/test\", exist_ok=True)\n\nwith zipfile.ZipFile(f\"{input_dir}/train.zip\") as z:\n    z.extractall(\"/kaggle/working/train\")\n\nwith zipfile.ZipFile(f\"{input_dir}/test.zip\") as z:\n    z.extractall(\"/kaggle/working/test\")\n\nprint(\"GPU:\", tf.config.list_physical_devices(\"GPU\"))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-24T08:06:51.186400Z","iopub.execute_input":"2026-07-24T08:06:51.186860Z","iopub.status.idle":"2026-07-24T08:07:28.750446Z","shell.execute_reply.started":"2026-07-24T08:06:51.186833Z","shell.execute_reply":"2026-07-24T08:07:28.749687Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"files = os.listdir(train_dir)\n\ndf = pd.DataFrame({\n    \"filename\": files\n})\n\ndf[\"label\"] = df[\"filename\"].apply(\n    lambda x: \"dog\" if x.startswith(\"dog\") else \"cat\"\n)\n\ntrain_df, val_df = train_test_split(\n    df,\n    test_size=0.2,\n    random_state=42,\n    stratify=df[\"label\"]\n)\n\ndatagen = ImageDataGenerator(rescale=1 / 255.0)\n\ntrain_data = datagen.flow_from_dataframe(\n    train_df,\n    directory=train_dir,\n    x_col=\"filename\",\n    y_col=\"label\",\n    target_size=(128, 128),\n    batch_size=32,\n    class_mode=\"binary\"\n)\n\nval_data = datagen.flow_from_dataframe(\n    val_df,\n    directory=train_dir,\n    x_col=\"filename\",\n    y_col=\"label\",\n    target_size=(128, 128),\n    batch_size=32,\n    class_mode=\"binary\",\n    shuffle=False\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-24T08:07:28.751343Z","iopub.execute_input":"2026-07-24T08:07:28.751873Z","iopub.status.idle":"2026-07-24T08:07:29.017929Z","shell.execute_reply.started":"2026-07-24T08:07:28.751847Z","shell.execute_reply":"2026-07-24T08:07:29.017253Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.layers import BatchNormalization\n\nmodel2 = Sequential([\n    tf.keras.Input(shape=(128, 128, 3)),\n\n    Conv2D(32, 3, padding=\"same\", activation=\"relu\"),\n    BatchNormalization(),\n    MaxPooling2D(),\n\n    Conv2D(64, 3, padding=\"same\", activation=\"relu\"),\n    BatchNormalization(),\n    MaxPooling2D(),\n\n    Conv2D(128, 3, padding=\"same\", activation=\"relu\"),\n    BatchNormalization(),\n    MaxPooling2D(),\n\n    Conv2D(256, 3, padding=\"same\", activation=\"relu\"),\n    BatchNormalization(),\n    MaxPooling2D(),\n\n    GlobalAveragePooling2D(),\n    Dense(128, activation=\"relu\"),\n    Dropout(0.5),\n\n    Dense(1, activation=\"sigmoid\")\n])\n\nmodel2.compile(\n    optimizer=\"adam\",\n    loss=\"binary_crossentropy\",\n    metrics=[\"accuracy\"]\n)\n\nmodel2.summary()\n\nhistory2 = model2.fit(\n    train_data,\n    validation_data=val_data,\n    epochs=5\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-24T08:07:29.018978Z","iopub.execute_input":"2026-07-24T08:07:29.019348Z","iopub.status.idle":"2026-07-24T08:10:27.970848Z","shell.execute_reply.started":"2026-07-24T08:07:29.019313Z","shell.execute_reply":"2026-07-24T08:10:27.970098Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nplt.plot(history2.history[\"accuracy\"], label=\"Train Accuracy\")\nplt.plot(history2.history[\"val_accuracy\"], label=\"Validation Accuracy\")\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Accuracy\")\nplt.title(\"Model 2 Accuracy\")\nplt.legend()\nplt.grid()\nplt.show()\n\nplt.plot(history2.history[\"loss\"], label=\"Train Loss\")\nplt.plot(history2.history[\"val_loss\"], label=\"Validation Loss\")\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Loss\")\nplt.title(\"Model 2 Loss\")\nplt.legend()\nplt.grid()\nplt.show()\n\nval_loss2, val_accuracy2 = model2.evaluate(val_data)\n\nprint(f\"2回目の検証正解率：{val_accuracy2 * 100:.2f}%\")\nprint(f\"2回目の検証損失：{val_loss2:.4f}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-24T08:10:27.972565Z","iopub.execute_input":"2026-07-24T08:10:27.972801Z","iopub.status.idle":"2026-07-24T08:10:34.835348Z","shell.execute_reply.started":"2026-07-24T08:10:27.972777Z","shell.execute_reply":"2026-07-24T08:10:34.834707Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_files = sorted(\n    os.listdir(test_dir),\n    key=lambda x: int(x.split(\".\")[0])\n)\n\ntest_df = pd.DataFrame({\n    \"filename\": test_files\n})\n\ntest_data = datagen.flow_from_dataframe(\n    test_df,\n    directory=test_dir,\n    x_col=\"filename\",\n    y_col=None,\n    target_size=(128, 128),\n    batch_size=32,\n    class_mode=None,\n    shuffle=False\n)\n\npredictions2 = model2.predict(test_data).reshape(-1)\n\nsubmission2 = pd.DataFrame({\n    \"id\": [int(x.split(\".\")[0]) for x in test_files],\n    \"label\": predictions2\n})\n\nsubmission2[\"label\"] = submission2[\"label\"].clip(0.005, 0.995)\n\nsubmission2.to_csv(\n    \"/kaggle/working/submission2.csv\",\n    index=False\n)\n\nprint(submission2.head())\nprint(\"submission2.csvを作成しました\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-24T08:10:34.836773Z","iopub.execute_input":"2026-07-24T08:10:34.837495Z","iopub.status.idle":"2026-07-24T08:10:52.867641Z","shell.execute_reply.started":"2026-07-24T08:10:34.837469Z","shell.execute_reply":"2026-07-24T08:10:52.866909Z"}},"outputs":[],"execution_count":null}]}