{"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":5441,"databundleVersionId":38425,"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,"execution":{"iopub.status.busy":"2025-07-25T08:11:48.456848Z","iopub.execute_input":"2025-07-25T08:11:48.457190Z","iopub.status.idle":"2025-07-25T08:11:48.815812Z","shell.execute_reply.started":"2025-07-25T08:11:48.457164Z","shell.execute_reply":"2025-07-25T08:11:48.815097Z"}},"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-25T08:11:48.817401Z","iopub.execute_input":"2025-07-25T08:11:48.817768Z","iopub.status.idle":"2025-07-25T08:11:50.406273Z","shell.execute_reply.started":"2025-07-25T08:11:48.817749Z","shell.execute_reply":"2025-07-25T08:11:50.405497Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"img_size = 224\n\nbatch_size = 16\n\nepochs = 30","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T08:11:50.407113Z","iopub.execute_input":"2025-07-25T08:11:50.407430Z","iopub.status.idle":"2025-07-25T08:11:50.411107Z","shell.execute_reply.started":"2025-07-25T08:11:50.407410Z","shell.execute_reply":"2025-07-25T08:11:50.410406Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# データを初期化\n!rm -rf ../data","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T08:11:50.411747Z","iopub.execute_input":"2025-07-25T08:11:50.411916Z","iopub.status.idle":"2025-07-25T08:11:50.562609Z","shell.execute_reply.started":"2025-07-25T08:11:50.411903Z","shell.execute_reply":"2025-07-25T08:11:50.561761Z"}},"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-25T08:11:50.564868Z","iopub.execute_input":"2025-07-25T08:11:50.565130Z","iopub.status.idle":"2025-07-25T08:12:00.722234Z","shell.execute_reply.started":"2025-07-25T08:11:50.565105Z","shell.execute_reply":"2025-07-25T08:12:00.721443Z"}},"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-25T08:12:00.723112Z","iopub.execute_input":"2025-07-25T08:12:00.723321Z","iopub.status.idle":"2025-07-25T08:12:00.728739Z","shell.execute_reply.started":"2025-07-25T08:12:00.723304Z","shell.execute_reply":"2025-07-25T08:12:00.727956Z"}},"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])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T08:12:00.729493Z","iopub.execute_input":"2025-07-25T08:12:00.729792Z","iopub.status.idle":"2025-07-25T08:12:00.762638Z","shell.execute_reply.started":"2025-07-25T08:12:00.729774Z","shell.execute_reply":"2025-07-25T08:12:00.762039Z"}},"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)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T08:12:00.763381Z","iopub.execute_input":"2025-07-25T08:12:00.763650Z","iopub.status.idle":"2025-07-25T08:12:04.195405Z","shell.execute_reply.started":"2025-07-25T08:12:00.763626Z","shell.execute_reply":"2025-07-25T08:12:04.194794Z"}},"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)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T08:12:04.196213Z","iopub.execute_input":"2025-07-25T08:12:04.196757Z","iopub.status.idle":"2025-07-25T08:12:14.048420Z","shell.execute_reply.started":"2025-07-25T08:12:04.196729Z","shell.execute_reply":"2025-07-25T08:12:14.047631Z"}},"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})\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T08:12:14.049271Z","iopub.execute_input":"2025-07-25T08:12:14.049468Z","iopub.status.idle":"2025-07-25T08:12:14.074375Z","shell.execute_reply.started":"2025-07-25T08:12:14.049453Z","shell.execute_reply":"2025-07-25T08:12:14.073780Z"}},"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)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T08:12:14.075223Z","iopub.execute_input":"2025-07-25T08:12:14.075445Z","iopub.status.idle":"2025-07-25T08:12:14.268336Z","shell.execute_reply.started":"2025-07-25T08:12:14.075412Z","shell.execute_reply":"2025-07-25T08:12:14.267752Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install -q transformers timm\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T08:12:14.269082Z","iopub.execute_input":"2025-07-25T08:12:14.269304Z","iopub.status.idle":"2025-07-25T08:12:17.553818Z","shell.execute_reply.started":"2025-07-25T08:12:14.269286Z","shell.execute_reply":"2025-07-25T08:12:17.552751Z"}},"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)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T08:12:17.554986Z","iopub.execute_input":"2025-07-25T08:12:17.555245Z","iopub.status.idle":"2025-07-25T08:12:19.719735Z","shell.execute_reply.started":"2025-07-25T08:12:17.555220Z","shell.execute_reply":"2025-07-25T08:12:19.719060Z"}},"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)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T08:12:19.722689Z","iopub.execute_input":"2025-07-25T08:12:19.723221Z","iopub.status.idle":"2025-07-25T08:12:19.822505Z","shell.execute_reply.started":"2025-07-25T08:12:19.723191Z","shell.execute_reply":"2025-07-25T08:12:19.821960Z"}},"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)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T08:12:19.823156Z","iopub.execute_input":"2025-07-25T08:12:19.823365Z","iopub.status.idle":"2025-07-25T08:12:20.051543Z","shell.execute_reply.started":"2025-07-25T08:12:19.823350Z","shell.execute_reply":"2025-07-25T08:12:20.050996Z"}},"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,"execution":{"iopub.status.busy":"2025-07-25T08:12:20.052266Z","iopub.execute_input":"2025-07-25T08:12:20.052466Z","iopub.status.idle":"2025-07-25T08:12:20.856309Z","shell.execute_reply.started":"2025-07-25T08:12:20.052450Z","shell.execute_reply":"2025-07-25T08:12:20.855638Z"}},"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\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T08:12:20.857012Z","iopub.execute_input":"2025-07-25T08:12:20.857240Z","iopub.status.idle":"2025-07-25T08:12:21.080459Z","shell.execute_reply.started":"2025-07-25T08:12:20.857214Z","shell.execute_reply":"2025-07-25T08:12:21.079648Z"}},"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)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T08:12:21.081345Z","iopub.execute_input":"2025-07-25T08:12:21.082258Z","iopub.status.idle":"2025-07-25T08:12:21.087465Z","shell.execute_reply.started":"2025-07-25T08:12:21.082230Z","shell.execute_reply":"2025-07-25T08:12:21.086610Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch.nn as nn\nfrom torch.optim import AdamW\nfrom tqdm import tqdm\n\nepochs = 1  # 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}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-25T08:12:21.088315Z","iopub.execute_input":"2025-07-25T08:12:21.089128Z"}},"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)\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.eval()\nall_preds = []\nwith torch.no_grad():\n    for batch in 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\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)\n","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)\n","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\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\nimport torch\n\n# 推論とラベル収集\nmodel.eval()\nval_preds = []\nval_trues = []\n\nwith torch.no_grad():\n    for batch in val_loader:\n        inputs = batch['pixel_values'].to(model.device)\n        labels = batch['labels'].to(model.device)\n\n        outputs = model(inputs)\n        logits = outputs.logits\n        probs = torch.sigmoid(logits).squeeze().cpu().numpy()  # 2クラスの片方の確率\n\n        preds = (probs > 0.5).astype(int)  # 0 or 1\n        val_preds.extend(preds.tolist())\n        val_trues.extend(labels.cpu().numpy().tolist())\n\n# スコア計算\nacc = accuracy_score(val_trues, val_preds)\nprec = precision_score(val_trues, val_preds)\nrec = recall_score(val_trues, val_preds)\nf1 = f1_score(val_trues, val_preds)\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}\")\n","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}