{ "cells": [ { "cell_type": "markdown", "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/Radar/Radar_Solution.ipynb)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n", "def visualize_prediction(predictions):\n", " # Ensure the predictions are on the CPU and convert to NumPy\n", " predictions_np = predictions.cpu().numpy()\n", "\n", " # If predictions are in batch form, select the first image\n", " if predictions_np.ndim == 3:\n", " predictions_np = predictions_np[0]\n", "\n", " # Plot the image\n", " plt.figure(figsize=(10, 5))\n", " plt.imshow(predictions_np, cmap='viridis') # You can choose a different colormap\n", " plt.colorbar()\n", " plt.title('Predicted Image')\n", " plt.axis('off')\n", " plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "source_hidden": false } }, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd \n", "import torch\n", "import torch.nn as nn\n", "import torch.optim as optim\n", "import pickle\n", "import os\n", "import sys\n", "import torch.nn.functional as F\n", "sys.path.append('/bohr/train-4gug/v2')\n", "from dataloader import load_data\n", "import torch.nn.functional as F\n", "import random\n", "SEED = 243\n", "\n", "random.seed(SEED)\n", "np.random.seed(SEED)\n", "torch.manual_seed(SEED)\n", "torch.cuda.manual_seed(SEED)\n", "torch.cuda.manual_seed_all(SEED) # 多GPU情况\n", "torch.backends.cudnn.deterministic = True\n", "torch.backends.cudnn.benchmark = False\n", "\n", "# 然后在DataLoader中\n", "def seed_worker(worker_id):\n", " worker_seed = torch.initial_seed() % 2**32\n", " np.random.seed(worker_seed)\n", " random.seed(worker_seed)\n", "\n", "g = torch.Generator()\n", "g.manual_seed(SEED)\n", "def cal_accuracy(model, test_loader, bonus=1500, mode = 'test'):\n", " model.eval()\n", " total_score = 0\n", " total_theo = 0\n", " sn = 0 \n", " so = 0\n", " with torch.no_grad():\n", " for images, labels, _ in test_loader:\n", " images = images.cuda() if torch.cuda.is_available() else images\n", " labels = labels.cuda() if torch.cuda.is_available() else labels\n", "\n", " outputs = model(images, mode=mode)\n", " outputs = torch.argmax(outputs, dim=1)\n", " \n", " equal_mask = outputs == labels # correctly predicted masks\n", " neg_one_mask = labels == 0 # Mask of background categories\n", "\n", " # Calculate the score\n", " score_neg_one = (equal_mask & neg_one_mask).sum() * 1 # Background category score\n", " score_other = (equal_mask & ~neg_one_mask).sum() * bonus # Target category score\n", " score_theo = neg_one_mask.sum() * 1 + (~neg_one_mask).sum() * bonus # Full marks in theory\n", " sn += neg_one_mask.sum() * 1 - score_neg_one\n", " so += (~neg_one_mask).sum() * bonus - score_other\n", " total_score += score_neg_one + score_other\n", " total_theo += score_theo\n", " print(sn.item(), '0选成1扣分')\n", " print(so.item(), '1选成0扣分')\n", " score = total_score.item() / total_theo.item()\n", " return score\n", "import torch\n", "import numpy as np\n", "from scipy.ndimage import label\n", "def find_largest_connected_component(predictions):\n", " \n", " # Set the top 5 rows to zero\n", " predictions[:, :5, :] = 0\n", " \n", " # Set the bottom 5 rows to zero\n", " predictions[:, -5:, :] = 0\n", " \n", " # Set the first 5 columns to zero\n", " predictions[:, :, :15] = 0\n", " \n", " # Set the last 5 columns to zero\n", " predictions[:, :, -15:] = 0\n", " # Convert predictions to numpy array\n", " predictions_np = predictions.cpu().numpy()\n", " return predictions_np\n", " # Initialize an array to store the largest component\n", " # largest_component = np.zeros_like(predictions_np)\n", " \n", " # for i in range(predictions_np.shape[0]): # Iterate over batch\n", " # # Label connected components\n", " # labeled_array, num_features = label(predictions_np[i])\n", " \n", " # # Find the largest component\n", " # if num_features > 0:\n", " # largest_component_size = 0\n", " # largest_component_label = 0\n", " # for label_num in range(1, num_features + 1):\n", " # component_size = np.sum(labeled_array == label_num)\n", " # if component_size > largest_component_size:\n", " # largest_component_size = component_size\n", " # largest_component_label = label_num\n", " \n", " # # Set the largest component in the output\n", " # largest_component[i] = (labeled_array == largest_component_label)\n", " \n", " # return torch.tensor(largest_component, dtype=torch.float32).to(predictions.device)\n", "class MyModel(nn.Module):\n", " def __init__(self):\n", " super(MyModel, self).__init__()\n", " \n", " # Encoder\n", " self.enc_conv1 = self.conv_block(6, 16)\n", " self.enc_conv2 = self.conv_block(16, 32)\n", " self.pool = nn.MaxPool2d(2, 2)\n", " \n", " # Bottleneck\n", " self.bottleneck = self.conv_block(32, 64)\n", " \n", " # Decoder\n", " self.upsample1 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n", " self.dec_conv1 = self.conv_block(96, 32)\n", " self.upsample2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n", " self.dec_conv2 = self.conv_block(48, 16)\n", " \n", " # Output layer\n", " self.out_conv = nn.Conv2d(16, 2, kernel_size=1)\n", " \n", " def conv_block(self, in_channels, out_channels, dropout_rate=0.5):\n", " return nn.Sequential(\n", " nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),\n", " nn.BatchNorm2d(out_channels),\n", " nn.LeakyReLU(negative_slope=0.01, inplace=True), # Use LeakyReLU\n", " nn.Dropout(p=dropout_rate),\n", " nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),\n", " nn.BatchNorm2d(out_channels),\n", " nn.LeakyReLU(negative_slope=0.01, inplace=True) # Use LeakyReLU\n", " )\n", " def dilate_label1_regions(self, predictions):\n", " \"\"\"\n", " 非对称膨胀:横向延伸2像素,纵向延伸1像素\n", " Args:\n", " predictions: [B, 2, H, W] 模型输出\n", " Returns:\n", " 处理后的预测结果,label 1区域按要求膨胀\n", " \"\"\"\n", " # 获取当前预测的label 1 mask [B, H, W]\n", " pred_mask = torch.argmax(predictions, dim=1)\n", " \n", " # 创建非对称膨胀核(5x3大小)\n", " kernel = torch.zeros((1, 1, 3, 5), device=predictions.device) # [1,1,H,W]\n", " kernel[0, 0, 1, :] = 1 # 中心行全1(横向延伸2像素)\n", " \n", " # 对每个样本进行处理\n", " dilated_masks = []\n", " for i in range(pred_mask.shape[0]):\n", " mask = pred_mask[i].float().unsqueeze(0).unsqueeze(0) # [1,1,H,W]\n", " \n", " # 应用膨胀(padding=2横向,padding=1纵向)\n", " dilated = F.conv2d(mask, kernel, padding=(1, 2)) # (padH, padW)\n", " dilated = (dilated > 0).float()\n", " dilated_masks.append(dilated.squeeze())\n", " \n", " dilated_mask = torch.stack(dilated_masks) # [B,H,W]\n", " \n", " # 更新预测结果\n", " new_label1_mask = (dilated_mask == 1) & (pred_mask == 0)\n", " processed_output = predictions.clone()\n", " processed_output[:, 1][new_label1_mask] = 1.0 # 强制新区域预测为1\n", " processed_output[:, 0][new_label1_mask] = -1.0 # 抑制背景通道\n", " \n", " return processed_output\n", " def forward(self, x, mode = 'test'):\n", " padding = (5, 6, 3, 3) \n", " x = F.pad(x, padding, mode='constant', value=0).cuda()\n", " \n", " # Encoder\n", " x1 = self.enc_conv1(x)\n", " x2 = self.pool(x1)\n", " x2 = self.enc_conv2(x2)\n", " x3 = self.pool(x2)\n", " \n", " # Bottleneck\n", " x3 = self.bottleneck(x3)\n", " \n", " # Decoder\n", " x4 = self.upsample1(x3)\n", " x4 = torch.cat([x4, x2], dim=1) # Skip connection\n", " x4 = self.dec_conv1(x4)\n", " \n", " x5 = self.upsample2(x4)\n", " x5 = torch.cat([x5, x1], dim=1) # Skip connection\n", " x5 = self.dec_conv2(x5)\n", " # Output layer\n", " x_out = self.out_conv(x5)\n", " # Crop the output to the desired size (181, 50)\n", " x_out = x_out[:, :, :50, :181]\n", " if mode == 'test':\n", " predictions = torch.argmax(x_out, dim=1)\n", " largest_component = find_largest_connected_component(predictions)\n", " mask = largest_component == 0\n", " x_out[:, 1, :, :][mask] = float('-inf')\n", " #visualize_prediction(largest_component)\n", " #visualize_prediction(predictions)\n", " #visualize_prediction(torch.argmax(x_out, dim=1))\n", " kernel_weights = torch.zeros((2, 2, 5, 5), device=x_out.device) # [out_ch, in_ch, H, W]\n", " \n", " # Middle row is 1 for both input and output channels\n", " kernel_weights[:, :, 2, :] = 1 # Set middle row to 1 for all channels\n", " kernel_weights[:, :, 1:4, 2] = 1\n", " # Apply the convolution with padding=2 to maintain spatial dimensions\n", " x_out = self.process_label1_regions(x_out)\n", " x_out = self.dilate_label1_regions(x_out)\n", " return x_out\n", " if mode == 'test2':\n", " predictions = torch.argmax(x_out, dim=1)\n", " largest_component = find_largest_connected_component(predictions)\n", " mask = largest_component == 0\n", " x_out[:, 1, :, :][mask] = float('-inf')\n", " #visualize_prediction(largest_component)\n", " #visualize_prediction(predictions)\n", " #visualize_prediction(torch.argmax(x_out, dim=1))\n", " kernel_weights = torch.zeros((2, 2, 5, 5), device=x_out.device) # [out_ch, in_ch, H, W]\n", " \n", " # Middle row is 1 for both input and output channels\n", " kernel_weights[:, :, 2, :] = 1 # Set middle row to 1 for all channels\n", " kernel_weights[:, :, 1:4, 2] = 1\n", " # Apply the convolution with padding=2 to maintain spatial dimensions\n", " x_out = self.process_label1_regions(x_out)\n", " return x_out\n", " return x_out\n", " def process_label1_regions(self, predictions, threshold_ratio=0.5):\n", " \"\"\"\n", " Process label 1 regions by:\n", " 1. Finding connected components in label 1\n", " 2. For each component, calculate its bounding box width\n", " 3. Keep only components whose bounding box width is >= threshold_ratio * max_width\n", " \n", " Args:\n", " predictions: Tensor of shape [B, 2, H, W] (output from forward)\n", " threshold_ratio: Ratio to determine small regions to remove based on width\n", " \n", " Returns:\n", " Processed tensor with small/narrow label 1 regions removed\n", " \"\"\"\n", " # Get binary mask for label 1\n", " pred_mask = torch.argmax(predictions, dim=1) # [B, H, W]\n", " label1_mask = (pred_mask == 1).cpu().numpy() # Convert to numpy for scipy\n", " \n", " processed_output = predictions.clone()\n", " \n", " for i in range(predictions.shape[0]): # Process each sample in batch\n", " # Label connected components\n", " labeled_array, num_features = label(label1_mask[i])\n", " \n", " if num_features == 0:\n", " continue # No label 1 regions\n", " \n", " # Calculate bounding box widths for each component\n", " bbox_widths = []\n", " for label_num in range(1, num_features + 1):\n", " rows, cols = np.where(labeled_array == label_num)\n", " if len(rows) == 0:\n", " bbox_widths.append(0)\n", " continue\n", " min_row, max_row = np.min(rows), np.max(rows)\n", " min_col, max_col = np.min(cols), np.max(cols)\n", " width = max_col - min_col + 1 # +1 because both ends are inclusive\n", " bbox_widths.append(width)\n", " \n", " max_width = np.max(bbox_widths)\n", " threshold = max_width * threshold_ratio\n", " \n", " # Create mask for narrow regions to remove\n", " remove_mask = np.zeros_like(label1_mask[i], dtype=bool)\n", " \n", " for label_num in range(1, num_features + 1):\n", " if bbox_widths[label_num - 1] < threshold:\n", " remove_mask |= (labeled_array == label_num)\n", " \n", " # Set narrow regions to label 0 by setting label 1 channel to -inf\n", " if remove_mask.any():\n", " processed_output[i, 1][torch.from_numpy(remove_mask).to(predictions.device)] = float('-inf')\n", " \n", " return processed_output\n", "def train(model, train_loader, test_loader, optimizer, criterion, num_epochs=100):\n", " train_losses = []\n", " val_losses = []\n", " best_score = -float('inf') # Initialize with very low value\n", " \n", " for epoch in range(num_epochs):\n", " model.train()\n", " epoch_loss = 0.0\n", " batch_count = 0\n", " \n", " if epoch % 5 == 0:\n", " with torch.no_grad():\n", " for images, labels, _ in test_loader:\n", " images = images.cuda() if torch.cuda.is_available() else images\n", " labels = labels.cuda() if torch.cuda.is_available() else labels\n", " outputs = model(images)\n", " break\n", " \n", " for images, labels, _ in train_loader:\n", " images = images.cuda() if torch.cuda.is_available() else images\n", " labels = labels.cuda() if torch.cuda.is_available() else labels\n", " outputs = model(images, mode = 'train')\n", " outputs = outputs.reshape(outputs.size(0), outputs.size(1), -1) # [B, C, H*W]\n", " labels = labels.reshape(labels.size(0), -1) # [B, H*W]\n", " loss = criterion(outputs, labels)\n", " optimizer.zero_grad()\n", " loss.backward()\n", " optimizer.step()\n", " \n", " epoch_loss += loss.item()\n", " batch_count += 1\n", " \n", " avg_train_loss = epoch_loss / batch_count\n", " train_losses.append(avg_train_loss)\n", " \n", " model.eval()\n", " val_loss = 0.0\n", " val_batch_count = 0\n", " \n", " with torch.no_grad():\n", " for images, labels, _ in test_loader:\n", " images = images.cuda() if torch.cuda.is_available() else images\n", " labels = labels.cuda() if torch.cuda.is_available() else labels\n", " outputs = model(images)\n", " outputs = outputs.reshape(outputs.size(0), outputs.size(1), -1) # [B, C, H*W]\n", " labels = labels.reshape(labels.size(0), -1) # [B, H*W]\n", " loss = criterion(outputs, labels)\n", " val_loss += loss.item()\n", " val_batch_count += 1\n", " \n", " avg_val_loss = val_loss / val_batch_count\n", " val_losses.append(avg_val_loss)\n", " current_score = cal_accuracy(model, test_loader) / 3 * 2 + cal_accuracy(model, train_loader) / 3\n", " if current_score > best_score:\n", " best_score = current_score\n", " torch.save(model.state_dict(), 'submission_dic.pth')\n", " print(f\"New best model saved with score: {best_score:.4f}\")\n", " if (epoch+1) % 5 == 0:\n", " # Assuming this returns the metric to monitor\n", " print(f'Epoch [{epoch+1}/{num_epochs}], '\n", " f'Train Loss: {avg_train_loss:.4f}, '\n", " f'Val Loss: {avg_val_loss:.4f}')\n", " print(f'{current_score:.4f} test loader test', \n", " f'{cal_accuracy(model, train_loader):.4f} train loader test', \n", " f'{cal_accuracy(model, test_loader, mode = \"train\"):.4f} test loader train')\n", " \n", " \n", " return train_losses, val_losses\n", "\n", "data_path = '/bohr/train-4gug/v2/training_set'\n", "\n", "train_loader, test_loader = load_data(\n", " base_path=data_path,\n", " batch_size=8, \n", " test_size=0.01,\n", " num_workers=0\n", ")\n", "\n", "model = MyModel()\n", "if torch.cuda.is_available():\n", " model = model.cuda()\n", "weight_class = [1.,4000.]\n", "print(weight_class)\n", "weight_tensor = torch.tensor(weight_class, dtype=torch.float32).cuda()\n", "criterion = nn.CrossEntropyLoss(weight = weight_tensor)\n", "optimizer = optim.Adam(model.parameters(), lr=1e-3, weight_decay = 2e-4) \n", "\n", "train_losses, val_losses = train(\n", " model=model,\n", " train_loader=train_loader,\n", " test_loader=test_loader,\n", " optimizer=optimizer,\n", " criterion=criterion,\n", " num_epochs=40\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import torch\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import matplotlib\n", "from matplotlib import rcParams\n", "from matplotlib.colors import ListedColormap\n", "from matplotlib.patches import Patch\n", "import matplotlib.gridspec as gridspec\n", "\n", "def visualize_predictions(model, data_loader, num_samples, phase = 'test'):\n", " model.eval()\n", " images, labels, _ = next(iter(data_loader))\n", " images = images.cuda() if torch.cuda.is_available() else images\n", " labels = labels.cuda() if torch.cuda.is_available() else labels\n", "\n", " with torch.no_grad():\n", " outputs = model(images, phase)\n", " predicted_labels = torch.argmax(outputs, dim=1) # Get the argmax predictions\n", "\n", " true_labels = labels.cpu().numpy()\n", " predicted_labels = predicted_labels.cpu().numpy()\n", "\n", " fig, axes = plt.subplots(1, num_samples, figsize=(num_samples * 4, 4))\n", " for i in range(num_samples):\n", " combined = np.zeros_like(true_labels[i], dtype=np.uint8)\n", "\n", " # Set background to white\n", " combined[true_labels[i] == 0] = 0\n", "\n", " # Set true labels to blue\n", " combined[true_labels[i] != 0] = 1\n", "\n", " # Set predicted labels to red where they differ from true labels\n", " combined[(predicted_labels[i] != 0) & (predicted_labels[i] != true_labels[i])] = 2\n", "\n", " # Set overlapping areas to yellow\n", " combined[(predicted_labels[i] != 0) & (predicted_labels[i] == true_labels[i])] = 3\n", "\n", " # Create a custom colormap\n", " cmap = plt.cm.colors.ListedColormap(['white', 'blue', 'red', 'yellow'])\n", " bounds = [-0.5, 0.5, 1.5, 2.5, 3.5]\n", " norm = plt.cm.colors.BoundaryNorm(bounds, cmap.N)\n", "\n", " axes[i].imshow(combined, cmap=cmap, norm=norm)\n", " axes[i].set_title(f\"Sample {i+1}\")\n", " axes[i].axis('off')\n", "\n", " plt.tight_layout()\n", " plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from torch.utils.data import DataLoader, Dataset\n", "test_loader = DataLoader(\n", " test_loader.dataset,\n", " batch_size=64,\n", " shuffle=False\n", ")\n", "\n", "visualize_predictions(model, test_loader, num_samples=18)\n", "print(1)\n", "visualize_predictions(model, test_loader, num_samples=18, phase='test2')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Please write your model code (including the necessary imported modules, such as torch and torch.nn) below to generate a model structure file that can be easily loaded by the grading platform\n", "model_code = \"\"\" \n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "import numpy as np\n", "from scipy.ndimage import label\n", "def find_largest_connected_component(predictions):\n", " \n", " # Set the top 5 rows to zero\n", " predictions[:, :5, :] = 0\n", " \n", " # Set the bottom 5 rows to zero\n", " predictions[:, -5:, :] = 0\n", " \n", " # Set the first 5 columns to zero\n", " predictions[:, :, :15] = 0\n", " \n", " # Set the last 5 columns to zero\n", " predictions[:, :, -15:] = 0\n", " # Convert predictions to numpy array\n", " predictions_np = predictions.cpu().numpy()\n", " return predictions_np\n", " # Initialize an array to store the largest component\n", " # largest_component = np.zeros_like(predictions_np)\n", " \n", " # for i in range(predictions_np.shape[0]): # Iterate over batch\n", " # # Label connected components\n", " # labeled_array, num_features = label(predictions_np[i])\n", " \n", " # # Find the largest component\n", " # if num_features > 0:\n", " # largest_component_size = 0\n", " # largest_component_label = 0\n", " # for label_num in range(1, num_features + 1):\n", " # component_size = np.sum(labeled_array == label_num)\n", " # if component_size > largest_component_size:\n", " # largest_component_size = component_size\n", " # largest_component_label = label_num\n", " \n", " # # Set the largest component in the output\n", " # largest_component[i] = (labeled_array == largest_component_label)\n", " \n", " # return torch.tensor(largest_component, dtype=torch.float32).to(predictions.device)\n", "class MyModel(nn.Module):\n", " def __init__(self):\n", " super(MyModel, self).__init__()\n", " \n", " # Encoder\n", " self.enc_conv1 = self.conv_block(6, 16)\n", " self.enc_conv2 = self.conv_block(16, 32)\n", " self.pool = nn.MaxPool2d(2, 2)\n", " \n", " # Bottleneck\n", " self.bottleneck = self.conv_block(32, 64)\n", " \n", " # Decoder\n", " self.upsample1 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n", " self.dec_conv1 = self.conv_block(96, 32)\n", " self.upsample2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n", " self.dec_conv2 = self.conv_block(48, 16)\n", " \n", " # Output layer\n", " self.out_conv = nn.Conv2d(16, 2, kernel_size=1)\n", " \n", " def conv_block(self, in_channels, out_channels, dropout_rate=0.5):\n", " return nn.Sequential(\n", " nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),\n", " nn.BatchNorm2d(out_channels),\n", " nn.LeakyReLU(negative_slope=0.01, inplace=True), # Use LeakyReLU\n", " nn.Dropout(p=dropout_rate),\n", " nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),\n", " nn.BatchNorm2d(out_channels),\n", " nn.LeakyReLU(negative_slope=0.01, inplace=True) # Use LeakyReLU\n", " )\n", " def dilate_label1_regions(self, predictions):\n", " # 获取当前预测的label 1 mask [B, H, W]\n", " pred_mask = torch.argmax(predictions, dim=1)\n", " \n", " # 创建非对称膨胀核(5x3大小)\n", " kernel = torch.zeros((1, 1, 3, 5), device=predictions.device) # [1,1,H,W]\n", " kernel[0, 0, 1, :] = 1 # 中心行全1(横向延伸2像素)\n", " \n", " # 对每个样本进行处理\n", " dilated_masks = []\n", " for i in range(pred_mask.shape[0]):\n", " mask = pred_mask[i].float().unsqueeze(0).unsqueeze(0) # [1,1,H,W]\n", " \n", " # 应用膨胀(padding=2横向,padding=1纵向)\n", " dilated = F.conv2d(mask, kernel, padding=(1, 2)) # (padH, padW)\n", " dilated = (dilated > 0).float()\n", " dilated_masks.append(dilated.squeeze())\n", " \n", " dilated_mask = torch.stack(dilated_masks) # [B,H,W]\n", " \n", " # 更新预测结果\n", " new_label1_mask = (dilated_mask == 1) & (pred_mask == 0)\n", " processed_output = predictions.clone()\n", " processed_output[:, 1][new_label1_mask] = 1.0 # 强制新区域预测为1\n", " processed_output[:, 0][new_label1_mask] = -1.0 # 抑制背景通道\n", " \n", " return processed_output\n", " def forward(self, x, mode = 'test'):\n", " padding = (5, 6, 3, 3) \n", " x = F.pad(x, padding, mode='constant', value=0).cuda()\n", " \n", " # Encoder\n", " x1 = self.enc_conv1(x)\n", " x2 = self.pool(x1)\n", " x2 = self.enc_conv2(x2)\n", " x3 = self.pool(x2)\n", " \n", " # Bottleneck\n", " x3 = self.bottleneck(x3)\n", " \n", " # Decoder\n", " x4 = self.upsample1(x3)\n", " x4 = torch.cat([x4, x2], dim=1) # Skip connection\n", " x4 = self.dec_conv1(x4)\n", " \n", " x5 = self.upsample2(x4)\n", " x5 = torch.cat([x5, x1], dim=1) # Skip connection\n", " x5 = self.dec_conv2(x5)\n", " # Output layer\n", " x_out = self.out_conv(x5)\n", " # Crop the output to the desired size (181, 50)\n", " x_out = x_out[:, :, :50, :181]\n", " if mode == 'test':\n", " predictions = torch.argmax(x_out, dim=1)\n", " largest_component = find_largest_connected_component(predictions)\n", " mask = largest_component == 0\n", " x_out[:, 1, :, :][mask] = float('-inf')\n", " #visualize_prediction(largest_component)\n", " #visualize_prediction(predictions)\n", " #visualize_prediction(torch.argmax(x_out, dim=1))\n", " kernel_weights = torch.zeros((2, 2, 5, 5), device=x_out.device) # [out_ch, in_ch, H, W]\n", " \n", " # Middle row is 1 for both input and output channels\n", " kernel_weights[:, :, 2, :] = 1 # Set middle row to 1 for all channels\n", " kernel_weights[:, :, 1:4, 2] = 1\n", " # Apply the convolution with padding=2 to maintain spatial dimensions\n", " x_out = self.process_label1_regions(x_out)\n", " x_out = self.dilate_label1_regions(x_out)\n", " return x_out\n", " if mode == 'test2':\n", " predictions = torch.argmax(x_out, dim=1)\n", " largest_component = find_largest_connected_component(predictions)\n", " mask = largest_component == 0\n", " x_out[:, 1, :, :][mask] = float('-inf')\n", " #visualize_prediction(largest_component)\n", " #visualize_prediction(predictions)\n", " #visualize_prediction(torch.argmax(x_out, dim=1))\n", " kernel_weights = torch.zeros((2, 2, 5, 5), device=x_out.device) # [out_ch, in_ch, H, W]\n", " \n", " # Middle row is 1 for both input and output channels\n", " kernel_weights[:, :, 2, :] = 1 # Set middle row to 1 for all channels\n", " kernel_weights[:, :, 1:4, 2] = 1\n", " # Apply the convolution with padding=2 to maintain spatial dimensions\n", " x_out = self.process_label1_regions(x_out)\n", " return x_out\n", " return x_out\n", " def process_label1_regions(self, predictions, threshold_ratio=0.5):\n", " # Get binary mask for label 1\n", " pred_mask = torch.argmax(predictions, dim=1) # [B, H, W]\n", " label1_mask = (pred_mask == 1).cpu().numpy() # Convert to numpy for scipy\n", " \n", " processed_output = predictions.clone()\n", " \n", " for i in range(predictions.shape[0]): # Process each sample in batch\n", " # Label connected components\n", " labeled_array, num_features = label(label1_mask[i])\n", " \n", " if num_features == 0:\n", " continue # No label 1 regions\n", " \n", " # Calculate bounding box widths for each component\n", " bbox_widths = []\n", " for label_num in range(1, num_features + 1):\n", " rows, cols = np.where(labeled_array == label_num)\n", " if len(rows) == 0:\n", " bbox_widths.append(0)\n", " continue\n", " min_row, max_row = np.min(rows), np.max(rows)\n", " min_col, max_col = np.min(cols), np.max(cols)\n", " width = max_col - min_col + 1 # +1 because both ends are inclusive\n", " bbox_widths.append(width)\n", " \n", " max_width = np.max(bbox_widths)\n", " threshold = max_width * threshold_ratio\n", " \n", " # Create mask for narrow regions to remove\n", " remove_mask = np.zeros_like(label1_mask[i], dtype=bool)\n", " \n", " for label_num in range(1, num_features + 1):\n", " if bbox_widths[label_num - 1] < threshold:\n", " remove_mask |= (labeled_array == label_num)\n", " \n", " # Set narrow regions to label 0 by setting label 1 channel to -inf\n", " if remove_mask.any():\n", " processed_output[i, 1][torch.from_numpy(remove_mask).to(predictions.device)] = float('-inf')\n", " \n", " return processed_output\n", "\"\"\"\n", "# Write code to file\n", "with open('submission_model.py', 'w',encoding=\"utf-8\") as f:\n", " f.write(model_code)\n", "print(\"submission_model.py file has been generated.\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# This block mainly specifies the submission format of this question.\n", "import zipfile\n", "import os\n", "\n", "# Define the files to zip and the zip file name.\n", "files_to_zip = ['submission_model.py', 'submission_dic.pth']\n", "zip_filename = 'submission.zip'\n", "\n", "# Create a zip file\n", "with zipfile.ZipFile(zip_filename, 'w') as zipf:\n", " for file in files_to_zip:\n", " # Add the file to the zip fil\n", " zipf.write(file, os.path.basename(file))\n", "\n", "print(f'{zip_filename} Created successfully!')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Save the parameters of the model\n", "torch.save(model.state_dict(), 'submission_dic.pth')\n", "print(\"submission_dic.pth file has been saved.\")" ] } ], "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": 4 }