{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\"IOAI\n", "\n", "[IOAI 2025 (Beijing, China), Individual Contest](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/Individual-Contest/Radar/Radar.ipynb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Radar\n", "\n", "## 1. Problem Description \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", "In this task, we provide an **indoor radar experiment dataset**, and your objective is to develop a model that performs **radar semantic segmentation**. \n", "\n", "\n", "## 2. Dataset\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", "\n", "The radar data is processed into multiple **heatmaps**, each encoding the **received signal strength** at various positions and directions.\n", "\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", "\n", "- 7 is the number of maps (6 heatmaps + 1 semantic label map),\n", "- 50 represents range bins (distance),\n", "- 181 represents angular or velocity bins, covering angles from \\-90° to \\+90° in either the horizontal or vertical plane. You can assume that the velocity bins are also remapped from \\-90° to \\+90° for visualization consistency.\n", "- each heatmap intensity value is normalized to [0, 1], representing received signal strength.\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. \n", "\n", "- **-1**: Background (no target)\n", "- **0**: Suitcase\n", "- **1**: Chair\n", "- **2**: Human\n", "- **3**: Wall\n", "\n", "This is the visualization of 1.mat.pt in training_set:\n", "\n", "\n", "\n", "Here is part of a sample from the dataset:\n", "\n", "\n", "\n", "\n", "Data scale: 1800 samples in the training set, 500 samples in the validation set, and 500 samples in the test set.\n", "\n", "## 3\\. 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 what the target is(-1 to 3) 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", "\n", "## 4\\. Submission \n", "\n", "Please submit a file named `submission.ipynb`. The output is a zip file named \"submission.zip\", which contains two tables `submission_val.csv` and `submission_test.csv` corresponding to the prediction results of the validation set and the test set respectively.\n", "\n", "**Note:** The output table should have a header, the data in the table is not the actual solved data, it is only used as an example of the submission format.\n", "\n", "| filename | pixel_0 | pixel_1 | ... | pixel_9049 |\n", "| :------: | :-----: | ------- | --- | ---------- |\n", "| 1.mat.pt | -1 | -1 | ... | -1 |\n", "| ... | ... | ... | ... | ... |\n", "\n", "## 5\\. Score\n", "\n", "The score is based on the **accuracy of label recognition**. Correctly identifying target points is weighted more heavily than correctly identifying background points. \n", "\n", "### Scoring Criteria: \n", "\n", "* Each correctly identified **background pixel** earns **1 point**. \n", "\n", "* Each correctly identified **non-background pixel** earns **50 points**. \n", "\n", "* The final score is normalized to a **0-1 point** by comparing it to the maximum possible score. \n", "\n", "### Formula:\n", "$$\n", "Score = \\frac{|C_{0,correct}| \\times 1 + |C_{1,correct}| \\times bonus}{|C_0| \\times 1 + |C_1| \\times bonus}\n", "$$\n", "where:\n", "\n", "$$\n", "\\begin{aligned}\n", "I &= \\{1, 2, \\dots, 50\\times 181\\}\\\\\n", "C_0 &= \\{i \\in I \\mid y_i = -1\\}\\\\\n", "C_1 &= \\{i \\in I \\mid y_i \\neq -1\\}\\\\\n", "C_{0,correct} &= \\{i \\in C_0 \\mid p_i = y_i\\}\\\\\n", "C_{1,correct} &= \\{i \\in C_1 \\mid p_i = y_i\\}\\\\\n", "\\end{aligned}\n", "$$\n", "\n", "\n", "### Example\n", "\n", "For a $3\\times3$ heatmap, assume the Ground Truth is:\n", "\n", "$$\n", "\\begin{bmatrix}\n", "-1 & -1 & -1 \\\\\n", "1 & 2 & 3 \\\\\n", "-1 & -1 & -1\n", "\\end{bmatrix}\n", "$$\n", "\n", "The intenteded result is:\n", "\n", "$$\n", "\\begin{bmatrix}\n", "-1 & 1 & -1 \\\\\n", "-1 & 2 & -1 \\\\\n", "-1 & 3 & -1\n", "\\end{bmatrix}\n", "$$\n", "\n", "Then there are four correctly identified `-1` and one correctly identified `2`. Your score is 4 + 50 = 54 points. The maximum possible score is 6 + 50 * 3 = 156, that is, the score for six background pixels and three non-background pixels. Your normalized score is 54 / 156 = 0.346.\n", "\n", "$$\n", "Score = \\frac{4 \\times 1 + 1 \\times 50}{6 \\times 1 + 3 \\times 50}=0.346\n", "$$\n", "\n", "## 6. Baseline and Training Set\n", "\n", "- Below you can find the baseline solution.\n", "- The dataset is in `training_set` folder.\n", "- The highest score by the Scientific Committee for this task is 0.90 in Leaderboard B, this score is used for score unification.\n", "- The baseline score by the Scientific Committee for this task is 0.67 in Leaderboard B, this score is used for score unification." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Data Loading" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import random\n", "import numpy as np\n", "import torch\n", "\n", "seed = 42\n", "\n", "random.seed(seed) # Python built-in random\n", "np.random.seed(seed) # NumPy\n", "torch.manual_seed(seed) # PyTorch (CPU)\n", "torch.cuda.manual_seed(seed) # PyTorch (single GPU)\n", "torch.cuda.manual_seed_all(seed) # PyTorch (all GPUs)\n", "\n", "# Ensures deterministic behavior\n", "torch.backends.cudnn.deterministic = True\n", "torch.backends.cudnn.benchmark = False" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import torch\n", "from torch.utils.data import Dataset, DataLoader\n", "from sklearn.model_selection import train_test_split\n", "\n", "class CustomDataset(Dataset):\n", " def __init__(self, file_paths, transform=None):\n", " self.file_paths = file_paths\n", " self.transform = transform\n", " self.file_names = [os.path.basename(path) for path in file_paths]\n", "\n", " def __len__(self):\n", " return len(self.file_paths)\n", "\n", " def __getitem__(self, idx):\n", " data = torch.load(self.file_paths[idx], weights_only=True)\n", " \n", " images = data[:6] \n", " labels = data[6] \n", " \n", " images = images.float() \n", " labels = labels.long() \n", " labels = labels + 1\n", "\n", " if self.transform:\n", " images = self.transform(images)\n", " labels = self.transform(labels)\n", " \n", " return images, labels, self.file_names[idx]\n", "\n", "class CustomDataset_test(Dataset):\n", " def __init__(self, file_paths, transform=None):\n", " self.file_paths = file_paths\n", " self.transform = transform\n", " self.file_names = [os.path.basename(path) for path in file_paths]\n", "\n", " def __len__(self):\n", " return len(self.file_paths)\n", "\n", " def __getitem__(self, idx):\n", " data = torch.load(self.file_paths[idx], weights_only=True)\n", " \n", " images = data[:6] \n", " \n", " images = images.float() \n", "\n", " if self.transform:\n", " images = self.transform(images)\n", " \n", " return images, self.file_names[idx]\n", "\n", "def generate_file_paths(base_path):\n", " file_paths = []\n", " for frame in os.listdir(base_path):\n", " frame_path = os.path.join(base_path, frame)\n", " if frame_path.endswith('.mat.pt'):\n", " file_paths.append(frame_path)\n", " return [path for path in file_paths if os.path.exists(path)]\n", "\n", "def load_data(base_path, batch_size=4, num_workers=2, test_size=0.2):\n", " file_paths = generate_file_paths(base_path)\n", " \n", " train_paths, test_paths = train_test_split(file_paths, test_size=test_size, random_state=42)\n", " \n", " train_dataset = CustomDataset(file_paths=train_paths)\n", " test_dataset = CustomDataset(file_paths=test_paths)\n", " \n", " train_loader = DataLoader(\n", " train_dataset, \n", " batch_size=batch_size, \n", " shuffle=True, \n", " num_workers=num_workers, \n", " drop_last=True\n", " )\n", " \n", " test_loader = DataLoader(\n", " test_dataset, \n", " batch_size=batch_size, \n", " shuffle=False, \n", " num_workers=num_workers, \n", " drop_last=True\n", " )\n", " \n", " return train_loader, test_loader" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Model Definition and Training" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import torch\n", "import torch.nn as nn\n", "import torch.optim as optim\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=5, 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", "TRAIN_PATH = \"./\"\n", "# The training set is deployed automatically in the testing machine. \n", "# You notebook can access the TRAIN_PATH even if you do not mount it along with notebook.\n", "data_path = TRAIN_PATH + 'training_set'\n", "\n", "train_loader, test_loader = load_data(\n", " base_path=data_path,\n", " batch_size=4, \n", " num_workers=2,\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": "markdown", "metadata": {}, "source": [ "### Generate CSV for Submission" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Run inference on validation set and testing set\n", "from torch.utils.data import DataLoader\n", "import pandas as pd\n", "\n", "def run_inference(model, data_loader):\n", " \"\"\"Run inference and return predictions with filenames\"\"\"\n", " model.eval()\n", " predictions = []\n", " filenames = []\n", " \n", " with torch.no_grad():\n", " for images, file_names in data_loader:\n", " images = images.cuda() if torch.cuda.is_available() else images\n", " \n", " outputs = model(images)\n", " preds = torch.argmax(outputs, dim=1)\n", " \n", " # Convert predictions back to original label range [-1, 3]\n", " preds = preds - 1\n", " \n", " # Flatten predictions for each sample\n", " for i, pred in enumerate(preds):\n", " predictions.append(pred.cpu().numpy().flatten())\n", " filenames.append(file_names[i])\n", " \n", " return predictions, filenames\n", "\n", "#DATA_PATH is the secret environment variable to point the address of the validation set and test set on the testing machine. \n", "#You cannot access this address locally.\n", "if os.environ.get('DATA_PATH'):\n", " DATA_PATH = os.environ.get(\"DATA_PATH\") + \"/\" \n", "else:\n", " DATA_PATH = \"\" # Fallback for local testing\n", "# Load validation set\n", "val_paths = generate_file_paths(DATA_PATH + 'validation_set')\n", "val_dataset = CustomDataset_test(file_paths=val_paths)\n", "val_loader = DataLoader(\n", " val_dataset,\n", " batch_size=1,\n", " shuffle=False,\n", " num_workers=2\n", ")\n", "\n", "# Load testing set\n", "test_paths = generate_file_paths(DATA_PATH + 'testing_set')\n", "test_dataset = CustomDataset_test(file_paths=test_paths)\n", "test_loader = DataLoader(\n", " test_dataset,\n", " batch_size=1,\n", " shuffle=False,\n", " num_workers=2\n", ")\n", "\n", "# Run inference on validation set\n", "print(\"Running inference on validation set...\")\n", "val_predictions, val_filenames = run_inference(model, val_loader)\n", "\n", "# Save validation results to CSV\n", "val_results = []\n", "for filename, pred in zip(val_filenames, val_predictions):\n", " # Create a row with filename and flattened predictions\n", " row = {'filename': filename}\n", " for i, p in enumerate(pred):\n", " row[f'pixel_{i}'] = p\n", " val_results.append(row)\n", "\n", "val_df = pd.DataFrame(val_results)\n", "val_df.to_csv('submission_val.csv', index=False)\n", "print(f\"Validation results saved to output_validation.csv with shape: {val_df.shape}\")\n", "\n", "# Run inference on testing set\n", "print(\"Running inference on testing set...\")\n", "test_predictions, test_filenames = run_inference(model, test_loader)\n", "\n", "# Save testing results to CSV\n", "test_results = []\n", "for filename, pred in zip(test_filenames, test_predictions):\n", " # Create a row with filename and flattened predictions\n", " row = {'filename': filename}\n", " for i, p in enumerate(pred):\n", " row[f'pixel_{i}'] = p\n", " test_results.append(row)\n", "\n", "test_df = pd.DataFrame(test_results)\n", "test_df.to_csv('submission_test.csv', index=False)\n", "print(f\"Testing results saved to output_testing.csv with shape: {test_df.shape}\")\n", "\n", "print(\"\\nInference completed! Results saved to:\")\n", "print(\"- submission_val.csv (for validation set leaderboard)\")\n", "print(\"- submission_test.csv (for testing set leaderboard)\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Create .zip File" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import zipfile\n", "import os\n", "\n", "# Define the files to zip and the zip file name.\n", "files_to_zip = ['submission_val.csv', 'submission_test.csv']\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 }