{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":31040,"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-01T14:10:31.942929Z","iopub.execute_input":"2025-07-01T14:10:31.943202Z","iopub.status.idle":"2025-07-01T14:10:32.540034Z","shell.execute_reply.started":"2025-07-01T14:10:31.943172Z","shell.execute_reply":"2025-07-01T14:10:32.539045Z"}},"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/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/test1.zip', 'r') as zip_ref:\n    zip_ref.extractall('/kaggle/working/test')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-01T14:10:32.541996Z","iopub.execute_input":"2025-07-01T14:10:32.542359Z","iopub.status.idle":"2025-07-01T14:10:48.829240Z","shell.execute_reply.started":"2025-07-01T14:10:32.542338Z","shell.execute_reply":"2025-07-01T14:10:48.828543Z"}},"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-01T14:10:48.830082Z","iopub.execute_input":"2025-07-01T14:10:48.830314Z","iopub.status.idle":"2025-07-01T14:10:53.152694Z","shell.execute_reply.started":"2025-07-01T14:10:48.830296Z","shell.execute_reply":"2025-07-01T14:10:53.151729Z"}},"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\ntrain_datagen = ImageDataGenerator(rescale=1./255,\n                                   rotation_range=20,\n                                   zoom_range=0.2,\n                                   horizontal_flip=True)\n\nval_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_directory(train_dir,\n                                                    target_size=(img_size, img_size),\n                                                    batch_size=batch_size,\n                                                    class_mode='binary')\n\nval_generator = val_datagen.flow_from_directory(val_dir,\n                                                target_size=(img_size, img_size),\n                                                batch_size=batch_size,\n                                                class_mode='binary')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-01T14:10:53.153710Z","iopub.execute_input":"2025-07-01T14:10:53.154202Z","iopub.status.idle":"2025-07-01T14:11:11.800071Z","shell.execute_reply.started":"2025-07-01T14:10:53.154173Z","shell.execute_reply":"2025-07-01T14:11:11.799171Z"}},"outputs":[],"execution_count":null},{"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()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-01T14:11:11.800944Z","iopub.execute_input":"2025-07-01T14:11:11.801500Z","iopub.status.idle":"2025-07-01T14:11:12.144750Z","shell.execute_reply.started":"2025-07-01T14:11:11.801478Z","shell.execute_reply":"2025-07-01T14:11:12.144008Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"学習","metadata":{}},{"cell_type":"code","source":"history = model.fit(train_generator,\n                    epochs=10,\n                    validation_data=val_generator)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-01T14:11:12.145687Z","iopub.execute_input":"2025-07-01T14:11:12.145985Z","iopub.status.idle":"2025-07-01T16:12:19.448992Z","shell.execute_reply.started":"2025-07-01T14:11:12.145964Z","shell.execute_reply":"2025-07-01T16:12:19.447203Z"}},"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)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-01T16:12:19.457183Z","iopub.execute_input":"2025-07-01T16:12:19.457723Z","iopub.status.idle":"2025-07-01T16:15:53.037286Z","shell.execute_reply.started":"2025-07-01T16:12:19.457677Z","shell.execute_reply":"2025-07-01T16:15:53.036443Z"}},"outputs":[],"execution_count":null}]}