Autonomous Drone Navigation via Deep Q-Learning & Computer Vision
An AirSim-based autonomous drone combining a ResNet CNN vision module with deep Q-learning for real-time obstacle avoidance and goal-driven navigation.
Verified results and performance
Project details
- Role
- Machine Learning & Embedded Robotics Developer (Solo Project)
- Timeline
- 2024
- Tracks
- software, embedded
Technologies and skills
Abstract
An autonomous quadcopter navigation pipeline built in Python using Microsoft AirSim and Unreal Engine 4. The system pairs a ResNet-18 visual perception backbone for forward obstacle recognition with a Deep Q-Network (DQN) policy for 3D flight control. By designing dense reward functions balancing obstacle clearance, goal progress, and angular stability, the agent learns collision-free trajectory planning across complex virtual environments without relying on GPS waypoints or active LiDAR sensors.
The Spark: Autonomous Flight in Cluttered Spaces
Piloting a micro aerial vehicle (quadcopter) through unknown or GPS-denied environments like collapsed buildings, dense warehouses, or indoor tunnels is one of the hardest challenges in robotics. Traditional drone navigation relies heavily on external satellite fixes (GPS) or expensive, heavy LiDAR units that consume excessive battery power and add prohibitive payload weight.
"To make micro drones truly autonomous, navigation must come from lightweight onboard cameras and fast neural policies rather than heavy external sensors."
In this project, I set out to build an end-to-end vision-based autonomous flight agent. Using Microsoft AirSim and Unreal Engine 4 as a high-fidelity physical simulation sandbox, I coupled a convolutional neural network (ResNet) vision backbone with a Deep Q-Network (DQN) reinforcement learning agent. The goal was simple: teach a simulated quadcopter to navigate to target waypoints across varied, unfamiliar virtual terrains while autonomously detecting and dodging obstacles in real time.
Software-in-the-loop (SITL) simulation: PX4 Autopilot flight stack running in Linux terminal communicating with Unreal Engine 4 and Microsoft AirSim iris quadcopter.
System Architecture: The Perception and Flight Loop
The overall system operates as a closed-loop Markov Decision Process (MDP) running across Python and Microsoft AirSim:
- AirSim Environment (Unreal Engine 4): Simulates multirotor rigid-body physics, motor aerodynamics, and forward-facing visual cameras at high refresh rates.
- Perception Backbone (ResNet CNN): Captures monocular camera frames (128x128 pixels), processes spatial depth cues, and extracts a dense 128-dimensional visual feature vector.
- State Fusion: Concatenates the visual feature vector with the drone kinematic state (current velocity vector, relative distance vector to the target waypoint, and yaw orientation).
- Deep Q-Network Policy: Evaluates expected discounted future rewards across a discrete flight action space.
- Flight Action Execution: Maps the selected action to low-level AirSim API velocity setpoints (moveByVelocityAsync), advancing the physics simulation by 200 ms per step.
+-------------------------------------------------------------------------+
| 1. AirSim Simulation (Unreal Engine 4) |
| - Forward RGB Camera (1280x720) - 6-DoF Multirotor Kinematics |
+------------------------------------+------------------------------------+
|
v
+-------------------------------------------------------------------------+
| 2. Perception Backbone (Modified ResNet-18) |
| - Downsampled 128x128 Grayscale - 128-D Latent Feature Vector |
+------------------------------------+------------------------------------+
|
v
+-------------------------------------------------------------------------+
| 3. State Concatenation & Normalization |
| - 128-D Visual Latent + 3D Relative Waypoint + 3D Velocity + Heading |
| - Total State Dimension: 135 continuous scalar values |
+------------------------------------+------------------------------------+
|
v
+-------------------------------------------------------------------------+
| 4. Deep Q-Network Policy (DQN MLP) |
| - Input: 135 -> FC(256) + LayerNorm -> FC(128) -> 7 Discrete Actions |
| - Experience Replay (50k transitions) + Target Network Update (500 ep)|
+------------------------------------+------------------------------------+
|
v
+-------------------------------------------------------------------------+
| 5. Velocity Control Setpoint Execution |
| - AirSim moveByVelocityAsync (200 ms control hold @ 5 Hz) |
+-------------------------------------------------------------------------+
Visual Perception Module: ResNet Feature Extraction
Rather than feeding raw high-resolution video directly into the RL policy network (which causes training instability and slow convergence), I designed a modular perception pipeline:
- Input Frame: 1280x720 RGB forward-facing camera image from the front of the drone.
- Preprocessing: Scaled to 128x128 grayscale and normalized to [0, 1] to minimize input dimensionality while preserving obstacle edges and silhouette boundaries.
- Backbone: A modified ResNet-18 feature extractor stripped of its final classification head, producing a compact 128-dimensional latent representation.
- Inference Speed: Using PyTorch with CUDA acceleration, feature extraction completed in just 11 ms per frame, well within the 50 Hz control budget.
import torch
import torch.nn as nn
from torchvision.models import resnet18
class DronePerceptionBackbone(nn.Module):
def __init__(self, latent_dim=128):
super().__init__()
base = resnet18(weights=None)
# Modify first layer for single-channel grayscale input
base.conv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.encoder = nn.Sequential(*list(base.children())[:-1])
self.projection = nn.Linear(512, latent_dim)
self.relu = nn.ReLU()
def forward(self, img_tensor):
# img_tensor shape: (B, 1, 128, 128)
features = self.encoder(img_tensor).squeeze(-1).squeeze(-1)
return self.relu(self.projection(features))
Deep Q-Learning (DQN) Agent Formulation
The reinforcement learning agent models the flight problem with discrete flight commands and continuous state observations:
State Space
At each control step t, the state vector s_t comprises:
- 128-dimensional visual feature vector from the ResNet backbone.
- 3D relative distance vector to target (x_rel, y_rel, z_rel).
- 3D linear velocity vector (v_x, v_y, v_z).
- Current yaw heading error delta_theta.
Total state dimensionality: 135 continuous scalar values.
Action Space
To ensure stable aerodynamic response and avoid erratic flight oscillation, the action space is discretized into 7 flight maneuvers executed at constant cruise speed (2.5 m/s):
- Action 0 (Cruise Forward): Velocity vector (2.5, 0.0, 0.0, 0.0)
- Action 1 (Bank Left): Velocity vector (2.0, -1.2, 0.0, -0.2)
- Action 2 (Bank Right): Velocity vector (2.0, 1.2, 0.0, 0.2)
- Action 3 (Climb and Forward): Velocity vector (2.0, 0.0, -0.8, 0.0)
- Action 4 (Descend and Forward): Velocity vector (2.0, 0.0, 0.8, 0.0)
- Action 5 (Rotate Yaw Left): Velocity vector (0.5, 0.0, 0.0, -0.5)
- Action 6 (Rotate Yaw Right): Velocity vector (0.5, 0.0, 0.0, 0.5)
Deep Q-Network Architecture and Bellman Update
The Q-network consists of a 3-layer fully connected MLP with LayerNorm and LeakyReLU activations:
- Input: 135 dimensions
- Hidden Layer 1: 256 units + LayerNorm
- Hidden Layer 2: 128 units + LayerNorm
- Output: 7 Q-values corresponding to each flight action
Optimization follows the standard Bellman loss with an independent Target Network Q_target:
To maintain training stability:
- Replay Memory Buffer: 50,000 transition tuples (s_t, a_t, r_t, s_t+1, done).
- Mini-batch Size: 64 randomly sampled transitions.
- Target Network Update: Parameters synchronized with policy network every 500 steps.
- Discount Factor: gamma = 0.99.
Loss = E [ ( r + gamma * max_a' Q_target(s', a') - Q(s, a) )^2 ]
Reward Shaping and Hyperparameter Tuning
In reinforcement learning, agent behavior is entirely governed by the reward function. A sparse reward (only rewarding reaching the goal) causes the drone to wander aimlessly and crash indefinitely. I engineered a dense, balanced multi-objective reward function:
- Progress Reward: 10 * (d_prev - d_curr), granting immediate positive reinforcement whenever the drone reduces Euclidean distance to the waypoint.
- Clearance Penalty: -2.0 / (d_min_obs + 0.1), penalizing the agent when approaching walls, poles, or obstacles detected by the proximity sensor.
- Stability Regularization: -0.05 * (|yaw_rate| + |acc_z|), penalizing rapid yaw oscillation and jerky vertical acceleration to promote smooth flight paths.
- Terminal Conditions:
- Reaching target goal within 1.5 meters: +100.0
- Collision detected via AirSim collision API: -100.0
- Step time penalty: -0.1 per step to encourage minimum-time trajectories.
| Training Phase | Exploration (ε) | Avg Return | Flight Characteristics |
|---|---|---|---|
| Phase 1: Exploration (Ep 1 to 200) | 1.00 -> 0.60 | -120 to -60 | Random control inputs; frequent obstacle collisions within 10 to 15 steps |
| Phase 2: Skill Formation (Ep 200 to 500) | 0.60 -> 0.20 | +80 to +180 | Learning banking maneuvers; trajectory duration increases past 120 steps |
| Phase 3: Policy Convergence (Ep 500 to 850) | 0.20 -> 0.05 | +320 to +340 | Stable 1.8 to 2.5m obstacle standoff; smooth goal navigation reached |
| Phase 4: Evaluation (50 unseen trials, ε = 0) | 0.00 | +345 avg | 92% collision-free goal arrival rate at 2.4 m/s cruise speed |
R_total = R_progress + R_clearance + R_stability + R_terminal
def compute_reward(prev_dist, curr_dist, min_obs_dist, collision, reached_goal, yaw_rate):
if collision:
return -100.0, True
if reached_goal:
return 100.0, True
progress = 10.0 * (prev_dist - curr_dist)
obstacle_penalty = -2.0 / (min_obs_dist + 0.1) if min_obs_dist < 3.0 else 0.0
smoothness = -0.05 * abs(yaw_rate)
step_penalty = -0.1
total_reward = progress + obstacle_penalty + smoothness + step_penalty
return total_reward, False
Training Progression and Convergence
Training was conducted over 1,000 episodes across two distinct Unreal Engine environments: a structured warehouse with shelves and an outdoor forest environment with random obstacle distributions:
- Episodes 1 to 200 (Random Exploration, epsilon > 0.6): The quadcopter crashed frequently within 10 to 15 flight steps, unable to associate obstacle visual cues with collision penalties. Average reward remained negative (-120 to -60).
- Episodes 200 to 500 (Skill Formation, epsilon approx 0.3): The agent learned basic banking maneuvers to clear large static obstacles while maintaining forward speed. Episode lengths increased from 15 steps to over 120 steps.
- Episodes 500 to 850 (Convergence, epsilon <= 0.1): Reward curves stabilized near +340. The drone consistently selected smooth banking actions around poles, maintaining a safe 1.8 to 2.5 meter standoff distance.
- Validation Evaluation (epsilon = 0): Evaluated across 50 unseen obstacle configurations, the trained policy achieved a 92% collision-free goal arrival rate with an average flight speed of 2.4 m/s.
Key Engineering Takeaways and Sim-to-Real Considerations
- State Discretization vs Control Frequency: High control frequencies (e.g. 100 Hz) caused the DQN agent to over-sample near-identical image frames, inflating the replay buffer with redundant experiences. Dropping control frequency to 5 Hz (200 ms action holds) drastically stabilized Q-learning convergence.
- Visual Feature Decoupling: Fine-tuning the ResNet backbone end-to-end alongside the Q-network caused gradient destabilization. Freezing early convolutional layers and only training residual projection weights kept visual features stable while the policy converged.
- Sim-to-Real Gap: While AirSim accurately simulates rigid-body aerodynamics and camera optical distortions, real-world drone deployment introduces aerodynamic downwash and lighting variations. Adding random camera brightness jitter and wind gusts during training proved essential for robust policy learning.
Discuss this project
Have questions about the architecture or design decisions?