{"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-22T05:52:23.217243Z","iopub.execute_input":"2025-07-22T05:52:23.217668Z","iopub.status.idle":"2025-07-22T05:52:23.226642Z","shell.execute_reply.started":"2025-07-22T05:52:23.217640Z","shell.execute_reply":"2025-07-22T05:52:23.225740Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"データの確認と解凍","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# test1.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":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-22T05:52:23.228449Z","iopub.execute_input":"2025-07-22T05:52:23.229451Z","iopub.status.idle":"2025-07-22T05:52:35.226034Z","shell.execute_reply.started":"2025-07-22T05:52:23.229420Z","shell.execute_reply":"2025-07-22T05:52:35.224746Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"学習用データを整理する（学習/検証用に分割）","metadata":{}},{"cell_type":"code","source":"import shutil\nimport os\nfrom sklearn.model_selection import train_test_split\n\noriginal_dir = '/kaggle/working/train/train'\nbase_dir = '/kaggle/working/data'\ntrain_dir = os.path.join(base_dir, 'train')\nval_dir = os.path.join(base_dir, 'val')\n#クラス別のフォルダ作成\nfor category in ['dog', 'cat']:\n    os.makedirs(os.path.join(train_dir, category), exist_ok=True)\n    os.makedirs(os.path.join(val_dir, category), exist_ok=True)\n#学習・検証に分割\nall_filenames = os.listdir(original_dir)\ntrain_filenames, val_filenames = train_test_split(all_filenames, test_size=0.2, random_state=42)\n#ファイルのコピー\nfor filename in train_filenames:\n    if 'dog' in filename:\n        shutil.copy(os.path.join(original_dir, filename), os.path.join(train_dir, 'dog', filename))\n    else:\n        shutil.copy(os.path.join(original_dir, filename), os.path.join(train_dir, 'cat', filename))\n\nfor filename in val_filenames:\n    if 'dog' in filename:\n        shutil.copy(os.path.join(original_dir, filename), os.path.join(val_dir, 'dog', filename))\n    else:\n        shutil.copy(os.path.join(original_dir, filename), os.path.join(val_dir, 'cat', filename))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-22T05:52:35.227102Z","iopub.execute_input":"2025-07-22T05:52:35.227416Z","iopub.status.idle":"2025-07-22T05:52:40.231258Z","shell.execute_reply.started":"2025-07-22T05:52:35.227384Z","shell.execute_reply":"2025-07-22T05:52:40.230309Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"前処理（データの拡張）","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nimg_size = 150\nbatch_size = 32\n\n# データ拡張付き：ランダム回転・ズーム・左右反転など\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,\n    rotation_range=20,\n    zoom_range=0.2,\n    shear_range=0.2,\n    width_shift_range=0.1,\n    height_shift_range=0.1,\n    horizontal_flip=True\n)\n\n# 検証用はリスケーリングのみ\nval_datagen = ImageDataGenerator(rescale=1./255)\n\n# フォルダから読み込み\ntrain_generator = train_datagen.flow_from_directory(\n    train_dir,\n    target_size=(img_size, img_size),\n    batch_size=batch_size,\n    class_mode='binary'\n)\n\nval_generator = val_datagen.flow_from_directory(\n    val_dir,\n    target_size=(img_size, img_size),\n    batch_size=batch_size,\n    class_mode='binary'\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-22T05:52:40.232921Z","iopub.execute_input":"2025-07-22T05:52:40.233280Z","iopub.status.idle":"2025-07-22T05:52:40.507431Z","shell.execute_reply.started":"2025-07-22T05:52:40.233260Z","shell.execute_reply":"2025-07-22T05:52:40.506570Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"CNNモデルの構築","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\n\nmodel = Sequential([\n    Conv2D(32, (3,3), activation='relu', input_shape=(img_size, img_size, 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    Flatten(),\n    Dropout(0.5),\n    Dense(512, activation='relu'),\n    Dense(1, activation='sigmoid')\n])\n\nmodel.compile(loss='binary_crossentropy',\n              optimizer='adam',\n              metrics=['accuracy'])\n\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-22T05:52:40.508321Z","iopub.execute_input":"2025-07-22T05:52:40.508619Z","iopub.status.idle":"2025-07-22T05:52:41.320778Z","shell.execute_reply.started":"2025-07-22T05:52:40.508600Z","shell.execute_reply":"2025-07-22T05:52:41.320094Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"モデルの学習","metadata":{}},{"cell_type":"code","source":"history = model.fit(train_generator,\n                    epochs=3,\n                    validation_data=val_generator)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-22T05:52:41.321599Z","iopub.execute_input":"2025-07-22T05:52:41.321884Z","iopub.status.idle":"2025-07-22T06:30:06.499401Z","shell.execute_reply.started":"2025-07-22T05:52:41.321854Z","shell.execute_reply":"2025-07-22T06:30:06.497289Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"テストデータの予測と提出ファイルの作成","metadata":{}},{"cell_type":"code","source":"test_dir = '/kaggle/working/test/test'\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntest_generator = test_datagen.flow_from_directory(\n    '/kaggle/working/',\n    classes=['test'],\n    target_size=(img_size, img_size),\n    batch_size=1,\n    class_mode=None,\n    shuffle=False)\n\npredictions = model.predict(test_generator, verbose=1)\npredicted_classes = predictions.ravel()\n\nimport pandas as pd\n\nfilenames = test_generator.filenames\nids = [int(os.path.basename(fname).split('.')[0]) for fname in filenames]\n\nsubmission = pd.DataFrame({'id': ids, 'label': predicted_classes})\nsubmission.sort_values('id', inplace=True)\nsubmission.to_csv('/kaggle/working/submission.csv', index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-22T06:30:06.503250Z","iopub.execute_input":"2025-07-22T06:30:06.503687Z","iopub.status.idle":"2025-07-22T06:33:29.436083Z","shell.execute_reply.started":"2025-07-22T06:30:06.503648Z","shell.execute_reply":"2025-07-22T06:33:29.435316Z"}},"outputs":[],"execution_count":null}]}