{ "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.ipynb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Radar\n", "\n", "Radar is a key technology in wireless communication, with widespread applications such as self-driving cars. It typically involves an antenna that transmits specific signals and receives their reflections from objects in the environment. By processing these signals, the system determines the angular direction, distance, and velocity of target objects.\n", "\n", "In real-world applications, radar signal processing is challenging due to noise and reflections from non-target objects in the surroundings. For example, when attempting to detect pedestrians, the radar may also receive reflections from trees or other background objects, which can degrade accuracy. Your task is to use AI to analyze the signals received by the radar and identify the presence of a human at each position.\n", "\n", "## Data\n", "\n", "To measure objects surrounding a radar, the following key parameters are used:\n", "\n", "- **Range**: The straight-line distance between the radar and an object.\n", "- **Azimuth**: The horizontal angle (left to right) between the radar and the object.\n", "- **Elevation**: The vertical angle (up or down) of the object relative to the radar.\n", "- **Velocity**: The speed at which the object is moving toward or away from the radar.\n", "\n", "\n", "\n", "The radar data is processed into multiple **heatmaps**, each encoding the **received signal strength** at various positions and directions. \n", "- **Static heatmaps** emphasize reflections from **stationary** objects. \n", "- **Dynamic heatmaps** highlight changes caused by **moving** objects. \n", "\n", "When no object is present at a specific location, the signal consists mostly of background noise and appears weak. In contrast, reflections from an object increase signal intensity, enabling detection of the object.\n", "\n", "For example, the **static range-azimuth heatmap** represents signal strength across different distances (**range**) and horizontal angles (**azimuth**), mainly reflected by stationary objects.\n", "\n", "Each sample in the dataset is stored in a `.mat.pt` file as a tensor of shape $7 \\times 50 \\times 181$, where:\n", "- $7$ is the number of maps (6 heatmaps + 1 semantic label map),\n", "- $50$ represents range bins (distance),\n", "- $181$ represents angular bins, covering angles from $-90^\\circ$ to $+90^\\circ$ in either the horizontal or vertical plane.\n", "\n", "The 6 heatmaps are structured as follows:\n", "\n", "- **Index 0**: Static range-azimuth heatmap \n", "- **Index 1**: Dynamic range-azimuth heatmap \n", "- **Index 2**: Static range-elevation heatmap \n", "- **Index 3**: Dynamic range-elevation heatmap \n", "- **Index 4**: Static range-velocity heatmap \n", "- **Index 5**: Dynamic range-velocity heatmap \n", "\n", "All values in heatmaps are **normalized**, so no unit conversion is required.\n", "\n", "The **map at Index 6** is the semantic label map, stored in range-azimuth format. Each pixel indicates whether a human target is present at that position, using binary values:\n", "- **0**: Human absent \n", "- **1**: Human present\n", "\n", "Here is part of a sample from the dataset:\n", "\n", "\n", "\n", "## Task\n", "\n", "Your task is to develop a model that takes the **first six heatmaps** (indices $0$ to $5$) as input, and predicts the **semantic label map** (index $6$) as the output. The goal is to accurately identify whether a **human target** is present (1) or absent (0) at each location in the radar’s field of view.\n", "\n", "1. **Input**: A tensor of shape **$6 \\times 50 \\times 181$**, representing six radar heatmaps. \n", "2. **Output**: A tensor of shape **$50 \\times 181$**, representing the target semantic label map. \n", "\n", "## Accessing Data\n", "You can download the training_set and validation_set through the link below\n", "\n", "```\n", "!pip install gdown\n", "```\n", "\n", "```\n", "!gdown https://drive.google.com/uc?id=1mXqBIqSfHif3LvJ7Jce1C7addqdfu7B-\n", "!unzip Millimeter-wave_dataset.zip\n", "```\n", "\n", "## Dataset Visualization\n", "You can select a piece of data for visualization to understand the specific content represented by each heatmap.\n", "```python\n", "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_pt_file(file_path):\n", " data = torch.load(file_path)\n", " print(f\"Loaded data shape: {data.shape}\")\n", " num_images = data.shape[0]\n", " cols = 3\n", " rows = (num_images + cols - 1) // cols\n", "\n", " fig = plt.figure(figsize=(cols * 5.5, rows * 5.5), constrained_layout=True)\n", "\n", " gs = gridspec.GridSpec(rows, cols, figure=fig)\n", "\n", " colors = ['black', 'yellow']\n", " cmap_discrete = ListedColormap(colors)\n", "\n", " for i in range(num_images):\n", " img = data[i].numpy().squeeze()\n", " img = np.flipud(img)\n", "\n", " if i < 6:\n", " ax = fig.add_subplot(gs[i // cols, i % cols], projection='polar')\n", " height, width = img.shape\n", " angles = np.linspace(-90, 90, width)\n", " distances = np.linspace(0, 50, height)\n", " angles_rad = np.radians(angles)\n", " theta, r = np.meshgrid(angles_rad, distances)\n", " im = ax.pcolormesh(theta, r, img, shading='auto')\n", "\n", " ax.set_thetalim(np.radians(-90), np.radians(90))\n", " ax.set_rlim(0, 50)\n", " ax.set_thetagrids(np.arange(-90, 91, 30))\n", " ax.set_rticks([0, 10, 20, 30, 40, 50])\n", " ax.set_rlabel_position(45)\n", " ax.set_title(f'Index {i}', pad=20)\n", "\n", " plt.colorbar(im, ax=ax, shrink=0.8, label='Intensity')\n", "\n", " else:\n", " ax = fig.add_subplot(gs[2, :])\n", " height, width = img.shape\n", " img_normalized = img + 1\n", " im = ax.imshow(img_normalized, extent=[-90, 90, 0, height],\n", " cmap=cmap_discrete, vmin=0, vmax=4, aspect='auto')\n", "\n", " ax.set_xlabel('X Axis')\n", " ax.set_ylabel('Y Axis')\n", " ax.set_title(f'Index {i} (Labels)')\n", "\n", " x_ticks = np.linspace(-90, 90, 7)\n", " ax.set_xticks(x_ticks)\n", " ax.set_xticklabels([f'{int(x)}' for x in x_ticks])\n", "\n", " y_ticks = np.linspace(0, height, 6)\n", " ax.set_yticks(y_ticks)\n", " ax.set_yticklabels([f'{int(y)}' for y in y_ticks])\n", "\n", " ax.grid(True, linestyle='--', alpha=0.5)\n", "\n", " legend_elements = [\n", " Patch(facecolor='black', label='Background'),\n", " Patch(facecolor='yellow', label='Human')\n", " ]\n", "\n", " ax.legend(handles=legend_elements,\n", " loc='best',\n", " fontsize='large')\n", "\n", " plt.show()\n", "```\n", "```\n", "file_path = f'/content/training_set/1.mat.pt'\n", "visualize_pt_file(file_path)\n", "```\n", "\n", "Loaded data shape: torch.Size([7, 50, 181])\n", "\n", "\n", "\n", "## Scoring\n", "The score for this task is based on the **accuracy of label recognition**. Correctly identifying target points is weighted more heavily than correctly identifying background points. \n", "\n", "More specifically:\n", "- Each correctly identified **background point** earns **1 point**. \n", "- Each correctly identified **target point** earns **1500 points**. \n", "- The final score is normalized to a **0-1 scale** by comparing it to the maximum possible score. \n", "\n", "The following function calculates your score:\n", "\n", "```\n", "import torch\n", "def cal_accuracy(model, test_loader, bonus):\n", " model.eval()\n", " total_score = 0\n", " total_theo = 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", "\n", " outputs = model(images)\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", "\n", " total_score += score_neg_one + score_other\n", " total_theo += score_theo\n", "\n", " score = total_score.item() / total_theo.item()\n", " return score\n", "```\n", "\n", "## Example\n", "For a $3\\times3$ heatmap, assume the Ground Truth is\n", "$$\n", "\\begin{bmatrix}\n", "0 & 0 & 0 \\\\\n", "1 & 1 & 1 \\\\\n", "0 & 0 & 0\n", "\\end{bmatrix}\n", "$$\n", "The result you identified is\n", "$$\n", "\\begin{bmatrix}\n", "0 & 1 & 0 \\\\\n", "0 & 1 & 0 \\\\\n", "0 & 1 & 0\n", "\\end{bmatrix}\n", "$$\n", "Then there are four correctly identified $0$ and one correctly identified $1$. Your score is $4 + 1500 = 1504$ points. The maximum possible score is $6 + 1500 \\times 3 = 4506$, that is, the score for six $0$s and three $1$s. Your normalized score is 1504 / 4506 = 0.33.\n", "$$\n", "Score = \\frac{4 \\times 1 + 1 \\times 1500}{6 \\times 1 + 3 \\times 1500}=0.33\n", "$$\n" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "name": "stdout", "text": "Epoch [2/40], Train Loss: 0.0041, Val Loss: 0.0040\n" }, "id": "8d97c2f8-b910c07af8ab7bfb46cbfad5_65_197", "meta": {}, "name": "stdout", "output_type": "stream", "parent_header": { "date": "2025-06-25T08:39:10.567571Z", "msg_id": "8d97c2f8-b910c07af8ab7bfb46cbfad5_65_197", "msg_type": "stream", "session": "8d97c2f8-b910c07af8ab7bfb46cbfad5", "username": "username", "version": "5.3" }, "text": [ "Epoch [2/40], Train Loss: 0.0041, Val Loss: 0.0040\n", "Epoch [4/40], Train Loss: 0.0034, Val Loss: 0.0034\n" ] } ], "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", "sys.path.append('/bohr/train-4gug/v2')\n", "from dataloader import load_data\n", "\n", "class MyModel(nn.Module):\n", " def __init__(self):\n", " super(MyModel, self).__init__()\n", " self.conv1 = nn.Conv2d(in_channels=6, out_channels=16, kernel_size=3, padding=1) \n", " self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, padding=1) \n", " self.conv3 = nn.Conv2d(in_channels=32, out_channels=2, kernel_size=3, padding=1)\n", "\n", " self.relu = nn.ReLU()\n", "\n", " def forward(self, x):\n", " x = self.relu(self.conv1(x))\n", " x = self.relu(self.conv2(x))\n", " x = self.conv3(x) \n", " return x\n", "\n", "def train(model, train_loader, test_loader, optimizer, criterion, num_epochs=100):\n", " train_losses = []\n", " val_losses = []\n", " \n", " for epoch in range(num_epochs):\n", " model.train()\n", " epoch_loss = 0.0\n", " batch_count = 0\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", " \n", " outputs = model(images)\n", " outputs = outputs.view(outputs.size(0), outputs.size(1), -1) # [B, C, H*W]\n", " labels = labels.view(labels.size(0), -1) # [B, H*W]\n", " loss = criterion(outputs, labels)\n", " \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", " \n", " outputs = model(images)\n", " outputs = outputs.view(outputs.size(0), outputs.size(1), -1)\n", " labels = labels.view(labels.size(0), -1)\n", " loss = criterion(outputs, labels)\n", " \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", " \n", " if (epoch+1) % 2 == 0:\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", " \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=4, \n", " test_size=0.2\n", ")\n", "\n", "model = MyModel()\n", "if torch.cuda.is_available():\n", " model = model.cuda()\n", "\n", "criterion = nn.CrossEntropyLoss()\n", "optimizer = optim.Adam(model.parameters(), lr=0.001) \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": [ "# 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", "class MyModel(nn.Module):\n", " def __init__(self):\n", " super(MyModel, self).__init__()\n", " self.conv1 = nn.Conv2d(in_channels=6, out_channels=16, kernel_size=3, padding=1)\n", " self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, padding=1)\n", " self.conv3 = nn.Conv2d(in_channels=32, out_channels=2, kernel_size=3, padding=1) # 5 categories\n", "\n", " self.relu = nn.ReLU()\n", "\n", " def forward(self, x):\n", " x = self.relu(self.conv1(x))\n", " x = self.relu(self.conv2(x))\n", " x = self.conv3(x) \n", " return x\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": 16, "metadata": {}, "outputs": [ { "data": { "name": "stdout", "text": "submission_dic.pth file has been saved.\n" }, "id": "8d97c2f8-b910c07af8ab7bfb46cbfad5_65_248", "meta": {}, "name": "stdout", "output_type": "stream", "parent_header": { "date": "2025-06-25T08:41:46.495225Z", "msg_id": "8d97c2f8-b910c07af8ab7bfb46cbfad5_65_248", "msg_type": "stream", "session": "8d97c2f8-b910c07af8ab7bfb46cbfad5", "username": "username", "version": "5.3" }, "text": [ "submission_dic.pth file has been saved.\n" ] }, { "data": { "execution_count": 16, "payload": [], "status": "ok", "user_expressions": {} }, "id": "8d97c2f8-b910c07af8ab7bfb46cbfad5_65_249", "meta": { "dependencies_met": true, "engine": "5900cc83-ab91-40f5-b3e7-13f00c9d6c2c", "started": "2025-06-25T08:41:46.492453Z", "status": "ok" }, "output_type": "execute_reply", "parent_header": { "date": "2025-06-25T08:41:46.496167Z", "msg_id": "8d97c2f8-b910c07af8ab7bfb46cbfad5_65_249", "msg_type": "execute_reply", "session": "8d97c2f8-b910c07af8ab7bfb46cbfad5", "username": "username", "version": "5.3" } } ], "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.\")" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "name": "stdout", "text": "submission.zip Created successfully!\n" }, "id": "8d97c2f8-b910c07af8ab7bfb46cbfad5_65_253", "meta": {}, "name": "stdout", "output_type": "stream", "parent_header": { "date": "2025-06-25T08:41:49.236861Z", "msg_id": "8d97c2f8-b910c07af8ab7bfb46cbfad5_65_253", "msg_type": "stream", "session": "8d97c2f8-b910c07af8ab7bfb46cbfad5", "username": "username", "version": "5.3" }, "text": [ "submission.zip Created successfully!\n" ] }, { "data": { "execution_count": 17, "payload": [], "status": "ok", "user_expressions": {} }, "id": "8d97c2f8-b910c07af8ab7bfb46cbfad5_65_254", "meta": { "dependencies_met": true, "engine": "5900cc83-ab91-40f5-b3e7-13f00c9d6c2c", "started": "2025-06-25T08:41:49.234794Z", "status": "ok" }, "output_type": "execute_reply", "parent_header": { "date": "2025-06-25T08:41:49.237776Z", "msg_id": "8d97c2f8-b910c07af8ab7bfb46cbfad5_65_254", "msg_type": "execute_reply", "session": "8d97c2f8-b910c07af8ab7bfb46cbfad5", "username": "username", "version": "5.3" } } ], "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!')" ] } ], "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 }