File size: 35,955 Bytes
2d5faf0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 | {
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"./figs/IOAI-Logo.png\" alt=\"IOAI Logo\" width=\"200\" height=\"auto\">\n",
"\n",
"[IOAI 2025 (Beijing, China), At-Home Round](https://ioai-official.org/china-2025)\n",
"\n",
"[](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
}
|