{"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-05T11:40:46.499751Z","iopub.execute_input":"2025-07-05T11:40:46.500064Z","iopub.status.idle":"2025-07-05T11:40:46.831441Z","shell.execute_reply.started":"2025-07-05T11:40:46.500037Z","shell.execute_reply":"2025-07-05T11:40:46.830666Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Required imports for zip extraction, file operations, regex handling, and TensorFlow image preprocessing and modeling","metadata":{}},{"cell_type":"code","source":"import zipfile # zipファイルの解凍に必要\nimport tensorflow as tf # 機械学習に必要\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator # データの正規化に必要\nfrom tensorflow.keras import layers, models # レイヤークラス, 学習モデル\nfrom tensorflow.keras.preprocessing import image # 画像の前処理に必要\nimport shutil # クラス分けに必要\nimport glob # ファイルのソートに必要\nimport re","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T11:40:46.832635Z","iopub.execute_input":"2025-07-05T11:40:46.833046Z","iopub.status.idle":"2025-07-05T11:41:04.113128Z","shell.execute_reply.started":"2025-07-05T11:40:46.833025Z","shell.execute_reply":"2025-07-05T11:41:04.111661Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Extract and unzip the specified training dataset into the working directory.","metadata":{}},{"cell_type":"code","source":"file_path = '/kaggle/input/dogs-vs-cats/train.zip'\nout_path = '/kaggle/working'\n\nwith zipfile.ZipFile(file_path, 'r') as file:\n    file.extractall(out_path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T11:41:04.114326Z","iopub.execute_input":"2025-07-05T11:41:04.114886Z","iopub.status.idle":"2025-07-05T11:41:13.939874Z","shell.execute_reply.started":"2025-07-05T11:41:04.114861Z","shell.execute_reply":"2025-07-05T11:41:13.938963Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Organize extracted training images into ‘cats’ and ‘dogs’ folders based on their filename prefixes.","metadata":{}},{"cell_type":"code","source":"train_dir = '/kaggle/working/train'\ncat_dir = os.path.join(train_dir, 'cats')\ndog_dir = os.path.join(train_dir, 'dogs')\n\nos.makedirs(cat_dir, exist_ok=True)\nos.makedirs(dog_dir, exist_ok=True)\n\nfor filename in os.listdir(train_dir):\n    \n    file_path = os.path.join(train_dir, filename)\n    if not os.path.isfile(file_path):\n        continue\n    \n    if filename.lower().startswith('cat'):\n        shutil.move(os.path.join(train_dir, filename), os.path.join(cat_dir, filename))\n    elif filename.lower().startswith('dog'):\n        shutil.move(os.path.join(train_dir, filename), os.path.join(dog_dir, filename))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T11:41:13.942903Z","iopub.execute_input":"2025-07-05T11:41:13.943177Z","iopub.status.idle":"2025-07-05T11:41:14.934133Z","shell.execute_reply.started":"2025-07-05T11:41:13.943157Z","shell.execute_reply":"2025-07-05T11:41:14.933141Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Extract and unzip the test1 dataset archive into the working directory.","metadata":{}},{"cell_type":"code","source":"file_path = '/kaggle/input/dogs-vs-cats/test1.zip'\nout_path = '/kaggle/working'\n\nwith zipfile.ZipFile(file_path, 'r') as file:\n    file.extractall(out_path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T11:41:14.935168Z","iopub.execute_input":"2025-07-05T11:41:14.935487Z","iopub.status.idle":"2025-07-05T11:41:19.575533Z","shell.execute_reply.started":"2025-07-05T11:41:14.935457Z","shell.execute_reply":"2025-07-05T11:41:19.574644Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Initialize image data generators for both training and testing by rescaling pixel values by 1/255.","metadata":{}},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(rescale=1./255)\ntest_datagen = ImageDataGenerator(rescale=1./255)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T11:41:19.576533Z","iopub.execute_input":"2025-07-05T11:41:19.576828Z","iopub.status.idle":"2025-07-05T11:41:19.581807Z","shell.execute_reply.started":"2025-07-05T11:41:19.576807Z","shell.execute_reply":"2025-07-05T11:41:19.580843Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Set up a training data generator to load 150×150 images in batches of 32 from the train directory for binary classification.","metadata":{}},{"cell_type":"code","source":"train_generator = train_datagen.flow_from_directory(\n    '/kaggle/working/train',\n    target_size=(150, 150),\n    batch_size=32,\n    class_mode='binary'\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T11:41:19.582891Z","iopub.execute_input":"2025-07-05T11:41:19.583179Z","iopub.status.idle":"2025-07-05T11:41:20.557355Z","shell.execute_reply.started":"2025-07-05T11:41:19.583157Z","shell.execute_reply":"2025-07-05T11:41:20.556389Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Initialize a test data generator to load 150×150 images in batches of 32 from the test1 directory for binary classification.","metadata":{}},{"cell_type":"code","source":"test_generator = test_datagen.flow_from_directory(\n    '/kaggle/working/test1',\n    target_size=(150, 150),\n    batch_size=32,\n    class_mode='binary'\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T11:41:20.558295Z","iopub.execute_input":"2025-07-05T11:41:20.558602Z","iopub.status.idle":"2025-07-05T11:41:20.645133Z","shell.execute_reply.started":"2025-07-05T11:41:20.558576Z","shell.execute_reply":"2025-07-05T11:41:20.644141Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Define a sequential CNN model with convolution, pooling, and dense layers for binary image classification.","metadata":{}},{"cell_type":"code","source":"model = models.Sequential([\n    layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)), # 画像化から特徴を抽出する\n    layers.MaxPooling2D(2, 2), # 重要な情報を残しつつ、画像サイズを圧縮\n    layers.Conv2D(64, (3, 3), activation='relu'),\n    layers.MaxPooling2D(2, 2),\n    layers.Conv2D(128, (3, 3), activation='relu'),\n    layers.MaxPooling2D(2, 2),\n    layers.Flatten(), # 畳み込み層の出力を、1次元のベクトルに変換\n    layers.Dense(512, activation='relu'), # 中間特徴を学習し、分析精度を向上させる\n    layers.Dense(1, activation='sigmoid') # sigmoidにより0-1の確率を算出\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T11:41:20.645812Z","iopub.execute_input":"2025-07-05T11:41:20.646053Z","iopub.status.idle":"2025-07-05T11:41:20.946207Z","shell.execute_reply.started":"2025-07-05T11:41:20.646034Z","shell.execute_reply":"2025-07-05T11:41:20.944716Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Compile the model with binary crossentropy loss, Adam optimizer, and accuracy metric.","metadata":{}},{"cell_type":"code","source":"model.compile(\n    loss='binary_crossentropy', # 損失関数\n    optimizer='adam', # 最適化アルゴリズム\n    metrics=['accuracy'] # 評価指標 accuracy：予測が正解だった割合\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T11:41:20.949849Z","iopub.execute_input":"2025-07-05T11:41:20.950178Z","iopub.status.idle":"2025-07-05T11:41:20.965359Z","shell.execute_reply.started":"2025-07-05T11:41:20.950155Z","shell.execute_reply":"2025-07-05T11:41:20.964541Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Train the model for 10 epochs using the training data generator.","metadata":{}},{"cell_type":"code","source":"history = model.fit(\n    train_generator,\n    epochs=10, # 訓練データを10回学習する\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T11:41:20.966202Z","iopub.execute_input":"2025-07-05T11:41:20.966765Z","iopub.status.idle":"2025-07-05T13:47:12.582069Z","shell.execute_reply.started":"2025-07-05T11:41:20.966738Z","shell.execute_reply":"2025-07-05T13:47:12.581268Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Save the trained model to the specified H5 file for later reuse.","metadata":{}},{"cell_type":"code","source":"file_path = '/kaggle/working/cnn.h5'\n\nmodel.save(file_path)\n# model = load_model(file_path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T13:47:12.583327Z","iopub.execute_input":"2025-07-05T13:47:12.583672Z","iopub.status.idle":"2025-07-05T13:47:13.035726Z","shell.execute_reply.started":"2025-07-05T13:47:12.583643Z","shell.execute_reply":"2025-07-05T13:47:13.034934Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"List all files in the test directory, sort them numerically by filename, and build their full path list.","metadata":{}},{"cell_type":"code","source":"# ファイル一覧を所得\ntest_dir = '/kaggle/working/test1'\ntest_files = os.listdir(test_dir)\n\n# 数値順にソートする関数\ndef extract_number(filename):\n    match = re.search(r'\\d+', filename)\n    return int(match.group()) if match else -1\n\n# 数値順にソート\nsorted_files = sorted(test_files, key=extract_number)\n\n# 画像ファイルのフルパスリスト\nimage_path_list = [os.path.join(test_dir, image) for image in sorted_files]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T13:47:13.036597Z","iopub.execute_input":"2025-07-05T13:47:13.036854Z","iopub.status.idle":"2025-07-05T13:47:13.078932Z","shell.execute_reply.started":"2025-07-05T13:47:13.036833Z","shell.execute_reply":"2025-07-05T13:47:13.077949Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Preprocess images into a normalized batch of size 150×150 and perform model inference to obtain predictions.","metadata":{}},{"cell_type":"code","source":"# 前処理\nimages = [image.img_to_array(image.load_img(path, target_size=(150, 150))) / 255.0 for path in image_path_list]\nbatch = np.array(images)\n\n# 推論\npreds = model.predict(batch)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T13:47:13.079924Z","iopub.execute_input":"2025-07-05T13:47:13.080149Z","iopub.status.idle":"2025-07-05T13:49:31.290118Z","shell.execute_reply.started":"2025-07-05T13:47:13.080130Z","shell.execute_reply":"2025-07-05T13:49:31.288920Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Extract image IDs, convert predictions to binary labels, and save the results as a CSV file.","metadata":{}},{"cell_type":"code","source":"# IDの取得\nids = [os.path.splitext(os.path.basename(path))[0] for path in image_path_list]\n\n# ラベルの取得\nlabels = [1 if p[0] > 0.5 else 0 for p in preds]\n\n# CSVで保存\ndf = pd.DataFrame({'id': ids, 'label': labels})\ndf.to_csv('submission.csv', index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T14:18:35.371739Z","iopub.execute_input":"2025-07-05T14:18:35.372070Z","iopub.status.idle":"2025-07-05T14:18:35.436994Z","shell.execute_reply.started":"2025-07-05T14:18:35.372045Z","shell.execute_reply":"2025-07-05T14:18:35.435845Z"}},"outputs":[],"execution_count":null}]}