{"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":"gpu","dataSources":[{"sourceId":5441,"databundleVersionId":38425,"sourceType":"competition"}],"dockerImageVersionId":31089,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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-25T03:50:09.175687Z","iopub.execute_input":"2025-07-25T03:50:09.175991Z","iopub.status.idle":"2025-07-25T03:50:09.183225Z","shell.execute_reply.started":"2025-07-25T03:50:09.175969Z","shell.execute_reply":"2025-07-25T03:50:09.182661Z"}},"outputs":[],"execution_count":null},{"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-25T03:50:09.184329Z","iopub.execute_input":"2025-07-25T03:50:09.184861Z","iopub.status.idle":"2025-07-25T03:50:18.914702Z","shell.execute_reply.started":"2025-07-25T03:50:09.184843Z","shell.execute_reply":"2025-07-25T03:50:18.914126Z"}},"outputs":[],"execution_count":null},{"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-25T03:50:18.915305Z","iopub.execute_input":"2025-07-25T03:50:18.915489Z","iopub.status.idle":"2025-07-25T03:50:22.687512Z","shell.execute_reply.started":"2025-07-25T03:50:18.915474Z","shell.execute_reply":"2025-07-25T03:50:22.686877Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import layers, models\n\nimg_size = 128\nbatch_size = 517\n\n# Resize + Padding 関数\ndef resize_and_pad(image, target_size=128):\n    shape = tf.shape(image)[:2]\n    h, w = shape[0], shape[1]\n\n    # 長辺に合わせてスケーリング\n    scale = tf.cast(target_size, tf.float32) / tf.cast(tf.reduce_max([h, w]), tf.float32)\n    new_h = tf.cast(tf.cast(h, tf.float32) * scale, tf.int32)\n    new_w = tf.cast(tf.cast(w, tf.float32) * scale, tf.int32)\n\n    image = tf.image.resize(image, [new_h, new_w])\n\n    # 中央パディング\n    pad_h = target_size - new_h\n    pad_w = target_size - new_w\n    image = tf.image.pad_to_bounding_box(image,\n                                         offset_height=pad_h // 2,\n                                         offset_width=pad_w // 2,\n                                         target_height=target_size,\n                                         target_width=target_size)\n    return image\n\n#  拡張＋前処理\ndef preprocess(image, label):\n    image = resize_and_pad(image, target_size=img_size)\n    image = tf.cast(image, tf.float32) / 255.0\n\n    # 拡張\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_brightness(image, 0.2)\n    image = tf.image.random_contrast(image, 0.8, 1.2)\n\n    return image, label\n\n# バリデーション用（拡張なし）\ndef preprocess_val(image, label):\n    image = resize_and_pad(image, target_size=img_size)\n    image = tf.cast(image, tf.float32) / 255.0\n    return image, label\n\n# データセット作成関数\ndef get_dataset(dir_path, batch_size=32, is_training=True):\n    dataset = tf.keras.utils.image_dataset_from_directory(\n        dir_path,\n        image_size=(256, 256),  # 仮設定、あとで resize_and_pad される\n        batch_size=batch_size,\n        label_mode='binary'\n    )\n\n    if is_training:\n        dataset = dataset.map(preprocess, num_parallel_calls=tf.data.AUTOTUNE)\n        dataset = dataset.shuffle(1000)\n    else:\n        dataset = dataset.map(preprocess_val, num_parallel_calls=tf.data.AUTOTUNE)\n\n    return dataset.prefetch(tf.data.AUTOTUNE)\n\n# データセットを取得\ntrain_dataset = get_dataset(train_dir, batch_size=batch_size, is_training=True)\nval_dataset = get_dataset(val_dir, batch_size=batch_size, is_training=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T03:50:22.688966Z","iopub.execute_input":"2025-07-25T03:50:22.689218Z","iopub.status.idle":"2025-07-25T03:50:23.714448Z","shell.execute_reply.started":"2025-07-25T03:50:22.689201Z","shell.execute_reply":"2025-07-25T03:50:23.713667Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nimg_size = 150\nbatch_size = 1024\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')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T03:50:23.715224Z","iopub.execute_input":"2025-07-25T03:50:23.715497Z","iopub.status.idle":"2025-07-25T03:50:23.951285Z","shell.execute_reply.started":"2025-07-25T03:50:23.715471Z","shell.execute_reply":"2025-07-25T03:50:23.950732Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom tensorflow.keras.layers import GlobalAveragePooling2D\n\nmodel = Sequential([\n    Conv2D(64, (3,3), activation='relu', input_shape=(img_size, img_size, 3)),\n    MaxPooling2D(2,2),\n    Conv2D(32, (3,3), activation='relu'),\n    MaxPooling2D(2,2),\n    Conv2D(32, (3,3), activation='relu'),\n    MaxPooling2D(2,2),\n    GlobalAveragePooling2D(),     # ここをFlatten()の代わりに\n    Dropout(0.2),\n    Dense(128, 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-25T03:50:23.952002Z","iopub.execute_input":"2025-07-25T03:50:23.952296Z","iopub.status.idle":"2025-07-25T03:50:24.014719Z","shell.execute_reply.started":"2025-07-25T03:50:23.952270Z","shell.execute_reply":"2025-07-25T03:50:24.014153Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.callbacks import *\n\nf_log = '/kaggle/working/weight'\nes_cb = EarlyStopping(monitor='val_loss', patience=1000, verbose=1, mode=\"auto\")\nf_path = os.path.join(f_log, 'weights.' '{epoch:03d}-{loss:.4f}-{val_loss:.4f}.h5')\ncp_cb = ModelCheckpoint(filepath=f_path, monitor='val_loss', verbose=1,\n                            save_best_only=True, mode=\"auto\", save_weights_only=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T03:50:24.015399Z","iopub.execute_input":"2025-07-25T03:50:24.015640Z","iopub.status.idle":"2025-07-25T03:50:24.019570Z","shell.execute_reply.started":"2025-07-25T03:50:24.015617Z","shell.execute_reply":"2025-07-25T03:50:24.019018Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"log = model.fit(train_dataset,\n                    epochs=30,\n                    validation_data=val_dataset,callbacks=[es_cb, cp_cb], shuffle=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T03:50:24.020136Z","iopub.execute_input":"2025-07-25T03:50:24.020355Z","iopub.status.idle":"2025-07-25T04:04:40.358035Z","shell.execute_reply.started":"2025-07-25T03:50:24.020340Z","shell.execute_reply":"2025-07-25T04:04:40.357429Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# モデルの学習履歴 log（例：model.fit(...) の戻り値）\nloss = log.history['loss']\nval_loss = log.history['val_loss']\nepochs = range(1, len(loss) + 1)\n\nplt.plot(epochs, loss, 'bo-', label='Training Loss')      # 青い点線\nplt.plot(epochs, val_loss, 'ro-', label='Validation Loss') # 赤い点線\nplt.title('Training and Validation Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.grid(True)\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T04:04:40.360367Z","iopub.execute_input":"2025-07-25T04:04:40.360598Z","iopub.status.idle":"2025-07-25T04:04:40.659164Z","shell.execute_reply.started":"2025-07-25T04:04:40.360580Z","shell.execute_reply":"2025-07-25T04:04:40.658399Z"}},"outputs":[],"execution_count":null},{"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-25T04:04:40.660001Z","iopub.execute_input":"2025-07-25T04:04:40.660310Z","iopub.status.idle":"2025-07-25T04:05:16.924204Z","shell.execute_reply.started":"2025-07-25T04:04:40.660284Z","shell.execute_reply":"2025-07-25T04:05:16.923633Z"}},"outputs":[],"execution_count":null}]}