{"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":91249,"databundleVersionId":11294684,"sourceType":"competition"},{"sourceId":405051,"sourceType":"modelInstanceVersion","modelInstanceId":331022,"modelId":351919}],"dockerImageVersionId":31040,"isInternetEnabled":false,"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\n# import numpy as np # linear algebra\n# import 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\n# import os\n# for 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-05-23T15:24:22.220841Z","iopub.execute_input":"2025-05-23T15:24:22.221182Z","iopub.status.idle":"2025-05-23T15:24:22.227895Z","shell.execute_reply.started":"2025-05-23T15:24:22.221151Z","shell.execute_reply":"2025-05-23T15:24:22.226629Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nfrom PIL import Image, ImageFilter\nimport cv2\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n\nimport gc","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-23T15:24:22.229799Z","iopub.execute_input":"2025-05-23T15:24:22.230102Z","iopub.status.idle":"2025-05-23T15:24:39.765553Z","shell.execute_reply.started":"2025-05-23T15:24:22.230076Z","shell.execute_reply":"2025-05-23T15:24:39.764537Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 定数\nDATA_DIR = \"/kaggle/input/byu-locating-bacterial-flagellar-motors-2025\"\nMODEL_PATH = \"/kaggle/input/2d_cnn0521/pytorch/default/1/2dcnn_fold5_final_20250521_064150.pth\"\nOUTPUT_DIR = \"/kaggle/working\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-23T15:24:39.766615Z","iopub.execute_input":"2025-05-23T15:24:39.767026Z","iopub.status.idle":"2025-05-23T15:24:39.771556Z","shell.execute_reply.started":"2025-05-23T15:24:39.767001Z","shell.execute_reply":"2025-05-23T15:24:39.770824Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ✅ これが抜けているとエラーになる！\ndf = pd.read_csv(os.path.join(DATA_DIR, \"train_labels.csv\"))\n\nparam_dict = {}\nfor label in [\"Array shape (axis 0)\", \"Array shape (axis 1)\", \"Array shape (axis 2)\"]:\n    df[f\"{label}_dist\"] = df[label] * df[\"Voxel spacing\"]\n\nmax_dist = max(df[\"Array shape (axis 1)_dist\"].max(), df[\"Array shape (axis 2)_dist\"].max())\nvoxel_spacing_mean = df[\"Voxel spacing\"].mean()\nparam_dict[\"max_dist\"] = max_dist\nparam_dict[\"voxel_spacing_mean\"] = voxel_spacing_mean\n\nfinal_img_size = int(np.ceil(max_dist / voxel_spacing_mean))\nprint(f\"✅ final_img_size = {final_img_size}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-23T15:24:39.772684Z","iopub.execute_input":"2025-05-23T15:24:39.773517Z","iopub.status.idle":"2025-05-23T15:24:39.833561Z","shell.execute_reply.started":"2025-05-23T15:24:39.773487Z","shell.execute_reply":"2025-05-23T15:24:39.832547Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_dir = os.path.join(DATA_DIR, \"test\")\n# save_base = os.path.join(OUTPUT_DIR, \"processed\")\n# os.makedirs(save_base, exist_ok=True)\n\n# test_tomos = os.listdir(test_dir)\n# for tomo_id in tqdm(test_tomos):\n#     tomo_dir = os.path.join(test_dir, tomo_id)\n#     save_dir = os.path.join(save_base, tomo_id)\n#     os.makedirs(save_dir, exist_ok=True)\n\n#     voxel_spacing = voxel_spacing_mean  # testには個別のspacing情報がない前提\n#     target_size = int(np.ceil(max_dist / voxel_spacing))\n\n#     image_names = sorted([f for f in os.listdir(tomo_dir) if f.endswith(\".jpg\")])\n#     for img_name in image_names:\n#         img_path = os.path.join(tomo_dir, img_name)\n#         img = Image.open(img_path).convert(\"L\")\n#         img_np = np.array(img).astype(np.float32)\n\n#         # 標準化 → 平均0埋め → リサイズ\n#         mean, std = img_np.mean(), img_np.std()\n#         img_std = img_np - mean if std == 0 else (img_np - mean) / std\n#         h, w = img_std.shape\n\n#         if h > target_size or w > target_size:\n#             img_std = cv2.resize(img_std, (target_size, target_size), interpolation=cv2.INTER_AREA)\n#             h, w = img_std.shape\n\n#         padded = np.zeros((target_size, target_size), dtype=np.float32)\n#         padded[:h, :w] = img_std\n#         resized = cv2.resize(padded, (final_img_size, final_img_size), interpolation=cv2.INTER_LINEAR)\n\n#         # # 正規化＆保存\n#         # out_img = np.clip((resized - resized.min()) / (resized.ptp() + 1e-8) * 255, 0, 255).astype(np.uint8)\n#         # Image.fromarray(out_img).save(os.path.join(save_dir, img_name))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-23T15:24:39.834589Z","iopub.execute_input":"2025-05-23T15:24:39.834823Z","iopub.status.idle":"2025-05-23T15:24:39.840671Z","shell.execute_reply.started":"2025-05-23T15:24:39.834805Z","shell.execute_reply":"2025-05-23T15:24:39.839574Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class MultiTaskCNN(nn.Module):\n    def __init__(self, img_size=224):\n        super().__init__()\n        self.features = nn.Sequential(\n            nn.Conv2d(1, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.Dropout2d(0.2), nn.MaxPool2d(2),\n            nn.Conv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.Dropout2d(0.2), nn.MaxPool2d(2),\n            nn.Conv2d(64,128, 3, padding=1), nn.BatchNorm2d(128), nn.ReLU(), nn.Dropout2d(0.2), nn.MaxPool2d(2),\n            nn.Conv2d(128,256, 3, padding=1), nn.BatchNorm2d(256), nn.ReLU(), nn.Dropout2d(0.2), nn.MaxPool2d(2),\n            nn.Conv2d(256,256, 3, padding=1), nn.BatchNorm2d(256), nn.ReLU(), nn.Dropout2d(0.2), nn.MaxPool2d(2),\n        )\n        dummy = torch.zeros(1, 1, img_size, img_size)\n        with torch.no_grad():\n            f = self.features(dummy)\n        self.cls_head = nn.Sequential(nn.Flatten(), nn.Linear(f.numel(), 512), nn.ReLU(), nn.Dropout(0.4), nn.Linear(512, 2))\n        h_dim, v_dim = f.shape[1]*f.shape[2], f.shape[1]*f.shape[3]\n        self.reg_head = nn.Sequential(nn.Linear(h_dim + v_dim, 256), nn.ReLU(), nn.Dropout(0.4), nn.Linear(256, 2), nn.Sigmoid())\n\n    def forward(self, x):\n        f = self.features(x)\n        logits = self.cls_head(f)\n        h_pool = f.max(dim=3)[0]\n        v_pool = f.max(dim=2)[0]\n        h_flat, v_flat = h_pool.view(h_pool.size(0), -1), v_pool.view(v_pool.size(0), -1)\n        coords = self.reg_head(torch.cat([h_flat, v_flat], dim=1))\n        return logits, coords","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-23T15:24:39.841962Z","iopub.execute_input":"2025-05-23T15:24:39.842331Z","iopub.status.idle":"2025-05-23T15:24:39.872933Z","shell.execute_reply.started":"2025-05-23T15:24:39.842305Z","shell.execute_reply":"2025-05-23T15:24:39.871831Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"final_img_size = 224  # 学習済みモデルに合わせる\n\nmodel = MultiTaskCNN(img_size=final_img_size)\nmodel.load_state_dict(torch.load(MODEL_PATH, map_location=\"cuda\" if torch.cuda.is_available() else \"cpu\"))\nmodel.eval().to(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nprint(\"✅ モデルのロード完了\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-23T15:24:39.875855Z","iopub.execute_input":"2025-05-23T15:24:39.876190Z","iopub.status.idle":"2025-05-23T15:24:40.653854Z","shell.execute_reply.started":"2025-05-23T15:24:39.876155Z","shell.execute_reply":"2025-05-23T15:24:40.652961Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# --- 変換 ---\ntransform = transforms.Compose([\n    transforms.Resize((final_img_size, final_img_size), antialias=True),\n    transforms.ToTensor(),\n    transforms.Normalize([0.5], [0.5])\n])\n\n# --- データセット定義 ---\nclass TestDataset(Dataset):\n    def __init__(self, base_dir, transform, final_img_size, voxel_spacing_mean, max_dist):\n        self.samples = []\n        self.final_img_size = final_img_size\n        self.voxel_spacing_mean = voxel_spacing_mean\n        self.max_dist = max_dist\n        self.transform = transform\n\n        for tomo_id in os.listdir(base_dir):\n            dir_path = os.path.join(base_dir, tomo_id)\n            for fname in sorted(os.listdir(dir_path)):\n                if fname.endswith(\".jpg\"):\n                    z = int(fname.replace(\"slice_\", \"\").replace(\".jpg\", \"\"))\n                    self.samples.append((tomo_id, z, os.path.join(dir_path, fname)))\n\n    def __len__(self):\n        return len(self.samples)\n\n    def __getitem__(self, idx):\n        tomo_id, z, path = self.samples[idx]\n        try:\n            img = Image.open(path).convert(\"L\").resize((self.final_img_size, self.final_img_size))\n            img_np = np.array(img)\n            if self.transform:\n                img = self.transform(img)\n            return img, tomo_id, z\n\n        except Exception as e:\n            print(f\"[ERROR] Failed to load image: {path} ({e})\")\n            dummy = torch.zeros(1, self.final_img_size, self.final_img_size)\n            return dummy, tomo_id, z\n\n# --- データローダ作成 ---\ndataset = TestDataset(\n    base_dir=os.path.join(DATA_DIR, \"test\"),\n    transform=transform,\n    final_img_size=final_img_size,\n    voxel_spacing_mean=voxel_spacing_mean,\n    max_dist=max_dist\n)\nloader = DataLoader(dataset, batch_size=32, shuffle=False, num_workers=2)\n\n# --- 推論 ---\nresults = []\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel.to(device)\nmodel.eval()\n\nwith torch.no_grad():\n    for imgs, tomo_ids, zs in tqdm(loader):\n        imgs = imgs.to(device)\n        logits, coords = model(imgs)\n        probs = torch.softmax(logits, dim=1)[:, 1].cpu().numpy()\n        coords = coords.cpu().numpy()\n        for tomo_id, z, p, (x, y) in zip(tomo_ids, zs, probs, coords):\n            results.append({\n                \"tomo_id\": tomo_id,\n                \"slice_index\": int(z),\n                \"x\": float(x),\n                \"y\": float(y),\n                \"prob\": float(p)\n            })\n\n# --- 結果保存 ---\ndf_sub = pd.DataFrame(results)\n\ndf_best = df_sub.loc[df_sub.groupby(\"tomo_id\")[\"prob\"].idxmax()].copy()\n\ndf_best = df_best.rename(columns={\n    \"slice_index\": \"Motor axis 0\",\n    \"y\": \"Motor axis 1\",\n    \"x\": \"Motor axis 2\"\n})[[\"tomo_id\", \"Motor axis 0\", \"Motor axis 1\", \"Motor axis 2\"]]\n\ndf_best.to_csv(\"/kaggle/working/submission.csv\", index=False)\n\nprint(\"✅ formatted submission.csv saved!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-23T15:36:52.345464Z","iopub.execute_input":"2025-05-23T15:36:52.346159Z","iopub.status.idle":"2025-05-23T15:38:08.869582Z","shell.execute_reply.started":"2025-05-23T15:36:52.346127Z","shell.execute_reply":"2025-05-23T15:38:08.868346Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(\"submission.csv exists:\", os.path.exists(\"/kaggle/working/submission.csv\"))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-23T15:24:40.671913Z","iopub.status.idle":"2025-05-23T15:24:40.672218Z","shell.execute_reply.started":"2025-05-23T15:24:40.672080Z","shell.execute_reply":"2025-05-23T15:24:40.672094Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}