{ "cells": [ { "cell_type": "markdown", "id": "ccd48593-3b72-47c1-9813-2f58d3df5dae", "metadata": {}, "source": [ "\"IOAI\n", "\n", "[IOAI 2025 (Beijing, China), At-Home Round](https://ioai-official.org/china-2025)\n", "\n", "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/IOAI-official/IOAI-2025/blob/main/At-Home-Round/Weather/Weather_Solution.ipynb)" ] }, { "cell_type": "code", "execution_count": null, "id": "05befd6f", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import torch\n", "import math\n", "import matplotlib.pyplot as plt\n", "import pandas as pd\n", "import os\n", "from pathlib import Path\n", "import zipfile\n", "from tqdm import tqdm\n", "from datetime import datetime, timedelta\n", "import torch.nn as nn\n", "from torch.utils.data import Dataset, DataLoader\n", "import torch.nn.functional as F\n", "\n", "TEST_PATH = \"./train_v2/\"\n", "DATASET_PATH = TEST_PATH + \"dataset.npz\"\n", "METADATA_PATH = TEST_PATH + \"metadata.csv\"\n", "DEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", "BASELINE_MODEL = TEST_PATH + \"model_weights.pth\"" ] }, { "cell_type": "code", "execution_count": null, "id": "42461c94", "metadata": {}, "outputs": [], "source": [ "# Load from .npz file\n", "loaded = np.load(DATASET_PATH)\n", "X_train_128 = loaded['X_train_128']\n", "X_train_256 = loaded['X_train_256']\n", "Y_train_128 = loaded['Y_train_128']\n", "Y_train_256 = loaded['Y_train_256']\n", "X_test_128 = loaded['X_test_128']\n", "X_test_256 = loaded['X_test_256']\n", "Y_test_128 = loaded['Y_test_128']\n", "Y_test_256 = loaded['Y_test_256']" ] }, { "cell_type": "code", "execution_count": null, "id": "aa3efecf", "metadata": {}, "outputs": [], "source": [ "df = pd.read_csv(METADATA_PATH)\n", "df_train_128 = df[(df['size'] == 128) & (df['split'] == 'train')][['i', 'j', 'start_time']]\n", "df_train_256 = df[(df['size'] == 256) & (df['split'] == 'train')][['i', 'j', 'start_time']]\n", "df_test_128 = df[(df['size'] == 128) & (df['split'] == 'test')][['i', 'j', 'start_time']]\n", "df_test_256 = df[(df['size'] == 256) & (df['split'] == 'test')][['i', 'j', 'start_time']]" ] }, { "cell_type": "code", "execution_count": null, "id": "39135842", "metadata": {}, "outputs": [], "source": [ "def pixel_to_latlon(i, j):\n", " \"\"\"\n", " Converts pixel indices (row i, column j) to geographic latitude and longitude.\n", "\n", " Args:\n", " i (int): Row index (from 0 at the top to 3499 at the bottom).\n", " j (int): Column index (from 0 at the left to 6999 at the right).\n", "\n", " Returns:\n", " tuple: (latitude, longitude) as floats.\n", "\n", " This function is used to convert from image/pixel coordinates \n", " (such as a satellite image) to actual map coordinates.\n", " \"\"\"\n", " lat = 60.0 - i * 0.01 # Each row down is 0.01 degree further south\n", " lon = -130.0 + j * 0.01 # Each column right is 0.01 degree further east\n", " return lat, lon\n", "\n", "\n", "def solar_elevation(x, y, dt_utc):\n", " \"\"\"\n", " Calculates the sun's elevation angle above the horizon for a specific\n", " location (pixel) and UTC time.\n", "\n", " Args:\n", " x (int): Row index in the image (vertical position).\n", " y (int): Column index in the image (horizontal position).\n", " dt_utc (datetime or str): The date and time in UTC (string or datetime).\n", "\n", " Returns:\n", " float: Solar elevation angle in degrees.\n", "\n", " This function tells you \"how high is the sun in the sky\" \n", " for a given place and time.\n", " \"\"\"\n", " # If time is given as string, convert to datetime\n", " if isinstance(dt_utc, str):\n", " dt_utc = datetime.strptime(dt_utc, '%Y-%m-%d %H:%M:%S.%f')\n", "\n", " # Convert pixel indices to latitude and longitude\n", " lat, lon = pixel_to_latlon(x, y)\n", "\n", " # Estimate local time (in hours) by longitude (15 degrees = 1 hour)\n", " timezone_offset = lon / 15.0\n", " local_time = dt_utc.hour + dt_utc.minute / 60 + timezone_offset\n", "\n", " # Day of year (1-365/366)\n", " N = dt_utc.timetuple().tm_yday\n", "\n", " # Solar declination: angle between sun's rays and Earth's equator\n", " decl = 23.44 * math.sin(math.radians(360 / 365 * (N - 81)))\n", "\n", " # Hour angle: how far in time from solar noon\n", " H = 15 * (local_time - 12) # degrees\n", "\n", " # Convert everything to radians for math functions\n", " phi = math.radians(lat)\n", " delta = math.radians(decl)\n", " H = math.radians(H)\n", "\n", " # Calculate elevation using spherical trigonometry\n", " sin_h = math.sin(phi) * math.sin(delta) + math.cos(phi) * math.cos(delta) * math.cos(H)\n", " return sin_h\n", "\n", "\n", "def parse_goes_time(timestr):\n", "\n", " \"\"\"\n", " Converts a GOES satellite timestamp string into a Python datetime.\n", "\n", " Args:\n", " timestr (str): Timestamp string, e.g. 's20242891100205'.\n", "\n", " Returns:\n", " datetime: The parsed datetime.\n", "\n", " Format explanation:\n", " - 's20242891100205' means:\n", " year = 2024,\n", " day-of-year = 289,\n", " hour = 11,\n", " minute = 00,\n", " second = 20,\n", " tenths of a second = 5\n", " \"\"\"\n", " year = int(timestr[1:5])\n", " doy = int(timestr[5:8])\n", " hour = int(timestr[8:10])\n", " minute = int(timestr[10:12])\n", " second = int(timestr[12:14])\n", " micro = int(timestr[14]) * 100000 # tenths of a second\n", " return datetime(year, 1, 1) + timedelta(days=doy - 1, hours=hour, minutes=minute, seconds=second, microseconds=micro)\n", "\n", "\n", "def df_to_list_solar_elevation(df):\n", " hs = []\n", " for i, j, t in zip(df['i'], df['j'], df['start_time']):\n", " h = solar_elevation(i, j, t)\n", " dt = parse_goes_time(t)\n", " \n", " # 正弦编码月份 (1-12 -> 0-2π)\n", " month_sin = math.sin(2 * math.pi * (dt.month - 1) / 12)\n", " month_cos = math.cos(2 * math.pi * (dt.month - 1) / 12)\n", " \n", " # 正弦编码一天内的时间 (小时 -> 0-2π)\n", " hour_decimal = dt.hour + dt.minute / 60 + dt.second / 3600\n", " time_sin = math.sin(2 * math.pi * hour_decimal / 24)\n", " time_cos = math.cos(2 * math.pi * hour_decimal / 24)\n", " \n", " # 正弦编码经纬度 (假设i和j是经纬度坐标)\n", " # 假设i是纬度,j是经度,需要根据实际数据范围调整\n", " i, j = pixel_to_latlon(i, j)\n", " lat_sin = math.sin(2 * math.pi * i / 180) # 纬度范围 -90到90\n", " lat_cos = math.cos(2 * math.pi * i / 180)\n", " lon_sin = math.sin(2 * math.pi * j / 360) # 经度范围 -180到180\n", " lon_cos = math.cos(2 * math.pi * j / 360)\n", " \n", " # 组合所有编码特征\n", " encoded_features = [h, month_sin, month_cos, time_sin, time_cos, \n", " lat_sin, lat_cos, lon_sin, lon_cos]\n", " hs.append(encoded_features)\n", " return hs\n" ] }, { "cell_type": "code", "execution_count": null, "id": "9711908d", "metadata": {}, "outputs": [], "source": [ "angles_train_128 = df_to_list_solar_elevation(df_train_128)\n", "angles_train_256 = df_to_list_solar_elevation(df_train_256)\n", "angles_test_128 = df_to_list_solar_elevation(df_test_128)\n", "angles_test_256 = df_to_list_solar_elevation(df_test_256)" ] }, { "cell_type": "code", "execution_count": null, "id": "c98c8273", "metadata": {}, "outputs": [], "source": [ "class HybridSolarElevationDataset(Dataset):\n", " def __init__(self, X128, Y128, X256, Y256, angles128, angles256, transform=None):\n", " self.X128 = X128\n", " self.Y128 = Y128\n", " self.X256 = X256\n", " self.Y256 = Y256\n", " self.angles128 = angles128\n", " self.angles256 = angles256\n", " self.transform = transform\n", " self.len_128 = len(X128)\n", " self.len_256 = len(X256)\n", " \n", " def __len__(self):\n", " return self.len_128 + self.len_256\n", " \n", " def normalize_channels(self, x):\n", " \"\"\"\n", " 对X[N,C,H,W]的每一个channel进行normalization\n", " \"\"\"\n", " # 确保x是4D张量 [N,C,H,W]\n", " if x.dim() == 3:\n", " x = x.unsqueeze(0) # [C,H,W] -> [1,C,H,W]\n", " \n", " # 对每个channel分别进行normalization\n", " for c in range(x.shape[1]):\n", " channel_data = x[:, c, :, :]\n", " mean = channel_data.mean()\n", " std = channel_data.std()\n", " if std > 0:\n", " x[:, c, :, :] = (channel_data - mean) / std\n", " \n", " return x.squeeze(0) if x.shape[0] == 1 else x\n", " \n", " def __getitem__(self, idx):\n", " if idx < self.len_128:\n", " # 128x128 数据,上采样到256x256\n", " x = torch.tensor(self.X128[idx], dtype=torch.float32)\n", " y = torch.tensor(self.Y128[idx], dtype=torch.float32).unsqueeze(0)\n", " \n", " # 对输入数据进行channel-wise normalization\n", " x = self.normalize_channels(x)\n", " \n", " # 使用双线性插值将128x128上采样到256x256\n", " x = F.interpolate(x.unsqueeze(0), size=(256, 256), mode='nearest', align_corners=False).squeeze(0)\n", " y = F.interpolate(y.unsqueeze(0), size=(256, 256), mode='nearest', align_corners=False).squeeze(0)\n", " \n", " angle = torch.tensor(self.angles128[idx], dtype=torch.float32).unsqueeze(-1)\n", " size_flag = 0 # 标记为128尺寸(已上采样)\n", " else:\n", " # 256x256 数据\n", " x = torch.tensor(self.X256[idx - self.len_128], dtype=torch.float32)\n", " y = torch.tensor(self.Y256[idx - self.len_128], dtype=torch.float32).unsqueeze(0)\n", " \n", " # 对输入数据进行channel-wise normalization\n", " x = self.normalize_channels(x)\n", " \n", " angle = torch.tensor(self.angles256[idx - self.len_128], dtype=torch.float32).unsqueeze(-1)\n", " size_flag = 1 # 标记为256尺寸\n", " \n", " if self.transform:\n", " x = self.transform(x)\n", " y = self.transform(y)\n", " \n", " return x, y, angle, size_flag\n", "\n", "# 创建混合数据集实例\n", "train_dataset = HybridSolarElevationDataset(\n", " X_train_128, Y_train_128, X_train_256, Y_train_256, \n", " angles_train_128, angles_train_256\n", ")\n", "test_dataset = HybridSolarElevationDataset(\n", " X_test_128, Y_test_128, X_test_256, Y_test_256, \n", " angles_test_128, angles_test_256\n", ")\n", "\n", "# 创建DataLoader\n", "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "df8121a7", "metadata": {}, "outputs": [], "source": [ "def dice_loss(pred, target, eps=1e-6):\n", " \"\"\"\n", " Computes Dice Loss, which measures overlap between prediction and target.\n", "\n", " Args:\n", " pred (torch.Tensor): Raw logits from the model, shape [B, 1, H, W]\n", " target (torch.Tensor): Ground truth masks, shape [B, 1, H, W]\n", " eps (float): Small number to avoid division by zero.\n", "\n", " Returns:\n", " torch.Tensor: Dice loss (scalar)\n", " \"\"\"\n", " # Apply sigmoid to logits to get probabilities between 0 and 1\n", " pred = torch.sigmoid(pred)\n", " # Intersection and union for each image in the batch\n", " intersection = (pred * target).sum(dim=(1,2,3))\n", " union = pred.sum(dim=(1,2,3)) + target.sum(dim=(1,2,3))\n", " # Dice loss = 1 - Dice coefficient (higher is worse)\n", " return 1 - ((2 * intersection + eps) / (union + eps)).mean()\n", "\n", "def train_segmentation(model, train_loader, val_loader, epochs=10, lr=1e-3, device=\"cuda\"):\n", " \"\"\"\n", " Trains the segmentation model using both BCEWithLogitsLoss and Dice loss.\n", "\n", " Args:\n", " model (nn.Module): The segmentation model (U-Net).\n", " train_loader (DataLoader): DataLoader for training data.\n", " val_loader (DataLoader): DataLoader for validation data.\n", " epochs (int): Number of training epochs.\n", " lr (float): Learning rate.\n", " device (str): 'cuda' for GPU or 'cpu' for CPU.\n", "\n", " computes the combined loss, and updates the model weights. After each epoch, validation is performed.\n", " \"\"\"\n", " bce_loss = nn.BCEWithLogitsLoss() # Binary cross-entropy loss for logits\n", " model.to(device) # Move model to device (GPU/CPU)\n", " optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n", "\n", " for epoch in range(epochs):\n", " evaluate_on_test_custom(model, test_loader, device=\"cuda\")\n", " model.train() # Set model to training mode (affects layers like BatchNorm, Dropout)\n", " total_loss = 0.0\n", " print(f\"Epoch {epoch + 1}/{epochs}\")\n", "\n", " # Progress bar for training\n", " pbar = tqdm(train_loader, desc=\"Training\", leave=False)\n", "\n", " for batch_idx, (x, y, angle, size_flag) in enumerate(pbar):\n", " # 如果size_flag是0,使用nearest插值对x,y进行下采样缩小\n", " if size_flag == 0:\n", " B, C, H, W = x.shape\n", " new_H, new_W = H // 2, W // 2\n", " x = F.interpolate(x, size=(new_H, new_W), mode='nearest')\n", " y = F.interpolate(y, size=(new_H, new_W), mode='nearest')\n", " \n", " x = x.to(device)\n", " y = y.to(device)\n", " angle = angle.to(device)\n", " optimizer.zero_grad() # Clear previous gradients\n", "\n", " logits = model(x, angle) # [B, 1, H, W]\n", " logits_clamped = torch.clamp(logits, -20, 20) # Clamp values for stability\n", "\n", " # Loss = BCE (pixelwise) + Dice (region overlap)\n", " loss = bce_loss(logits_clamped, y) + dice_loss(logits_clamped, y)\n", "\n", " if torch.isnan(loss):\n", " print(f\"❌ Batch {batch_idx}: loss is NaN, skipping\")\n", " else:\n", " loss.backward() # Compute gradients\n", " optimizer.step() # Update weights\n", " total_loss += loss.item()\n", "\n", " print(f\" Avg epoch loss: {total_loss:.4f}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "69981e62", "metadata": {}, "outputs": [], "source": [ "class UNetSegmentation(nn.Module):\n", " \"\"\"\n", " U-Net neural network for image segmentation.\n", "\n", " Args:\n", " in_channels (int): Number of input channels (e.g., 16 for your patches)\n", "\n", " The U-Net consists of an encoder (downsampling), a bottleneck (middle), \n", " and a decoder (upsampling). It is widely used for segmenting images, \n", " where every pixel needs to be classified (e.g., rain/no rain).\n", " \"\"\"\n", " def __init__(self, in_channels):\n", " super().__init__()\n", " # Encoder path (\"contracting\" path): extracts features, reduces size\n", " self.encoder1 = self.conv_block(in_channels, 64)\n", " self.encoder2 = self.conv_block(64, 128)\n", " self.encoder3 = self.conv_block(128, 256)\n", " self.encoder4 = self.conv_block(256, 512)\n", "\n", " self.pool = nn.MaxPool2d(2) # Downsamples by factor of 2\n", "\n", " # Bottleneck (middle part)\n", " self.mid = self.conv_block(512, 1024)\n", "\n", " # Decoder path (\"expanding\" path): upscales, combines with encoder outputs\n", " self.up4 = nn.ConvTranspose2d(1024, 512, 2, stride=2) # Upsample\n", " self.dec4 = self.conv_block(1024, 512)\n", " self.up3 = nn.ConvTranspose2d(512, 256, 2, stride=2)\n", " self.dec3 = self.conv_block(512, 256)\n", " self.up2 = nn.ConvTranspose2d(256, 128, 2, stride=2)\n", " self.dec2 = self.conv_block(256, 128)\n", " self.up1 = nn.ConvTranspose2d(128, 64, 2, stride=2)\n", " self.dec1 = self.conv_block(128, 64)\n", "\n", " # Final layer: reduces to 1 output channel per pixel (for binary segmentation)\n", " self.final = nn.Conv2d(64, 1, kernel_size=1) # Output: logits per pixel\n", "\n", " def conv_block(self, in_ch, out_ch):\n", " \"\"\"\n", " Helper function to build a block of two convolutional layers, \n", " each followed by BatchNorm and ReLU activation.\n", "\n", " Args:\n", " in_ch (int): Number of input channels.\n", " out_ch (int): Number of output channels.\n", " \"\"\"\n", " return nn.Sequential(\n", " nn.Conv2d(in_ch, out_ch, 3, padding=1), # Keeps spatial size the same\n", " nn.BatchNorm2d(out_ch), # Helps training\n", " nn.ReLU(inplace=True), # Non-linearity\n", " nn.Conv2d(out_ch, out_ch, 3, padding=1), # Another conv layer\n", " nn.BatchNorm2d(out_ch),\n", " nn.ReLU(inplace=True)\n", " )\n", "\n", " def forward(self, x, a):\n", " \"\"\"\n", " Forward pass through the network.\n", "\n", " Args:\n", " x (torch.Tensor): Input tensor of shape [batch, channels, height, width]\n", "\n", " Returns:\n", " torch.Tensor: Output logits, shape [batch, 1, height, width]\n", " \"\"\"\n", " # Encoder: save outputs for skip connections\n", " e1 = self.encoder1(x)\n", " e2 = self.encoder2(self.pool(e1))\n", " e3 = self.encoder3(self.pool(e2))\n", " e4 = self.encoder4(self.pool(e3))\n", " m = self.mid(self.pool(e4))\n", " m = m * a.view(-1, 1, 1, 1)\n", "\n", " # Decoder: upsample, concatenate with encoder outputs (skip connections), then convolve\n", " d4 = self.dec4(torch.cat([self.up4(m), e4], dim=1))\n", " d3 = self.dec3(torch.cat([self.up3(d4), e3], dim=1))\n", " d2 = self.dec2(torch.cat([self.up2(d3), e2], dim=1))\n", " d1 = self.dec1(torch.cat([self.up1(d2), e1], dim=1))\n", "\n", " return self.final(d1) # Output shape: [batch, 1, H, W]\n" ] }, { "cell_type": "code", "execution_count": null, "id": "6ebe4996", "metadata": {}, "outputs": [], "source": [ "def evaluate_on_test_custom(model, test_loader, device=\"cuda\", threshold=0.5):\n", " \"\"\"\n", " 评估分割模型在测试数据上的性能并打印指标。\n", "\n", " Args:\n", " model (nn.Module): 训练好的分割模型\n", " test_loader (DataLoader): 测试数据的DataLoader\n", " device (str): 'cuda' 用于GPU或 'cpu' 用于CPU\n", " threshold (float): 将概率转换为二值掩码的阈值\n", "\n", " Prints:\n", " - IoU (Intersection over Union)\n", " - Dice coefficient\n", " - Precision\n", " - Recall\n", " - 图像级准确率 (如果图像中任何像素被检测为\"雨\")\n", " Returns:\n", " float: Dice系数和图像级准确率的平均值\n", " \"\"\"\n", " model.eval() # 设置为评估模式 (不更新dropout/batchnorm)\n", " model.to(device)\n", "\n", " total_iou = 0.0 # IoU累加器\n", " total_dice = 0.0 # Dice系数累加器\n", " total_prec = 0.0 # 精确率累加器\n", " total_recall = 0.0 # 召回率累加器\n", " total_batches = 0\n", "\n", " rain_y_true = [] # 真实图像级标签列表 (雨/无雨)\n", " rain_y_pred = [] # 预测图像级标签列表\n", "\n", " with torch.no_grad(): # 评估时不需要计算梯度\n", " pbar = tqdm(test_loader, desc=\"Test\", leave=False)\n", " for batch_idx, (x, y, angle, size_flag) in enumerate(pbar):\n", " if size_flag == 0:\n", " B, C, H, W = x.shape\n", " new_H, new_W = H // 2, W // 2\n", " x = F.interpolate(x, size=(new_H, new_W), mode='nearest')\n", " y = F.interpolate(y, size=(new_H, new_W), mode='nearest')\n", " x = x.to(device)\n", " y = y.to(device)\n", " angle = angle.to(device)\n", " \n", " # 按照训练代码的方式处理角度信息\n", " x = x + angle.view(-1, 1, 1, 1)\n", "\n", " logits = model(x) # [B, 1, H, W]\n", " probs = torch.sigmoid(logits) # 概率值在 [0, 1] 之间\n", " preds = (probs > threshold).float() # 二值预测\n", "\n", " # 计算IoU的交集和并集\n", " intersection = (preds * y).sum(dim=(1, 2, 3))\n", " union = ((preds + y) > 0).float().sum(dim=(1, 2, 3))\n", " iou = (intersection / (union + 1e-6)).mean().item()\n", "\n", " # 计算Dice系数\n", " dice = (2 * intersection / (preds.sum(dim=(1,2,3)) + y.sum(dim=(1,2,3)) + 1e-6)).mean().item()\n", "\n", " # 所有像素的精确率和召回率\n", " tp = (preds * y).sum().item() # 真正例\n", " fp = (preds * (1 - y)).sum().item() # 假正例\n", " fn = ((1 - preds) * y).sum().item() # 假负例\n", "\n", " precision = tp / (tp + fp + 1e-6)\n", " recall = tp / (tp + fn + 1e-6)\n", "\n", " # 添加到总计中以计算平均值\n", " total_iou += iou\n", " total_dice += dice\n", " total_prec += precision\n", " total_recall += recall\n", " total_batches += 1\n", "\n", " # 图像级雨/无雨: 如果任何像素是\"雨\"则为True\n", " rain_y_true += [(y > 0.5).any(dim=(1,2,3)).cpu()]\n", " rain_y_pred += [(preds > 0.5).any(dim=(1,2,3)).cpu()]\n", "\n", " if total_batches == 0:\n", " print(\"⚠️ 没有有效的批次\")\n", " return\n", "\n", " # 合并图像级标签以计算准确率\n", " rain_y_true = torch.cat(rain_y_true)\n", " rain_y_pred = torch.cat(rain_y_pred)\n", " acc = (rain_y_true == rain_y_pred).float().mean().item()\n", "\n", " dice_final = total_dice / total_batches\n", "\n", " print(f\"\\n📊 测试指标:\")\n", " print(f\" • IoU : {total_iou / total_batches:.4f}\")\n", " print(f\" • Dice : {dice_final:.4f}\")\n", " print(f\" • Prec : {total_prec / total_batches:.4f}\")\n", " print(f\" • Recall: {total_recall / total_batches:.4f}\")\n", " print(f\" • 图像级雨检测准确率: {acc:.4f}\")\n", " total_score = (dice_final + acc) / 2\n", " print(f\"最终得分: {total_score:.4f}\")\n", "\n", " # 返回排行榜的组合得分\n", " return dice_final, acc, total_score" ] }, { "cell_type": "code", "execution_count": null, "id": "f5493a63", "metadata": {}, "outputs": [], "source": [ "model = UNetSegmentation(in_channels=16)\n", "model.load_state_dict(torch.load(BASELINE_MODEL, map_location=torch.device(DEVICE)))" ] }, { "cell_type": "code", "execution_count": null, "id": "88a129a3", "metadata": {}, "outputs": [], "source": [ "train_segmentation(model, train_loader, test_loader, epochs=10, lr=1e-3, device=\"cuda\")" ] }, { "cell_type": "code", "execution_count": null, "id": "4a9d98c2", "metadata": {}, "outputs": [], "source": [ "evaluate_on_test_custom(model, test_loader, device=\"cuda\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.9" } }, "nbformat": 4, "nbformat_minor": 5 }