{"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":"gpu","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":31040,"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},"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},"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\n\noriginal_train_dir = '/kaggle/working/train/train'\n\n\nbase_dir = '/kaggle/working/data'\ntrain_dir = os.path.join(base_dir, 'train')\nval_dir = os.path.join(base_dir, 'val')\ntest_dir = os.path.join(base_dir, 'test')\n\n\nfor dir_path in [train_dir, val_dir, test_dir]:\n    for category in ['dog', 'cat']:\n        os.makedirs(os.path.join(dir_path, category), exist_ok=True)\n\nall_filenames = os.listdir(original_train_dir)\n\n# 1回目の分割 → train（90%）と test候補（10%）\ntrain_val_filenames, test_filenames = train_test_split(all_filenames, test_size=0.1, random_state=42)\n\n# 2回目の分割 → train_val をさらに train（90%）と val（10%）に\ntrain_filenames, val_filenames = train_test_split(train_val_filenames, test_size=0.1, random_state=42)\n\ndef copy_files(filenames, dst_dir):\n    for filename in filenames:\n        src = os.path.join(original_train_dir, filename)\n        if 'dog' in filename:\n            dst = os.path.join(dst_dir, 'dog', filename)\n        else:\n            dst = os.path.join(dst_dir, 'cat', filename)\n        shutil.copy(src, dst)\n\ncopy_files(train_filenames, train_dir)\ncopy_files(val_filenames, val_dir)\ncopy_files(test_filenames, test_dir)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"前処理","metadata":{}},{"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)\n","metadata":{"trusted":true},"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(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    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()\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"callback\n1. earlystopping(無駄な学習を防ぐ)\n1. modelcheckpointはいらないかも..","metadata":{}},{"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},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"学習","metadata":{}},{"cell_type":"code","source":"log = model.fit(train_dataset,\n                    epochs=50,\n                    validation_data=val_dataset,callbacks=[es_cb, cp_cb], shuffle=True)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"学習曲線の表示","metadata":{}},{"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()\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"テストデータの予測\n0.5は閾値","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.metrics import accuracy_score\n\n# テストデータのディレクトリ\ntest_dir = '/kaggle/working/data/test'\nimg_size = 128  # 適宜定義\n\n# Generator の設定\ntest_datagen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_datagen.flow_from_directory(\n    test_dir,\n    target_size=(img_size, img_size),\n    batch_size=1,\n    class_mode='binary',\n    shuffle=False\n)\n\n# 正解ラベル（generatorから取得）\ny_true = test_generator.classes\n\n# モデルから予測（generatorを使う）\npredicted_probs = model.predict(test_generator, verbose=1).ravel()\n\n# 0.4を閾値にして2クラス分類\ny_pred = (predicted_probs >= 0.5).astype(int)\n\n# 指標を計算\nacc = accuracy_score(y_true, y_pred)\n\nprint(f'Accuracy : {acc:.4f}')","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_generator からファイル名一覧取得\nfilenames = test_generator.filenames\n\n# ファイル名の先頭の数字をIDとして抽出（例: '123.jpg' → 123）\nids = []\nfor fname in filenames:\n    base = os.path.basename(fname)\n    id_str = base.split('.')[0]\n    try:\n        ids.append(int(id_str))\n    except ValueError:\n        ids.append(0)  # 変換できない場合の処理\n\n# 予測ラベルは y_pred に合わせる（0/1 の分類結果）\nsubmission = pd.DataFrame({'id': ids, 'label': y_pred})\n\n# id で昇順ソート\nsubmission.sort_values('id', inplace=True)\n\n# CSVファイルに書き出し（ヘッダー付き、indexなし）\nsubmission.to_csv('/kaggle/working/submission.csv', index=False)\n\n# 最初の10行を表示\nprint(submission.head(10))\n","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}