{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.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":31089,"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","trusted":true,"execution":{"iopub.status.busy":"2025-07-24T02:47:28.796975Z","iopub.execute_input":"2025-07-24T02:47:28.797343Z","iopub.status.idle":"2025-07-24T02:47:28.804917Z","shell.execute_reply.started":"2025-07-24T02:47:28.797314Z","shell.execute_reply":"2025-07-24T02:47:28.804060Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import zipfile\n# ===== 1. zipファイルの解凍 =====\ninput_dir = \"/kaggle/input/dogs-vs-cats-redux-kernels-edition/\"\nwork_dir = \"/kaggle/working/\"\n\nwith zipfile.ZipFile(input_dir + \"train.zip\", \"r\") as zip_ref:\n    zip_ref.extractall(work_dir + \"train/\")\n\nwith zipfile.ZipFile(input_dir + \"test.zip\", \"r\") as zip_ref:\n    zip_ref.extractall(work_dir + \"test/\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-24T02:47:28.806199Z","iopub.execute_input":"2025-07-24T02:47:28.806511Z","iopub.status.idle":"2025-07-24T02:47:42.937470Z","shell.execute_reply.started":"2025-07-24T02:47:28.806451Z","shell.execute_reply":"2025-07-24T02:47:42.936530Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n# InceptionV3による犬猫分類（Kaggle Redux用）\nimport os, shutil\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import InceptionV3\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D\nfrom tensorflow.keras.optimizers import Adam\n\n# 1. Redux形式で展開された画像を cat/dog に振り分け\nsrc = \"/kaggle/working/train/train\"\ndst = \"/kaggle/working/train_split\"\nos.makedirs(f\"{dst}/cat\", exist_ok=True)\nos.makedirs(f\"{dst}/dog\", exist_ok=True)\n\nfor fname in os.listdir(src):\n    if fname.startswith(\"cat\"):\n        shutil.move(os.path.join(src, fname), os.path.join(dst, \"cat\", fname))\n    elif fname.startswith(\"dog\"):\n        shutil.move(os.path.join(src, fname), os.path.join(dst, \"dog\", fname))\n\n# 2. ImageDataGeneratorによる読み込み\ntrain_dir = dst\ntrain_datagen = ImageDataGenerator(rescale=1./255, validation_split=0.2)\n\ntrain_generator = train_datagen.flow_from_directory(\n    train_dir,\n    target_size=(150, 150),\n    batch_size=32,\n    class_mode='binary',\n    subset='training'\n)\nval_generator = train_datagen.flow_from_directory(\n    train_dir,\n    target_size=(150, 150),\n    batch_size=32,\n    class_mode='binary',\n    subset='validation'\n)\n\n# 3. InceptionV3 モデル構築（転移学習）\nbase_model = InceptionV3(weights='imagenet', include_top=False, input_shape=(150, 150, 3))\nx = base_model.output\nx = GlobalAveragePooling2D()(x)\nx = Dense(128, activation='relu')(x)\npredictions = Dense(1, activation='sigmoid')(x)\nmodel = Model(inputs=base_model.input, outputs=predictions)\n\nfor layer in base_model.layers:\n    layer.trainable = False\n\nmodel.compile(optimizer=Adam(learning_rate=0.0001),\n              loss='binary_crossentropy',\n              metrics=['accuracy'])\n\n# 4. 学習（3エポック）\nhistory = model.fit(\n    train_generator,\n    validation_data=val_generator,\n    epochs=3\n)\n\n# 5. 精度グラフの表示\nplt.plot(history.history['accuracy'], label='Train acc')\nplt.plot(history.history['val_accuracy'], label='Val acc')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-24T02:47:42.938457Z","iopub.execute_input":"2025-07-24T02:47:42.938761Z","iopub.status.idle":"2025-07-24T03:13:07.133531Z","shell.execute_reply.started":"2025-07-24T02:47:42.938735Z","shell.execute_reply":"2025-07-24T03:13:07.132585Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# テスト画像ディレクトリ\ntest_dir = \"/kaggle/working/test/test\"\n\n# テストデータ用のジェネレータ\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntest_generator = test_datagen.flow_from_directory(\n    directory=\"/kaggle/working/\",\n    classes=[\"test\"],\n    target_size=(150, 150),\n    batch_size=1,\n    class_mode=None,\n    shuffle=False\n)\n\n# 予測の実行\npredictions = model.predict(test_generator, verbose=1)\nlabels = predictions.ravel()  # sigmoid出力なのでそのまま確率値\n\n# ファイル名からid抽出（test/1234.jpg → 1234）\nfile_paths = test_generator.filenames\nids = [int(p.split(\"/\")[-1].split(\".\")[0]) for p in file_paths]\n\n# DataFrameの作成と保存\nsubmission_df = pd.DataFrame({\"id\": ids, \"label\": labels})\nsubmission_df.to_csv(\"submission.csv\", index=False)\nprint(\"submission.csv を保存しました。\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-24T03:13:07.134951Z","iopub.execute_input":"2025-07-24T03:13:07.135449Z"}},"outputs":[],"execution_count":null}]}