{"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":"nvidiaTeslaT4","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-25T07:53:27.307010Z","iopub.execute_input":"2025-07-25T07:53:27.307361Z","iopub.status.idle":"2025-07-25T07:53:28.989313Z","shell.execute_reply.started":"2025-07-25T07:53:27.307323Z","shell.execute_reply":"2025-07-25T07:53:28.988567Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport os, glob, time, copy, zipfile\nfrom PIL import Image\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.utils.data as data\nimport torch.nn.functional as F\nfrom torchvision import models, transforms","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T07:53:28.990807Z","iopub.execute_input":"2025-07-25T07:53:28.991133Z","iopub.status.idle":"2025-07-25T07:53:35.426414Z","shell.execute_reply.started":"2025-07-25T07:53:28.991115Z","shell.execute_reply":"2025-07-25T07:53:35.425687Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"img_size = 224\nbatch_size = 16\nepochs = 30","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T07:53:35.427238Z","iopub.execute_input":"2025-07-25T07:53:35.427642Z","iopub.status.idle":"2025-07-25T07:53:35.431436Z","shell.execute_reply.started":"2025-07-25T07:53:35.427616Z","shell.execute_reply":"2025-07-25T07:53:35.430726Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# データを初期化\n!rm -rf ../data","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T07:53:35.432282Z","iopub.execute_input":"2025-07-25T07:53:35.432486Z","iopub.status.idle":"2025-07-25T07:53:35.576985Z","shell.execute_reply.started":"2025-07-25T07:53:35.432470Z","shell.execute_reply":"2025-07-25T07:53:35.576212Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# データの解凍\nbase_dir = '/kaggle/input/dogs-vs-cats-redux-kernels-edition'\ndata_dir = \"/kaggle/working/data/\"\ntrain_dir = '/kaggle/working/data/train'\ntest_dir = '/kaggle/working/data/test'\n\nos.makedirs('./data', exist_ok=True)\n\n# 学習データの解凍\nwith zipfile.ZipFile(os.path.join(base_dir, 'train.zip')) as train_zip:\n    train_zip.extractall(data_dir)\n    \n#推論データの解凍\nwith zipfile.ZipFile(os.path.join(base_dir, 'test.zip')) as test_zip:\n    test_zip.extractall(data_dir)\n\n\ntrain_list = glob.glob(os.path.join(train_dir, '*.jpg'))\ntest_list = glob.glob(os.path.join(test_dir, '*.jpg'))\n\n# 学習データから検証データを分割(8:2)\ntrain_list, val_list = train_test_split(train_list, test_size=0.2)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T07:53:35.579212Z","iopub.execute_input":"2025-07-25T07:53:35.579406Z","iopub.status.idle":"2025-07-25T07:53:48.474730Z","shell.execute_reply.started":"2025-07-25T07:53:35.579385Z","shell.execute_reply":"2025-07-25T07:53:48.474154Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class ImageTransform():\n    \n    def __init__(self, resize, mean, std):\n        self.data_transform = {\n            'train': transforms.Compose([\n                transforms.Resize((resize, resize)),  # 画像サイズを224にリサイズ\n                transforms.RandomHorizontalFlip(),    # ランダム水平反転\n                transforms.RandomVerticalFlip(),      # ランダム垂直反転\n                transforms.ToTensor(),                # テンソルに変換\n                transforms.Normalize(mean, std)       # 正規化\n            ]),\n            'val': transforms.Compose([\n                transforms.Resize((resize, resize)),  # 画像サイズを224にリサイズ\n                transforms.ToTensor(),                # テンソルに変換\n                transforms.Normalize(mean, std)       # 正規化\n            ])\n        }\n        \n    def __call__(self, img, phase):\n        return self.data_transform[phase](img)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T07:53:48.475389Z","iopub.execute_input":"2025-07-25T07:53:48.475583Z","iopub.status.idle":"2025-07-25T07:53:48.481244Z","shell.execute_reply.started":"2025-07-25T07:53:48.475567Z","shell.execute_reply":"2025-07-25T07:53:48.480460Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"size = 224\nmean = (0.485, 0.456, 0.406)\nstd = (0.229, 0.224, 0.225)\nclass ImageDataset(data.Dataset):\n    \n    def __init__(self, file_list, transform=None, phase='train'):    \n        self.file_list = file_list\n        self.transform = transform\n        self.phase = phase\n        \n    def __len__(self):\n        return len(self.file_list)\n    \n    def __getitem__(self, idx):\n        \n        img_path = self.file_list[idx]\n        img = Image.open(img_path)\n        \n        img_transformed = self.transform(img, self.phase)\n        \n        # ファイル名からラベルを取得\n        label = img_path.split('/')[-1].split('.')[0]\n        if label == 'dog': #ファイル名がdogであれば 1\n            label = 1\n        elif label == 'cat':#ファイル名がcatであれば 0\n            label = 0\n\n        return img_transformed, label\n\n\n# データの前処理\ntrain_dataset = ImageDataset(train_list, transform=ImageTransform(size, mean, std), phase='train')\nval_dataset = ImageDataset(val_list, transform=ImageTransform(size, mean, std), phase='val')\n\n# データの読み込み\ntrain_dataloader = data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\nval_dataloader = data.DataLoader(val_dataset, batch_size=batch_size, shuffle=False)\n\ndataloader_dict = {'train': train_dataloader, 'val': val_dataloader}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T07:53:48.481951Z","iopub.execute_input":"2025-07-25T07:53:48.482423Z","iopub.status.idle":"2025-07-25T07:53:48.575129Z","shell.execute_reply.started":"2025-07-25T07:53:48.482395Z","shell.execute_reply":"2025-07-25T07:53:48.574623Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\n\ndef get_label_from_path(path):\n    filename = os.path.basename(path)\n    if filename.startswith('dog'):\n        return 1\n    else:\n        return 0\n\ntrain_labels = np.array([get_label_from_path(p) for p in train_list])\nval_labels = np.array([get_label_from_path(p) for p in val_list])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T07:53:48.575840Z","iopub.execute_input":"2025-07-25T07:53:48.576071Z","iopub.status.idle":"2025-07-25T07:53:48.606120Z","shell.execute_reply.started":"2025-07-25T07:53:48.576049Z","shell.execute_reply":"2025-07-25T07:53:48.605569Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ndef get_label_from_path(path):\n    filename = os.path.basename(path)\n    return 'dog' if filename.startswith('dog') else 'cat'\n\ntrain_labels = [get_label_from_path(p) for p in train_list]\nval_labels = [get_label_from_path(p) for p in val_list]\n\ndf_train = pd.DataFrame({'filename': train_list, 'label': train_labels})\ndf_val = pd.DataFrame({'filename': val_list, 'label': val_labels})\n\nimg_size = 128\n\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,\n    horizontal_flip=True,\n    rotation_range=10\n)\nval_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_gen = train_datagen.flow_from_dataframe(\n    df_train, \n    x_col='filename',\n    y_col='label',\n    target_size=(img_size, img_size),\n    class_mode='binary',\n    batch_size=32,\n    shuffle=True\n)\nval_gen = val_datagen.flow_from_dataframe(\n    df_val,\n    x_col='filename',\n    y_col='label',\n    target_size=(img_size, img_size),\n    class_mode='binary',\n    batch_size=32,\n    shuffle=False\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T07:53:48.606822Z","iopub.execute_input":"2025-07-25T07:53:48.607056Z","iopub.status.idle":"2025-07-25T07:54:02.684115Z","shell.execute_reply.started":"2025-07-25T07:53:48.607036Z","shell.execute_reply":"2025-07-25T07:54:02.683536Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"base_dir = '/kaggle/input/dogs-vs-cats-redux-kernels-edition'\ndata_dir = \"/kaggle/working/data/\"\ntrain_dir = '/kaggle/working/data/train'\ntest_dir = '/kaggle/working/data/test'\n\nos.makedirs(data_dir, exist_ok=True)\n\n# zip解凍\nimport zipfile\nwith zipfile.ZipFile(os.path.join(base_dir, 'train.zip')) as train_zip:\n    train_zip.extractall(data_dir)\nwith zipfile.ZipFile(os.path.join(base_dir, 'test.zip')) as test_zip:\n    test_zip.extractall(data_dir)\n\nimport glob\n# 画像ファイル一覧\ntrain_list_all = glob.glob(os.path.join(train_dir, '*.jpg'))\ntest_list = glob.glob(os.path.join(test_dir, '*.jpg'))\n\n# train/val分割\nfrom sklearn.model_selection import train_test_split\ntrain_list, val_list = train_test_split(train_list_all, test_size=0.2, random_state=42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T07:54:02.684968Z","iopub.execute_input":"2025-07-25T07:54:02.685423Z","iopub.status.idle":"2025-07-25T07:54:12.752667Z","shell.execute_reply.started":"2025-07-25T07:54:02.685404Z","shell.execute_reply":"2025-07-25T07:54:12.751874Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ラベル作成データフレイム化\ndef get_label_from_path(path):\n    filename = os.path.basename(path)\n    return 'dog' if filename.startswith('dog') else 'cat'\n\ntrain_labels = [get_label_from_path(p) for p in train_list]\nval_labels = [get_label_from_path(p) for p in val_list]\n\ndf_train = pd.DataFrame({'filename': train_list, 'label': train_labels})\ndf_val = pd.DataFrame({'filename': val_list, 'label': val_labels})","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T07:54:12.753429Z","iopub.execute_input":"2025-07-25T07:54:12.753658Z","iopub.status.idle":"2025-07-25T07:54:12.776864Z","shell.execute_reply.started":"2025-07-25T07:54:12.753640Z","shell.execute_reply":"2025-07-25T07:54:12.776098Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n#データローダーの作成\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,\n    horizontal_flip=True,\n    rotation_range=10\n)\nval_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_gen = train_datagen.flow_from_dataframe(\n    df_train, \n    x_col='filename',\n    y_col='label',\n    target_size=(img_size, img_size),\n    class_mode='binary',\n    batch_size=8,\n    shuffle=True\n)\nval_gen = val_datagen.flow_from_dataframe(\n    df_val,\n    x_col='filename',\n    y_col='label',\n    target_size=(img_size, img_size),\n    class_mode='binary',\n    batch_size=8,\n    shuffle=False\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T07:54:12.777616Z","iopub.execute_input":"2025-07-25T07:54:12.777812Z","iopub.status.idle":"2025-07-25T07:54:13.577617Z","shell.execute_reply.started":"2025-07-25T07:54:12.777796Z","shell.execute_reply":"2025-07-25T07:54:13.577032Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install -q keras-cv","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T07:54:13.578263Z","iopub.execute_input":"2025-07-25T07:54:13.578698Z","iopub.status.idle":"2025-07-25T07:54:30.466610Z","shell.execute_reply.started":"2025-07-25T07:54:13.578677Z","shell.execute_reply":"2025-07-25T07:54:30.465695Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow import keras","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T07:54:30.470837Z","iopub.execute_input":"2025-07-25T07:54:30.471106Z","iopub.status.idle":"2025-07-25T07:54:30.475099Z","shell.execute_reply.started":"2025-07-25T07:54:30.471082Z","shell.execute_reply":"2025-07-25T07:54:30.474367Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ndf_test = pd.DataFrame({'filename': test_list})\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\ntest_gen = test_datagen.flow_from_dataframe(\n    df_test,\n    x_col='filename',\n    class_mode=None,\n    target_size=(img_size, img_size),\n    batch_size=1,\n    shuffle=False\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T07:54:30.475862Z","iopub.execute_input":"2025-07-25T07:54:30.476180Z","iopub.status.idle":"2025-07-25T07:54:30.564921Z","shell.execute_reply.started":"2025-07-25T07:54:30.476152Z","shell.execute_reply":"2025-07-25T07:54:30.564439Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install -q transformers timm","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T07:54:30.565564Z","iopub.execute_input":"2025-07-25T07:54:30.565724Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from transformers import ViTForImageClassification, ViTImageProcessor\nimport torch\nfrom PIL import Image\nimport numpy as np\n\n# 事前学習済みViTのロード（ImageNetで学習済み2値分類用ヘッドに切り替えが必要な場合あり）\nmodel_name = \"google/vit-base-patch16-224-in21k\"\nmodel = ViTForImageClassification.from_pretrained(model_name, num_labels=2)\nprocessor = ViTImageProcessor.from_pretrained(model_name)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 画像のパスからnumpy配列への変換例\ndef preprocess_images(image_paths):\n    images = [Image.open(p).convert('RGB') for p in image_paths]\n    return processor(images=images, return_tensors=\"pt\")['pixel_values']\n\n# 例: val_listやtest_listを使って推論データ作成\npixel_values = preprocess_images(test_list[:8])  # 8枚だけ例","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.eval()\nwith torch.no_grad():\n    outputs = model(pixel_values)\n    logits = outputs.logits\n    preds = torch.argmax(logits, dim=1).numpy()\nprint(preds)  # 0, 1で出る（ラベルに合わせてマッピングを工夫）","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import glob\nimport os\nfrom sklearn.model_selection import train_test_split\n\ntrain_dir = '/kaggle/working/data/train'\ntest_dir = '/kaggle/working/data/test'\n\ntrain_list = glob.glob(os.path.join(train_dir, '*.jpg'))\ntest_list = glob.glob(os.path.join(test_dir, '*.jpg'))\n\ndef get_label_from_path(path):\n    filename = os.path.basename(path)\n    return 1 if filename.startswith('dog') else 0\n\nlabels = [get_label_from_path(p) for p in train_list]\ntrain_imgs, val_imgs, train_labels, val_labels = train_test_split(train_list, labels, test_size=0.2, random_state=42)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from PIL import Image\nfrom torch.utils.data import Dataset, DataLoader\nfrom transformers import ViTImageProcessor\n\nprocessor = ViTImageProcessor.from_pretrained('google/vit-base-patch16-224-in21k')\n\nclass CatsDogsDataset(Dataset):\n    def __init__(self, file_list, labels=None, processor=None):\n        self.file_list = file_list\n        self.labels = labels\n        self.processor = processor\n\n    def __len__(self):\n        return len(self.file_list)\n\n    def __getitem__(self, idx):\n        img_path = self.file_list[idx]\n        img = Image.open(img_path).convert(\"RGB\")\n        inputs = self.processor(images=img, return_tensors=\"pt\")\n        inputs = {k: v.squeeze(0) for k, v in inputs.items()}\n        if self.labels is not None:\n            label = self.labels[idx]\n            return inputs, label\n        else:\n            return inputs\n\nbatch_size = 8  # ViTは重いので小さめ\ntrain_ds = CatsDogsDataset(train_imgs, train_labels, processor)\nval_ds   = CatsDogsDataset(val_imgs,   val_labels,   processor)\ntest_ds  = CatsDogsDataset(test_list,  None,         processor)\n\ntrain_loader = DataLoader(train_ds, batch_size=batch_size, shuffle=True)\nval_loader   = DataLoader(val_ds,   batch_size=batch_size)\ntest_loader  = DataLoader(test_ds,  batch_size=1)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nfrom transformers import ViTForImageClassification\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel = ViTForImageClassification.from_pretrained(\n    \"google/vit-base-patch16-224-in21k\",\n    num_labels=2  # 犬猫\n)\nmodel.to(device)\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from PIL import Image\nfrom torch.utils.data import Dataset\nfrom transformers import ViTImageProcessor\n\nprocessor = ViTImageProcessor.from_pretrained('google/vit-base-patch16-224-in21k')\n\nclass CatsDogsDataset(Dataset):\n    def __init__(self, file_list, labels=None, processor=None):\n        self.file_list = file_list\n        self.labels = labels\n        self.processor = processor\n\n    def __len__(self):\n        return len(self.file_list)\n\n    def __getitem__(self, idx):\n        img_path = self.file_list[idx]\n        img = Image.open(img_path).convert(\"RGB\")\n        inputs = self.processor(images=img, return_tensors=\"pt\")\n        inputs = {k: v.squeeze(0) for k, v in inputs.items()}\n        if self.labels is not None:\n            label = self.labels[idx]\n            return inputs, label\n        else:\n            return inputs","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"batch_size = 8  # ViTは重いので小さめ\ntrain_ds = CatsDogsDataset(train_imgs, train_labels, processor)\nval_ds   = CatsDogsDataset(val_imgs,   val_labels,   processor)\ntest_ds  = CatsDogsDataset(test_list,  None,         processor)\n\nfrom torch.utils.data import DataLoader\ntrain_loader = DataLoader(train_ds, batch_size=batch_size, shuffle=True)\nval_loader   = DataLoader(val_ds,   batch_size=batch_size)\ntest_loader  = DataLoader(test_ds,  batch_size=1)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch.nn as nn\nfrom torch.optim import AdamW\nfrom tqdm import tqdm\n\nepochs = 8  # Kaggleなら3〜5くらいで様子見\noptimizer = AdamW(model.parameters(), lr=2e-5)\nloss_fn = nn.CrossEntropyLoss()\n\nfor epoch in range(epochs):\n    model.train()\n    total_loss = 0\n    for batch in tqdm(train_loader):\n        inputs, labels = batch\n        for k in inputs:\n            inputs[k] = inputs[k].to(device)\n        labels = torch.tensor(labels).to(device)\n        optimizer.zero_grad()\n        outputs = model(**inputs)\n        loss = loss_fn(outputs.logits, labels)\n        loss.backward()\n        optimizer.step()\n        total_loss += loss.item()\n    avg_loss = total_loss / len(train_loader)\n    print(f\"Epoch {epoch+1}/{epochs} Train Loss: {avg_loss:.4f}\")\n    \n    # Validation\n    model.eval()\n    correct, total = 0, 0\n    with torch.no_grad():\n        for batch in val_loader:\n            inputs, labels = batch\n            for k in inputs:\n                inputs[k] = inputs[k].to(device)\n            labels = torch.tensor(labels).to(device)\n            outputs = model(**inputs)\n            preds = outputs.logits.argmax(dim=1)\n            correct += (preds == labels).sum().item()\n            total += len(labels)\n    acc = correct / total\n    print(f\"Validation Accuracy: {acc:.4f}\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.eval()\nall_preds = []\nwith torch.no_grad():\n    for batch in tqdm(test_loader):\n        inputs = batch\n        for k in inputs:\n            inputs[k] = inputs[k].to(device)\n        outputs = model(**inputs)\n        pred = outputs.logits.argmax(dim=1).item()\n        all_preds.append(pred)\n\nids = [int(os.path.basename(x).split('.')[0]) for x in test_list]\nimport pandas as pd\nsubmission = pd.DataFrame({'id': ids, 'label': all_preds})\nsubmission = submission.sort_values('id')\nsubmission.to_csv('submission.csv', index=False)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# すでにtest_genがある前提\npred = model.predict(test_gen, steps=len(test_gen), verbose=1)\nlabels = (pred > 0.5).astype(int).flatten()\n\nids = [int(os.path.basename(x).split('.')[0]) for x in test_list]\nsubmission = pd.DataFrame({'id': ids, 'label': labels})\nsubmission = submission.sort_values('id')\nsubmission.to_csv('submission.csv', index=False)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\nimport numpy as np","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n\n# val_labels が \"dog\"/\"cat\" の場合は 0/1 に変換\nval_labels_int = [1 if label == 'dog' else 0 for label in val_labels]\n\n# 検証データで推論（val_genを使って予測）\nval_pred_probs = model.predict(val_gen)\nval_pred_labels = (val_pred_probs > 0.5).astype(int).flatten()\n\n# 指標を計算\nacc = accuracy_score(val_labels_int, val_pred_labels)\nprec = precision_score(val_labels_int, val_pred_labels)\nrec = recall_score(val_labels_int, val_pred_labels)\nf1 = f1_score(val_labels_int, val_pred_labels)\n\nprint('--- Validation Data ---')\nprint(f\"Accuracy : {acc:.4f}\")\nprint(f\"Precision: {prec:.4f}\")\nprint(f\"Recall   : {rec:.4f}\")\nprint(f\"F1 Score : {f1:.4f}\")","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}