Certainly! Below is a comprehensive Google Colab notebook that processes your multimodal data, constructs the described neural network architecture, generates the top 5 beam predictions, and calculates the accuracy based on your CSV dataset.
Overview
- Environment Setup: Install necessary libraries and import required modules.
- Data Loading and Preprocessing:
- Load the CSV file.
- Define custom dataset classes to handle different data modalities (Images, LiDAR, GPS, etc.).
- Apply necessary transformations and normalization.
- Model Architecture:
- GPS Network: 1D CNN to process GPS data.
- LiDAR Network: 1D CNN layers inspired by PointNet to process LiDAR data.
- Vision Transformer (ViT): Pre-trained ViT from
torchvision to process images.
- Fusion and Prediction Layers: Concatenate embeddings from all modalities and pass through fully connected layers to predict beam indices.
- Training and Evaluation:
- Define loss function and optimizer.
- Train the model on the dataset.
- Evaluate the model by generating top 5 beam predictions and calculating accuracy.
Google Colab Implementation
# Install necessary libraries
!pip install open3d
!pip install torchvision==0.15.2 # Ensure compatibility with your PyTorch version
# Import Libraries
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
import torchvision.transforms as transforms
from torchvision import models
import pandas as pd
import numpy as np
from PIL import Image
import open3d as o3d
import os
from sklearn.model_selection import train_test_split
from tqdm import tqdm
# Set device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# Define Constants
BATCH_SIZE = 16
NUM_EPOCHS = 10
LEARNING_RATE = 1e-4
M_ARRAY_SIZE = 64 # As per your description
# Helper Functions to Load Data
def load_image(path, transform=None):
image = Image.open(path).convert('RGB')
if transform:
image = transform(image)
return image
def load_mmWave(path):
# Assuming mmWave_power_*.txt contains a single float value
with open(path, 'r') as f:
power = float(f.read().strip())
return np.array([power], dtype=np.float32)
def load_lidar(path):
# Load point cloud and extract XYZ coordinates
pcd = o3d.io.read_point_cloud(path)
points = np.asarray(pcd.points)
# Normalize or preprocess as needed
if points.shape[0] < 1024:
pad = 1024 - points.shape[0]
points = np.pad(points, ((0, pad), (0, 0)), 'constant')
else:
points = points[:1024]
return points.astype(np.float32)
def load_radar(path):
# Assuming radar_data_*.npy is a numpy array
radar = np.load(path)
return radar.astype(np.float32)
def load_gps(path):
# Assuming gps_location.txt contains a list of coordinates, e.g., lat, lon, alt
# Here, we'll load it as a numpy array
gps = np.loadtxt(path, delimiter=',') # Adjust delimiter if necessary
# Normalize GPS data if needed
return gps.flatten().astype(np.float32)
# Custom Dataset
class BeamDataset(Dataset):
def __init__(self, csv_file, transform=None):
self.data = pd.read_csv(csv_file)
self.transform = transform
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
row = self.data.iloc[idx]
# Load data modalities
image = load_image(row['unit1_rgb'], self.transform)
mmWave = load_mmWave(row['unit1_pwr_60ghz'])
lidar = load_lidar(row['unit1_lidar'])
radar = load_radar(row['unit1_radar'])
gps1 = load_gps(row['unit1_loc'])
gps2 = load_gps(row['unit2_loc'])
# You can load more modalities if needed
# Concatenate or process GPS data as needed
gps = np.concatenate([gps1, gps2], axis=0)
# Ground truth beam
beam = row['unit1_beam'] # Assuming beam indices start from 0
sample = {
'image': image,
'mmWave': torch.from_numpy(mmWave),
'lidar': torch.from_numpy(lidar),
'radar': torch.from_numpy(radar),
'gps': torch.from_numpy(gps),
'beam': torch.tensor(beam, dtype=torch.long)
}
return sample
# Define Transforms for Images
image_transforms = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
# Normalize based on ImageNet statistics
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std =[0.229, 0.224, 0.225]),
])
# Initialize Dataset and DataLoader
dataset = BeamDataset(csv_file='path_to_your_csv_file.csv', transform=image_transforms)
train_size, test_size = train_test_split(len(dataset), test_size=0.2, random_state=42)
train_dataset, test_dataset = torch.utils.data.random_split(dataset, [train_size, test_size])
train_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True, num_workers=2)
test_loader = DataLoader(test_dataset, batch_size=BATCH_SIZE, shuffle=False, num_workers=2)
# Define the Model
class MultimodalBeamSelectionModel(nn.Module):
def __init__(self, num_beams):
super(MultimodalBeamSelectionModel, self).__init__()
# GPS Network: 1D CNN
self.gps_cnn = nn.Sequential(
nn.Conv1d(in_channels=6, out_channels=16, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool1d(kernel_size=2),
nn.Conv1d(16, 32, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool1d(2)
)
self.gps_embedding = 32 * (6 // 4) # Assuming input length is 6, adjust accordingly
# LiDAR Network: 1D CNN similar to PointNet
self.lidar_cnn = nn.Sequential(
nn.Conv1d(in_channels=3, out_channels=64, kernel_size=1),
nn.ReLU(),
nn.Conv1d(64, 128, kernel_size=1),
nn.ReLU(),
nn.Conv1d(128, 256, kernel_size=1),
nn.ReLU()
)
self.lidar_embedding = 256 # Assuming global feature
# Vision Transformer
self.vit = models.vit_b_16(pretrained=True)
self.vit_features = self.vit.heads.head.in_features
self.vit.heads.head = nn.Identity() # Remove the classification head
# mmWave and Radar might be processed via FC layers
self.mmWave_fc = nn.Linear(1, 16)
self.radar_fc = nn.Linear(10, 16) # Adjust input size based on radar data
# Fusion and Fully Connected Layers
total_embedding = self.gps_embedding + self.lidar_embedding + self.vit_features + 16 + 16
self.fc1 = nn.Linear(total_embedding, 512)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(512, M_ARRAY_SIZE) # M_ARRAY_SIZE represents beam indices
self.fc3 = nn.Linear(512, num_beams) # For classification
def forward(self, image, mmWave, lidar, radar, gps):
# GPS
gps = gps.unsqueeze(1) # Shape: (batch, channels, seq_length)
gps_feat = self.gps_cnn(gps)
gps_feat = gps_feat.view(gps_feat.size(0), -1)
# LiDAR
lidar = lidar.permute(0, 2, 1) # Shape: (batch, channels, points)
lidar_feat = self.lidar_cnn(lidar)
lidar_feat, _ = torch.max(lidar_feat, dim=2) # Global max pooling
# Vision Transformer
vit_feat = self.vit(image)
# mmWave
mmWave_feat = self.mmWave_fc(mmWave)
# Radar
radar_feat = self.radar_fc(radar)
# Concatenate all features
combined = torch.cat([gps_feat, lidar_feat, vit_feat, mmWave_feat, radar_feat], dim=1)
x = self.fc1(combined)
x = self.relu(x)
logits = self.fc2(x)
logits = self.relu(logits)
logits = self.fc3(x) # Final classification layer
return logits
# Initialize Model
num_beams = M_ARRAY_SIZE # Assuming beams are indexed from 0 to M_ARRAY_SIZE-1
model = MultimodalBeamSelectionModel(num_beams=num_beams).to(device)
# Define Loss and Optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)
# Training Loop
for epoch in range(NUM_EPOCHS):
model.train()
running_loss = 0.0
for batch in tqdm(train_loader, desc=f"Training Epoch {epoch+1}/{NUM_EPOCHS}"):
images = batch['image'].to(device)
mmWave = batch['mmWave'].to(device)
lidar = batch['lidar'].to(device)
radar = batch['radar'].to(device)
gps = batch['gps'].to(device)
beams = batch['beam'].to(device)
optimizer.zero_grad()
outputs = model(images, mmWave, lidar, radar, gps)
loss = criterion(outputs, beams)
loss.backward()
optimizer.step()
running_loss += loss.item() * images.size(0)
epoch_loss = running_loss / len(train_loader.dataset)
print(f"Epoch {epoch+1}, Loss: {epoch_loss:.4f}")
# Evaluation
model.eval()
top_k = 5
correct = 0
total = 0
with torch.no_grad():
for batch in tqdm(test_loader, desc="Evaluating"):
images = batch['image'].to(device)
mmWave = batch['mmWave'].to(device)
lidar = batch['lidar'].to(device)
radar = batch['radar'].to(device)
gps = batch['gps'].to(device)
beams = batch['beam'].to(device)
outputs = model(images, mmWave, lidar, radar, gps)
probabilities = torch.softmax(outputs, dim=1)
top5_probs, top5_idx = probabilities.topk(top_k, dim=1)
# Check if ground truth is in top 5
for i in range(beams.size(0)):
if beams[i] in top5_idx[i]:
correct += 1
total += 1
accuracy = correct / total * 100
print(f"Top-5 Accuracy: {accuracy:.2f}%")
# Save the Model
torch.save(model.state_dict(), "multimodal_beam_selection_model.pth")
Explanation of the Implementation
-
Environment Setup:
- Libraries:
open3d for handling LiDAR point cloud data (.ply files).
torchvision for pre-trained Vision Transformer (ViT).
- Device Configuration: Utilizes GPU if available for faster computation.
-
Data Loading and Preprocessing:
- Custom Dataset (
BeamDataset):
- Reads the CSV file.
- Loads and preprocesses each modality:
- Images: Resized and normalized using ImageNet statistics.
- mmWave: Reads power values from
.txt files.
- LiDAR: Loads point clouds using Open3D, normalizes to a fixed size (e.g., 1024 points).
- Radar: Loads radar data from
.npy files.
- GPS: Loads and flattens GPS coordinates from
.txt files.
- DataLoader: Splits data into training and testing sets with an 80-20 split.
-
Model Architecture:
- GPS Network:
- Processes concatenated GPS data (from
unit1_loc and unit2_loc) using 1D CNN layers.
- LiDAR Network:
- Inspired by PointNet, processes LiDAR point clouds with 1D CNN layers and applies global max pooling to extract features.
- Vision Transformer (ViT):
- Utilizes a pre-trained ViT (
vit_b_16) from torchvision.
- Removes the classification head to extract feature embeddings.
- mmWave and Radar Processing:
- Simple fully connected layers to extract features from mmWave and radar data.
- Fusion and Prediction Layers:
- Concatenates embeddings from all modalities.
- Passes through fully connected layers to predict beam indices.
-
Training:
- Uses CrossEntropyLoss suitable for classification tasks.
- Adam optimizer for efficient training.
Notes and Assumptions
-
Data Formats:
- GPS Data: Assumed to be comma-separated values representing latitude, longitude, altitude, etc.
- Radar Data: Assumed to have a fixed size (e.g., 10 features). Adjust
radar_fc input size based on actual data.
-
Model Hyperparameters:
- Batch Size: Set to 16. Adjust based on available GPU memory.
- Number of Epochs: Set to 10. Increase for potentially better performance.
- Learning Rate: Set to
1e-4. Monitor for convergence.
-
Beam Indices: Assumed to range from 0 to M_ARRAY_SIZE - 1. Ensure your unit1_beam in the CSV aligns with this indexing.
-
Transformations:
- Images are resized to 224x224 as required by ViT.
- Normalization parameters are based on ImageNet statistics, which is standard for pre-trained models.
-
Error Handling: For brevity, error handling (e.g., missing files, corrupt data) is not included. It's recommended to add checks for production-level code.
-
Performance: Depending on dataset size and model complexity, training might take significant time. Utilize GPU acceleration for efficiency.
-
Extensibility: This framework can be extended to include additional modalities or more complex network architectures as needed.
This implementation provides a solid foundation for multimodal beam selection using neural networks. Ensure to adjust paths, hyperparameters, and data processing steps according to your specific dataset and requirements.