File size: 51,899 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 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 | {
"cells": [
{
"cell_type": "markdown",
"id": "b8ade52e-3ee7-4403-8a83-de02b812568b",
"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/Weather/Weather.ipynb)"
]
},
{
"cell_type": "markdown",
"id": "d4e463e6-45ed-4f71-a4cf-88ed6c1b0bbc",
"metadata": {},
"source": [
"# Satellite Weather Forecasting\n",
"\n",
"Please use Google Colab to verify your solution first. \n",
"We are very sorry about the issue of submitting a solution. The reason is that due to the fact that mainland China cannot directly access huggingface.co, there are too many network obstacles between the Testing Server and huggingface.co as well as hf-mirror.com. We are currently identifying the issue, which may take some time.\n",
"\n",
"The Google Colab link for this task is https://colab.research.google.com/drive/14tI_EARXubr6NNl7T_Ikhz0A5-Jhy2hZ?usp=sharing. The contestants can download the datasets and debug offline. However, it is strongly recommended that the contestants use Bohrium to be familiar with the contest platform. The on-site stage task will not provide the Google Colab links.\n",
"\n",
"You're a high school student interning at a regional climate lab, working alongside a small team of scientists focused on improving rainfall prediction using only satellite imagery. Traditionally, rain is measured by radar and ground sensors — but these systems are costly and often unavailable in remote regions.\n",
"\n",
"<img src=\"./figs/Weather Fig 1.png\" width=\"400\">\n",
"\n",
"While analyzing GOES-16 satellite images, you come up with an idea:\n",
"\n",
"> \"What if we could train a model to detect rain directly from satellite images — even without ground-based data? And what if we used additional context like sun angle, time of day, and location to improve its accuracy?\"\n",
"\n",
"The scientists are intrigued. You're given access to a large archive of satellite data and precipitation masks — and one challenge: prove it can work. If successful, your approach could help small farmers in underserved regions plan irrigation more effectively and reduce crop losses.\n",
"\n",
"Your mission: build a model that looks at the sky — and tells us whether it’s going to rain.\n",
"\n",
"\n",
"## Task\n",
"\n",
"Your task is to develop an AI model that takes satellite imagery from the GOES-16 satellite as the input; and predicts — for each pixel — whether rainfall is occurring at the corresponding location on Earth. This is a **semantic segmentation** task: your model should output a binary mask indicating \"rain\" or \"no rain\" at each pixel.\n",
"\n",
"You can train and evaluate your model using ground-truth precipitation data provided by the MRMS (Multi-Radar Multi-Sensor) dataset.\n",
"\n",
"A baseline segmentation model based on a pretrained U-Net is provided to help you get started.\n",
"\n",
"**You ARE allowed to:**\n",
"- Fine-tune or modify the baseline U-Net\n",
"- Use metadata (e.g., latitude, longitude, time, sun elevation)\n",
"- Modify the inference logic (e.g., thresholding, post-processing)\n",
"\n",
"**You are NOT allowed to:**\n",
"- Use any external datasets\n",
"- Use external pretrained models other than the provided baseline\n",
"- Look for the weather-forecasting articles on the internet. While this is a home task, it is intended to prepare you for the on-site contest.\n",
"\n",
"## Data\n",
"\n",
"The dataset includes satellite observations from the year 2024 and includes the following:\n",
"\n",
"- **GOES-16 ABI Multichannel Imagery** \n",
" 16 spectral channels (C01–C16), covering a range of wavelengths: \n",
" - C01–C03: visible light \n",
" - C04–C06: near-infrared \n",
" - C07–C16: infrared \n",
" Images are cropped into patches of either 128×128 or 256×256 pixels.\n",
"\n",
"- **Precipitation masks** from the MRMS system, providing binary labels (rain/no rain) per pixel.\n",
"\n",
"- **Metadata**, including: \n",
" - Latitude and longitude of the patch's top-left corner \n",
" - Start and end time in UTC (capturing all 16 channels takes ~10 minutes) \n",
" - A Python utility to compute **sun elevation angle** based on time and location\n",
"\n",
"\n",
"### Train-Validation Split\n",
"\n",
"- The **training set** is biased toward rainy scenes: only patches where at least 3% of pixels contain rain are included.\n",
" \n",
"- The **validation set** is designed to reflect real-world conditions: many patches contain little or no rainfall. Additionally, some samples may include transmission issues — for example, certain spectral channels might be deliberately missing or corrupted.\n",
"\n",
"\n",
"## Evaluation\n",
"\n",
"Your model will be evaluated on two metrics:\n",
"\n",
"- **Mean Dice Score**: \n",
" Measures how well your predicted mask matches the ground truth, pixel-by-pixel. The Formula is 2 × |intersection| / (|prediction| + |ground_truth|).\n",
"\n",
"\n",
"- **Image-level Rain Accuracy**: \n",
" Measures whether your model correctly classifies if any rain is present in the image. This is because sometimes you do not need to segment every drop of rain — it is enough to simply know whether it will rain at all. Even a single accurate prediction can help protect an entire field of crops.\n",
"\n",
"- **Final Score**:\n",
" Final Score = (Mean Dice Score + Image-level Rain Accuracy) / 2.\n",
"\n",
"## Copyright\n",
"\n",
"All data used in this challenge is publicly available:\n",
"\n",
"- **GOES-16 ABI** satellite data from NOAA and NESDIS \n",
"- **MRMS** precipitation data from NOAA's National Severe Storms Laboratory (NSSL)\n",
"\n",
"\n",
"## Submission\n",
"\n",
"Your notebook needs to generate a `submission.zip` file containing your predictions on the public testing set `pred_a.npz` and your predictions on the private testing set `pred_b.npz`. Each `.npz` file should contain `Y_pred_128` (shape $51 \\times 128 \\times 128$) and `Y_pred_256` (shape $183 \\times 256 \\times 256$), your boolean predictions for each testing set.\n",
"\n",
"```python\n",
"# first generate pred_a.npz\n",
"\n",
"model.eval()\n",
"model.to(DEVICE)\n",
"\n",
"Y_pred_128 = []\n",
"with torch.no_grad():\n",
" for i in tqdm(range(len(X_test[128]))):\n",
" x = X_test[128][i]\n",
" metadata = df[(df['size'] == 128) & (df['split'] == 'test') & (df['ind'] == i)] # sample metadata usage\n",
" logits = model(x.unsqueeze(0).to(torch.float32).to(DEVICE))\n",
" probs = torch.sigmoid(logits)\n",
" preds = (probs > 0.5).float().squeeze(0)\n",
" Y_pred_128.append(preds.cpu().detach().numpy())\n",
"Y_pred_128 = np.concatenate(Y_pred_128, axis=0)\n",
"\n",
"print(Y_pred_128.shape)\n",
"\n",
"Y_pred_256 = []\n",
"with torch.no_grad():\n",
" for i in tqdm(range(len(X_test[256]))):\n",
" x = X_test[256][i]\n",
" metadata = df[(df['size'] == 256) & (df['split'] == 'test') & (df['ind'] == i)]\n",
" logits = model(x.unsqueeze(0).to(torch.float32).to(DEVICE))\n",
" probs = torch.sigmoid(logits)\n",
" preds = (probs > 0.5).float().squeeze(0)\n",
" Y_pred_256.append(preds.cpu().detach().numpy())\n",
"Y_pred_256 = np.concatenate(Y_pred_256, axis=0)\n",
"\n",
"print(Y_pred_256.shape)\n",
"\n",
"# You must name your prediction arrays `Y_pred_128` and `Y_pred_256`, and name the file `pred_a.npz` for the public leaderboard\n",
"np.savez('pred_a.npz', Y_pred_128=Y_pred_128, Y_pred_256=Y_pred_256)\n",
"```\n",
"\n",
"```\n",
"100%|██████████| 51/51 [00:00<00:00, 53.08it/s]\n",
"(51, 128, 128)\n",
"100%|██████████| 183/183 [00:08<00:00, 21.31it/s]\n",
"(183, 256, 256)\n",
"```\n",
"\n",
"```python\n",
"# Your notebook will gain access to the test dataset via the DATA_PATH environment variable after submission.\n",
"TEST_PATH = os.environ.get('DATA_PATH', \"test\")\n",
"\n",
"test = np.load(Path(TEST_PATH) / \"X_test.npz\") # Read test data from X_test.npz under the provided path\n",
"\n",
"X_test = {\n",
" 128: torch.from_numpy(test['X_test_128']),\n",
" 256: torch.from_numpy(test['X_test_256']),\n",
"} # only X_test will be provided\n",
"\n",
"df_test = pd.read_csv(Path(TEST_PATH) / \"metadata_test.csv\") # Read metadata from metadata_test.csv under the provided path\n",
"```\n",
"\n",
"```python\n",
"Y_pred_128 = []\n",
"with torch.no_grad():\n",
" for i in tqdm(range(len(X_test[128]))):\n",
" x = X_test[128][i]\n",
" metadata = df_test[(df_test['size'] == 128) & (df_test['ind'] == i)] # sample metadata usage\n",
" logits = model(x.unsqueeze(0).to(torch.float32).to(DEVICE))\n",
" probs = torch.sigmoid(logits)\n",
" preds = (probs > 0.5).float().squeeze(0)\n",
" Y_pred_128.append(preds.cpu().detach().numpy())\n",
"Y_pred_128 = np.concatenate(Y_pred_128, axis=0)\n",
"\n",
"print(Y_pred_128.shape)\n",
"\n",
"Y_pred_256 = []\n",
"with torch.no_grad():\n",
" for i in tqdm(range(len(X_test[256]))):\n",
" x = X_test[256][i]\n",
" metadata = df_test[(df_test['size'] == 256) & (df_test['ind'] == i)]\n",
" logits = model(x.unsqueeze(0).to(torch.float32).to(DEVICE))\n",
" probs = torch.sigmoid(logits)\n",
" preds = (probs > 0.5).float().squeeze(0)\n",
" Y_pred_256.append(preds.cpu().detach().numpy())\n",
"Y_pred_256 = np.concatenate(Y_pred_256, axis=0)\n",
"\n",
"print(Y_pred_256.shape)\n",
"\n",
"# You must name your prediction arrays `Y_pred_128` and `Y_pred_256`, and name the file `pred_b.npz` for private leaderboard\n",
"np.savez('pred_b.npz', Y_pred_128=Y_pred_128, Y_pred_256=Y_pred_256)\n",
"```\n",
"```\n",
"100%|██████████| 51/51 [00:00<00:00, 58.14it/s]\n",
"(51, 128, 128)\n",
"100%|██████████| 183/183 [00:08<00:00, 22.31it/s]\n",
"(183, 256, 256)\n",
"```\n",
"\n",
"```python\n",
"# zip `pred_a.npz` and `pred_b.npz` into `submission.zip`\n",
"with zipfile.ZipFile('submission.zip', 'w') as zipf:\n",
" zipf.write('pred_a.npz')\n",
" zipf.write('pred_b.npz')\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "e015eaf5-723a-4d1c-8d98-e711b3d058fb",
"metadata": {},
"source": [
"## Imports"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "da8f71f7-8fad-4e8c-81ad-6b9c6803c400",
"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",
"\n",
"TEST_PATH = \"/bohr/train-ma50/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": "markdown",
"id": "18ed6aa4",
"metadata": {},
"source": [
"## Data Utility Functions"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0ed83942",
"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",
" h = math.degrees(math.asin(sin_h))\n",
" return h\n",
"\n",
"\n",
"def parse_goes_time(timestr):\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 prepare_dataset(data, threshold=0.1):\n",
" \"\"\"\n",
" Prepares input (X) and output (Y) tensors from raw patch data,\n",
" applying normalization, thresholding, and cleaning.\n",
"\n",
" Args:\n",
" data (dict): Dictionary mapping patch size to lists of numpy arrays,\n",
" each array is [17, D, D] (16 channels + 1 mask channel).\n",
" threshold (float): Threshold for converting last channel to binary mask.\n",
"\n",
" Returns:\n",
" tuple: (X_dict, Y_dict, norm_stats)\n",
" - X_dict: Dict of input tensors, shape [N, 16, D, D] for each size.\n",
" - Y_dict: Dict of output masks, shape [N, D, D] for each size.\n",
" - norm_stats: Dict with 'mean' and 'std' for normalization (per channel).\n",
"\n",
" This function does two passes over the data:\n",
" 1. Computes mean and std for each input channel (ignoring NaNs).\n",
" 2. Normalizes the data and packs it into torch tensors.\n",
" \"\"\"\n",
"\n",
" num_channels = 16 # First 16 channels are features, last one is target mask\n",
"\n",
" # === Pass 1: Compute statistics for normalization ===\n",
" sum_channels = torch.zeros(num_channels, dtype=torch.float64) # Total sum per channel\n",
" sum_sq_channels = torch.zeros(num_channels, dtype=torch.float64) # Total squared sum per channel\n",
" count_channels = torch.zeros(num_channels, dtype=torch.int64) # Number of valid (non-NaN) values per channel\n",
"\n",
" for patches in data.values():\n",
" for arr in patches:\n",
" arr = torch.tensor(arr.squeeze(0), dtype=torch.float32) # arr: [17, D, D]\n",
" x = arr[:16] # [16, D, D] - input features\n",
" x = torch.nan_to_num(x, nan=0.0, posinf=0.0, neginf=0.0) # Replace NaN/inf with 0\n",
"\n",
" valid = ~torch.isnan(x) # Mask of valid values\n",
" sum_channels += torch.where(valid, x, torch.tensor(0.0)).sum(dim=(1, 2))\n",
" sum_sq_channels += torch.where(valid, x ** 2, torch.tensor(0.0)).sum(dim=(1, 2))\n",
" count_channels += valid.sum(dim=(1, 2))\n",
"\n",
" # Compute mean and std per channel\n",
" means = sum_channels / count_channels\n",
" variances = (sum_sq_channels / count_channels) - means ** 2\n",
" stds = torch.sqrt(torch.clamp(variances, min=1e-6)) # avoid sqrt of negative\n",
"\n",
" # === Make sure no zeros, NaNs or infs in std/mean ===\n",
" stds[stds == 0] = 1.0\n",
" stds[torch.isnan(stds)] = 1.0\n",
" stds[torch.isinf(stds)] = 1.0\n",
"\n",
" means[torch.isnan(means)] = 0.0\n",
" means[torch.isinf(means)] = 0.0\n",
"\n",
" norm_stats = {\n",
" \"mean\": means.to(torch.float32),\n",
" \"std\": stds.to(torch.float32)\n",
" }\n",
"\n",
" # === Pass 2: Normalize and pack tensors for PyTorch training ===\n",
" X_dict = {}\n",
" Y_dict = {}\n",
"\n",
" for size, patches in data.items():\n",
" n = len(patches) # Number of patches for this size\n",
" D = size # Patch size (width and height)\n",
"\n",
" # Allocate memory for all normalized patches and masks\n",
" X_tensor = torch.empty((n, num_channels, D, D), dtype=torch.float16)\n",
" Y_tensor = torch.empty((n, D, D), dtype=torch.uint8)\n",
"\n",
" for i, arr in enumerate(patches):\n",
" arr = torch.tensor(arr.squeeze(0), dtype=torch.float32) # [17, D, D]\n",
" x = arr[:16] # First 16 channels: features\n",
" y = (arr[16] > threshold).to(torch.uint8) # Last channel: mask, binarized\n",
"\n",
" x = torch.nan_to_num(x, nan=0.0, posinf=0.0, neginf=0.0) # Clean\n",
"\n",
" # Normalize per channel: (value - mean) / std\n",
" x_norm = ((x - means[:, None, None]) / stds[:, None, None]).to(torch.float16)\n",
"\n",
" X_tensor[i] = x_norm # Save normalized input\n",
" Y_tensor[i] = y # Save output mask\n",
"\n",
" X_dict[size] = X_tensor\n",
" Y_dict[size] = Y_tensor\n",
"\n",
" return X_dict, Y_dict, norm_stats"
]
},
{
"cell_type": "markdown",
"id": "f1dd38ab",
"metadata": {},
"source": [
"## Model Utility Functions"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1453ceae",
"metadata": {},
"outputs": [],
"source": [
"class PatchDataset(Dataset):\n",
" \"\"\"\n",
" Custom PyTorch dataset for image patches and their segmentation masks.\n",
"\n",
" Args:\n",
" X_tensor (torch.Tensor): Input tensor of image patches, shape [N, 16, D, D]\n",
" Y_tensor (torch.Tensor): Target segmentation masks, shape [N, D, D]\n",
"\n",
" This class is used to feed data into the neural network during training and testing.\n",
" \"\"\"\n",
" def __init__(self, X_tensor, Y_tensor):\n",
" self.X = X_tensor # Input images: shape [num_samples, 16, height, width], float16\n",
" self.Y = Y_tensor # Target masks: shape [num_samples, height, width], uint8 (0 or 1)\n",
"\n",
" def __len__(self):\n",
" # Returns number of samples in dataset\n",
" return self.X.shape[0]\n",
"\n",
" def __getitem__(self, idx):\n",
" \"\"\"\n",
" Fetch one sample and its mask by index.\n",
" Converts X to float32 and adds a channel to Y (needed for loss).\n",
" \"\"\"\n",
" x = self.X[idx].to(torch.float32) # Convert to float32 (needed for the model)\n",
" y = self.Y[idx].unsqueeze(0).to(torch.float32) # Add a channel, shape [1, D, D]\n",
" return x, y\n",
"\n",
"\n",
"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):\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",
"\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",
"\n",
"\n",
"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",
"\n",
"def train_segmentation(model, train_loaders, val_loaders=None, 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_loaders (dict): Dictionary of DataLoader(s) for different patch sizes.\n",
" val_loaders (dict or None): Not used in this code, can be used for validation.\n",
" epochs (int): Number of training epochs.\n",
" lr (float): Learning rate.\n",
" device (str): 'cuda' for GPU or 'cpu' for CPU.\n",
"\n",
" During training, for each patch size, the function loops through the data in batches,\n",
" computes the combined loss, and updates the model weights.\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.SGD(model.parameters(), lr=lr) # Stochastic Gradient Descent\n",
"\n",
" for epoch in range(epochs):\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",
" for size in train_loaders:\n",
" loader = train_loaders[size]\n",
" # Progress bar for this patch size\n",
" pbar = tqdm(loader, desc=f\"Training {size}x{size}\", leave=False)\n",
"\n",
" for batch_idx, (x, y) in enumerate(pbar):\n",
" x = x.to(device)\n",
" y = y.to(device)\n",
"\n",
" optimizer.zero_grad() # Clear previous gradients\n",
"\n",
" logits = model(x) # [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}\")\n",
"\n",
"\n",
"def build_dataloaders(X_dict, Y_dict, shuffle=True, regime='train'):\n",
" \"\"\"\n",
" Builds PyTorch DataLoader objects for different patch sizes.\n",
"\n",
" Args:\n",
" X_dict (dict): Dict of input tensors for each patch size.\n",
" Y_dict (dict): Dict of label tensors for each patch size.\n",
" shuffle (bool): Whether to shuffle the data (good for training).\n",
" regime (str): Can be 'train' or 'test', not used in code.\n",
"\n",
" Returns:\n",
" dict: Dictionary of DataLoader objects for each patch size.\n",
" \"\"\"\n",
" batch_sizes = {128: 32, 256: 16} # Set batch size for each patch size\n",
" train_loaders = {}\n",
" for size in X_dict:\n",
" ds = PatchDataset(X_dict[size], Y_dict[size]) # Make dataset for this size\n",
" train_loaders[size] = DataLoader(ds, batch_size=batch_sizes[size], shuffle=shuffle)\n",
" return train_loaders\n",
"\n",
"\n",
"def evaluate_on_test(model, test_loaders, device=\"cuda\", threshold=0.5):\n",
" \"\"\"\n",
" Evaluates the segmentation model on test data and prints metrics.\n",
"\n",
" Args:\n",
" model (nn.Module): The trained segmentation model.\n",
" test_loaders (dict): Dictionary of DataLoader(s) for each patch size.\n",
" device (str): 'cuda' for GPU or 'cpu' for CPU.\n",
" threshold (float): Threshold for converting probabilities to binary masks.\n",
"\n",
" Prints:\n",
" - IoU (Intersection over Union)\n",
" - Dice coefficient\n",
" - Precision\n",
" - Recall\n",
" - Image-level accuracy (if any pixel is detected as \"rain\" in image)\n",
" Returns:\n",
" float: Average of Dice coefficient and image-level accuracy.\n",
" \"\"\"\n",
" model.eval() # Set model to evaluation mode (no dropout/batchnorm update)\n",
" model.to(device)\n",
"\n",
" total_iou = 0.0 # Intersection over Union accumulator\n",
" total_dice = 0.0 # Dice coefficient accumulator\n",
" total_prec = 0.0 # Precision accumulator\n",
" total_recall = 0.0 # Recall accumulator\n",
" total_batches = 0\n",
"\n",
" rain_y_true = [] # List for true image-level labels (rain/no rain)\n",
" rain_y_pred = [] # List for predicted image-level labels\n",
"\n",
" with torch.no_grad(): # No need to compute gradients during evaluation\n",
" for size, loader in test_loaders.items():\n",
" pbar = tqdm(loader, desc=f\"Test {size}x{size}\", leave=False)\n",
" for x, y in pbar:\n",
" x = x.to(device)\n",
" y = y.to(device)\n",
"\n",
" logits = model(x) # [B, 1, H, W]\n",
" probs = torch.sigmoid(logits) # Probabilities in [0, 1]\n",
" preds = (probs > threshold).float() # Binary predictions\n",
"\n",
" # Compute intersection and union for 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",
" # Compute Dice coefficient\n",
" dice = (2 * intersection / (preds.sum(dim=(1,2,3)) + y.sum(dim=(1,2,3)) + 1e-6)).mean().item()\n",
"\n",
" # Precision and recall for all pixels\n",
" tp = (preds * y).sum().item() # True positives\n",
" fp = (preds * (1 - y)).sum().item() # False positives\n",
" fn = ((1 - preds) * y).sum().item() # False negatives\n",
"\n",
" precision = tp / (tp + fp + 1e-6)\n",
" recall = tp / (tp + fn + 1e-6)\n",
"\n",
" # Add to totals for averaging\n",
" total_iou += iou\n",
" total_dice += dice\n",
" total_prec += precision\n",
" total_recall += recall\n",
" total_batches += 1\n",
"\n",
" # For image-level rain/no-rain: True if any pixel is \"rain\"\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(\"⚠️ No valid batches\")\n",
" return\n",
"\n",
" # Combine image-level labels for accuracy calculation\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📊 Test metrics across all sizes:\")\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\" • Image-level Rain Acc: {acc:.4f}\")\n",
" total_score = (dice_final + acc) / 2\n",
" print(f\"Final score: {total_score:.4f}\")\n",
"\n",
" # Return a combined score for leaderboard\n",
" return dice_final, acc, total_score"
]
},
{
"cell_type": "markdown",
"id": "6b016b87-9f8d-4c94-9d44-1c11b5a4ab36",
"metadata": {},
"source": [
"## Let's load the data and take a look on it"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "276773d5-b889-4c99-9a02-9ea83444adc6",
"metadata": {},
"outputs": [],
"source": [
"# Load from .npz file\n",
"loaded = np.load(DATASET_PATH)\n",
"\n",
"# Reconstruct dictionaries\n",
"X_train = {\n",
" 128: torch.from_numpy(loaded['X_train_128']),\n",
" 256: torch.from_numpy(loaded['X_train_256']),\n",
"}\n",
"Y_train = {\n",
" 128: torch.from_numpy(loaded['Y_train_128']),\n",
" 256: torch.from_numpy(loaded['Y_train_256']),\n",
"}\n",
"X_test = {\n",
" 128: torch.from_numpy(loaded['X_test_128']),\n",
" 256: torch.from_numpy(loaded['X_test_256']),\n",
"}\n",
"Y_test = {\n",
" 128: torch.from_numpy(loaded['Y_test_128']),\n",
" 256: torch.from_numpy(loaded['Y_test_256']),\n",
"}\n",
"\n",
"\n",
"del loaded"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "41ada818-deff-45ce-a7f8-88ba036fa871",
"metadata": {},
"outputs": [],
"source": [
"for dx, dname in zip([X_train, Y_train],\n",
" ['X_train', 'Y_train']\n",
" ):\n",
" for k, d in dx.items():\n",
" print(dname, k, d.shape)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "59606532-bb48-4d13-aab3-d36acdfee67a",
"metadata": {},
"outputs": [],
"source": [
"sample_ind = 8"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "26002a63-ab2e-452b-b8df-0979804fad7c",
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(15,15))\n",
"for ind in range(16):\n",
" plt.subplot(4,4,ind+1)\n",
" plt.imshow(X_train[256][sample_ind, ind, ...])\n",
" plt.colorbar()\n",
" plt.contourf(Y_train[256][sample_ind, ...], cmap='Blues', alpha=.3)\n",
" plt.axis('off')\n",
" plt.title(ind)\n",
"plt.tight_layout()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c11eeb15-de2b-48bf-874e-75625da8defd",
"metadata": {},
"outputs": [],
"source": [
"df = pd.read_csv(METADATA_PATH)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "04b12afa-c3e5-4e6f-acbc-41184524df29",
"metadata": {},
"outputs": [],
"source": [
"df"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "037b05ad-636f-474f-9290-90a3d76e78c7",
"metadata": {},
"outputs": [],
"source": [
"# to access the metadata of the `sample_ind`th sample of `X_train_128`\n",
"i, j, start_time = df[(df['size'] == 128) & (df['split'] == 'train') & (df['ind'] == sample_ind)][['i', 'j', 'start_time']].values[0]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bca6ea60",
"metadata": {},
"outputs": [],
"source": [
"print(df[(df['size'] == 128) & (df['split'] == 'train') & (df['ind'] == sample_ind)].values)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8769cd93-0820-4b38-bd2e-93afd584145b",
"metadata": {},
"outputs": [],
"source": [
"solar_elevation(i, j, start_time) # this means sun is below horison -- you can see it on channels 0-3"
]
},
{
"cell_type": "markdown",
"id": "3c594338-f488-4958-a4f6-6b4443195aea",
"metadata": {},
"source": [
"## Load model"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c7c627bb-3d86-4790-a2ff-bda619e6be7f",
"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": "4f2bc8a6",
"metadata": {},
"outputs": [],
"source": [
"X_train[256][sample_ind:sample_ind+1, ...].to(torch.float32).shape"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0e3b1c14-6c1f-4c60-bf4d-8fd90768c4c3",
"metadata": {},
"outputs": [],
"source": [
"prediction = model(X_train[256][sample_ind:sample_ind+1, ...].to(torch.float32))\n",
"prediction = torch.sigmoid(prediction[0,0,...].detach().cpu()).numpy()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bfc7c1af-4914-44bf-beb0-36c626e5d551",
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(12, 4))\n",
"plt.subplot(1,3,1)\n",
"plt.imshow(prediction > .5, cmap='Reds')\n",
"plt.title('Prediction')\n",
"plt.axis('off')\n",
"\n",
"plt.subplot(1,3,2)\n",
"plt.imshow(Y_train[256][sample_ind, ...], cmap='Blues')\n",
"plt.title('Truth')\n",
"plt.axis('off')\n",
"\n",
"plt.subplot(1,3,3)\n",
"plt.title('Combined')\n",
"plt.imshow(prediction > .5, cmap='Reds', alpha=.5)\n",
"plt.contourf(Y_train[256][sample_ind, ...], cmap='Blues', alpha=.5)\n",
"plt.axis('off')\n",
"\n",
"plt.tight_layout()"
]
},
{
"cell_type": "markdown",
"id": "ad41fd6b",
"metadata": {},
"source": [
"## This is how you can run training"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4dd78cc6",
"metadata": {},
"outputs": [],
"source": [
"# # you can check model_utils.prepare_dataset to peak on the data preparation\n",
"train_loaders = build_dataloaders(X_train, Y_train)\n",
"train_segmentation(model, train_loaders, None, lr=1e-3, epochs=1, device=DEVICE) # change device if it's cuda"
]
},
{
"cell_type": "markdown",
"id": "6b2a96af-d155-4ae2-a286-01e8f5587801",
"metadata": {},
"source": [
"## Evaluate model\n",
"\n",
"Note: you can use a separate model for the image-level (rain/no-rain) classification.\n",
"\n",
"Here, we've provided you with a baseline: just utilize segmentation results for it.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "337def9e-e1bc-4a3c-a8dc-a75c7d167008",
"metadata": {},
"outputs": [],
"source": [
"test_loaders = build_dataloaders(X_test, Y_test)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "de423c5f-a72c-404c-a060-62151dd9d6f3",
"metadata": {},
"outputs": [],
"source": [
"dice_val, accuracy, total = evaluate_on_test(model, test_loaders, device=DEVICE)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "90c6e8ce-03e6-4c85-a322-29e16fe448f1",
"metadata": {},
"outputs": [],
"source": [
"total # your task is to make it larger without peaking on Y_test"
]
},
{
"cell_type": "markdown",
"id": "9c057b33-c2e1-4db7-9cb8-4ac31024624d",
"metadata": {},
"source": [
"## 💡 Which channels could help with rain detection?\n",
"\n",
"- C07, C13–C15 → Show cloud-top temperature — cold tops often mean strong storms\n",
"\n",
"- C08–C10 → Show how much water vapor is in the air\n",
"\n",
"- C04, C05, C06 → Help differentiate cloud types (ice vs. water)\n",
"\n",
"- C11 → Good for identifying cloud phase and dusty conditions\n",
"\n",
"- C16 → Useful for estimating cloud height (important for tall rain clouds)\n",
"\n",
"| Channel | Type | Wavelength | What it sees / Why it matters |\n",
"| ------- | ---------- | ---------- | --------------------------------------------- |\n",
"| **C01** | Visible | 0.47 μm | Blue light: detects smoke, haze, small clouds |\n",
"| **C02** | Visible | 0.64 μm | Red light: useful for detailed cloud edges |\n",
"| **C03** | Near-IR | 0.86 μm | Vegetation, cloud phase, land/water contrast |\n",
"| **C04** | Near-IR | 1.38 μm | Thin high clouds (cirrus), upper atmosphere |\n",
"| **C05** | Near-IR | 1.61 μm | Snow vs. cloud detection |\n",
"| **C06** | Near-IR | 2.25 μm | Cloud particle size and ice content |\n",
"| **C07** | Infrared | 3.90 μm | Fog at night, surface heat |\n",
"| **C08** | IR (WV) | 6.19 μm | Upper-level water vapor |\n",
"| **C09** | IR (WV) | 6.95 μm | Mid-level water vapor |\n",
"| **C10** | IR (WV) | 7.34 μm | Lower-level water vapor |\n",
"| **C11** | Infrared | 8.50 μm | Cloud phase, volcanic ash, dust |\n",
"| **C12** | Infrared | 9.61 μm | Ozone detection |\n",
"| **C13** | IR (Clean) | 10.3 μm | Clean infrared: cloud tops, clear air |\n",
"| **C14** | Infrared | 11.2 μm | Standard IR for cloud-top temperature |\n",
"| **C15** | Infrared | 12.3 μm | Dirty window: deeper clouds & water vapor |\n",
"| **C16** | IR (CO₂) | 13.3 μm | CO₂ band: used for estimating cloud height |\n"
]
},
{
"cell_type": "markdown",
"id": "d2ced9bb",
"metadata": {},
"source": [
"## Submission\n",
"\n",
"Your notebook needs to generate a `submission.zip` file containing your predictions on the public testing set `pred_a.npz` and your predictions on the private testing set `pred_b.npz`. Each `.npz` file should contain `Y_pred_128` (shape $51\\times128\\times128$) and `Y_pred_256` (shape $183\\times256\\times256$), your boolean predictions for each testing set."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "93d904a7",
"metadata": {},
"outputs": [],
"source": [
"# first generate pred_a.npz\n",
"\n",
"model.eval()\n",
"model.to(DEVICE)\n",
"\n",
"Y_pred_128 = []\n",
"with torch.no_grad():\n",
" for i in tqdm(range(len(X_test[128]))):\n",
" x = X_test[128][i]\n",
" metadata = df[(df['size'] == 128) & (df['split'] == 'test') & (df['ind'] == i)] # sample metadata usage\n",
" logits = model(x.unsqueeze(0).to(torch.float32).to(DEVICE))\n",
" probs = torch.sigmoid(logits)\n",
" preds = (probs > 0.5).float().squeeze(0)\n",
" Y_pred_128.append(preds.cpu().detach().numpy())\n",
"Y_pred_128 = np.concatenate(Y_pred_128, axis=0)\n",
"\n",
"print(Y_pred_128.shape)\n",
"\n",
"Y_pred_256 = []\n",
"with torch.no_grad():\n",
" for i in tqdm(range(len(X_test[256]))):\n",
" x = X_test[256][i]\n",
" metadata = df[(df['size'] == 256) & (df['split'] == 'test') & (df['ind'] == i)]\n",
" logits = model(x.unsqueeze(0).to(torch.float32).to(DEVICE))\n",
" probs = torch.sigmoid(logits)\n",
" preds = (probs > 0.5).float().squeeze(0)\n",
" Y_pred_256.append(preds.cpu().detach().numpy())\n",
"Y_pred_256 = np.concatenate(Y_pred_256, axis=0)\n",
"\n",
"print(Y_pred_256.shape)\n",
"\n",
"# You must name your prediction arrays `Y_pred_128` and `Y_pred_256`, and name the file `pred_a.npz` for the public leaderboard\n",
"np.savez('pred_a.npz', Y_pred_128=Y_pred_128, Y_pred_256=Y_pred_256)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f9755ae4",
"metadata": {},
"outputs": [],
"source": [
"# Your notebook will gain access to the test dataset via the DATA_PATH environment variable after submission.\n",
"# In the actual debugging process, it is normal for this block to fail to run. \n",
"#‘DATA_PATH’ is an environment variable provided by the testing machine, used to read the testing set. \n",
"# Participants cannot access it directly. Please retain this environment variable during submission, otherwise the testing machine will not be able to read the testing set.\n",
"TEST_PATH = os.environ.get('DATA_PATH', \"test\")\n",
"\n",
"test = np.load(Path(TEST_PATH) / \"X_test.npz\") # Read test data from X_test.npz under the provided path\n",
"\n",
"X_test = {\n",
" 128: torch.from_numpy(test['X_test_128']),\n",
" 256: torch.from_numpy(test['X_test_256']),\n",
"} # only X_test will be provided\n",
"\n",
"df_test = pd.read_csv(Path(TEST_PATH) / \"metadata_test.csv\") # Read metadata from metadata_test.csv under the provided path"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1eee4ee2",
"metadata": {},
"outputs": [],
"source": [
"Y_pred_128 = []\n",
"with torch.no_grad():\n",
" for i in tqdm(range(len(X_test[128]))):\n",
" x = X_test[128][i]\n",
" metadata = df_test[(df_test['size'] == 128) & (df_test['ind'] == i)] # sample metadata usage\n",
" logits = model(x.unsqueeze(0).to(torch.float32).to(DEVICE))\n",
" probs = torch.sigmoid(logits)\n",
" preds = (probs > 0.5).float().squeeze(0)\n",
" Y_pred_128.append(preds.cpu().detach().numpy())\n",
"Y_pred_128 = np.concatenate(Y_pred_128, axis=0)\n",
"\n",
"print(Y_pred_128.shape)\n",
"\n",
"Y_pred_256 = []\n",
"with torch.no_grad():\n",
" for i in tqdm(range(len(X_test[256]))):\n",
" x = X_test[256][i]\n",
" metadata = df_test[(df_test['size'] == 256) & (df_test['ind'] == i)]\n",
" logits = model(x.unsqueeze(0).to(torch.float32).to(DEVICE))\n",
" probs = torch.sigmoid(logits)\n",
" preds = (probs > 0.5).float().squeeze(0)\n",
" Y_pred_256.append(preds.cpu().detach().numpy())\n",
"Y_pred_256 = np.concatenate(Y_pred_256, axis=0)\n",
"\n",
"print(Y_pred_256.shape)\n",
"\n",
"# You must name your prediction arrays `Y_pred_128` and `Y_pred_256`, and name the file `pred_b.npz` for private leaderboard\n",
"np.savez('pred_b.npz', Y_pred_128=Y_pred_128, Y_pred_256=Y_pred_256)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4506b3a0",
"metadata": {},
"outputs": [],
"source": [
"# zip `pred_a.npz` and `pred_b.npz` into `submission.zip`\n",
"with zipfile.ZipFile('submission.zip', 'w') as zipf:\n",
" zipf.write('pred_a.npz')\n",
" zipf.write('pred_b.npz')\n"
]
}
],
"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
}
|