Certainly! Below is a comprehensive Python implementation that aligns with your requirements. The code is modular, follows PEP-8 standards with appropriate type hints, emphasizes efficiency and scalability, and includes robust error handling. It utilizes torch for the reinforcement learning agent, Gymnasium for the environment simulation, and plotly for visualization.
Overview
- Environment (
AttackDefenseEnv): A custom Gymnasium environment where the agent selects the best defense against a given attack.
- Agent (
RLAgent): A reinforcement learning agent using Deep Q-Network (DQN) implemented with PyTorch to learn optimal defense strategies.
- Visualization: Plotly is used to visualize training progress, agent actions, and environment interactions.
- Interface: A simple command-line interface is provided for interaction and visualization.
Code Implementation
1. Import Necessary Modules
import random
from typing import List, Tuple, Dict, Any
import gymnasium as gym
from gymnasium import spaces
import torch
import torch.nn as nn
import torch.optim as optim
from torch.nn import functional as F
import plotly.graph_objects as go
from collections import deque
import numpy as np
2. Define the Environment
The custom Gymnasium environment simulates interactions between attacks and defenses.
class AttackDefenseEnv(gym.Env):
"""
Custom Gymnasium environment for Attack-Defense scenario using Reinforcement Learning.
"""
def __init__(self, attacks: List[str], defenses: List[str]) -> None:
super(AttackDefenseEnv, self).__init__()
try:
self.attacks = attacks
self.defenses = defenses
self.action_space = spaces.Discrete(len(defenses)) # Actions: Defenses
self.observation_space = spaces.Discrete(len(attacks)) # Observations: Attacks
self.current_attack = None
self.done = False
self.reset()
except Exception as e:
raise ValueError(f"Error initializing the environment: {e}")
def reset(self) -> int:
"""
Resets the environment to an initial state and returns the initial observation.
"""
try:
self.current_attack = random.randint(0, len(self.attacks) - 1)
self.done = False
return self.current_attack
except Exception as e:
raise RuntimeError(f"Error during reset: {e}")
def step(self, action: int) -> Tuple[int, float, bool, Dict[str, Any]]:
"""
Executes one time step within the environment.
"""
try:
assert self.action_space.contains(action), "Invalid action"
attack = self.attacks[self.current_attack]
defense = self.defenses[action]
# Simulate interaction and compute reward
effectiveness = self.get_effectiveness(attack, defense)
# Define reward: +1 for effective defense, -1 otherwise
reward = 1.0 if effectiveness else -1.0
self.done = True # Episode ends after one step
# Prepare next observation
next_state = self.reset()
# Additional information
info = {
'attack': attack,
'defense': defense,
'effectiveness': effectiveness
}
return next_state, reward, self.done, info
except AssertionError as ae:
print(f"Assertion error: {ae}")
return self.current_attack, 0.0, False, {}
except Exception as e:
raise RuntimeError(f"Error during step: {e}")
def render(self, mode: str = 'human') -> None:
"""
Renders the current state of the environment.
"""
try:
if mode == 'human':
attack = self.attacks[self.current_attack]
print(f"Current Attack: {attack}")
else:
super(AttackDefenseEnv, self).render(mode=mode)
except Exception as e:
raise RuntimeError(f"Error during render: {e}")
def get_effectiveness(self, attack: str, defense: str) -> bool:
"""
Determines if the selected defense is effective against the given attack.
For demonstration, effectiveness is randomly determined.
"""
try:
# In a real scenario, replace this with actual effectiveness logic
return random.choice([True, False])
except Exception as e:
raise RuntimeError(f"Error determining effectiveness: {e}")
3. Define the Neural Network for the Agent
The DQN (Deep Q-Network) model that the agent will use to learn optimal actions.
class DQN(nn.Module):
"""
Deep Q-Network (DQN) model for approximating Q-values.
"""
def __init__(self, input_dim: int, output_dim: int) -> None:
super(DQN, self).__init__()
try:
self.fc1 = nn.Linear(input_dim, 128)
self.fc2 = nn.Linear(128, 128)
self.fc3 = nn.Linear(128, output_dim)
except Exception as e:
raise ValueError(f"Error initializing DQN: {e}")
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Forward pass through the network.
"""
try:
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
return self.fc3(x)
except Exception as e:
raise RuntimeError(f"Error during forward pass: {e}")
4. Define the Agent
The reinforcement learning agent that interacts with the environment and learns from experiences.
class RLAgent:
"""
Reinforcement Learning Agent using Deep Q-Network (DQN).
"""
def __init__(
self,
state_size: int,
action_size: int,
lr: float = 1e-3,
gamma: float = 0.99,
epsilon_start: float = 1.0,
epsilon_end: float = 0.1,
epsilon_decay: float = 0.995,
batch_size: int = 64,
memory_size: int = 10000,
device: str = 'cpu'
) -> None:
try:
self.state_size = state_size
self.action_size = action_size
self.lr = lr
self.gamma = gamma
self.epsilon = epsilon_start
self.epsilon_min = epsilon_end
self.epsilon_decay = epsilon_decay
self.batch_size = batch_size
self.memory = deque(maxlen=memory_size)
self.device = torch.device(device)
# Initialize policy and target networks
self.policy_net = DQN(input_dim=state_size, output_dim=action_size).to(self.device)
self.target_net = DQN(input_dim=state_size, output_dim=action_size).to(self.device)
self.target_net.load_state_dict(self.policy_net.state_dict())
self.target_net.eval()
# Optimizer
self.optimizer = optim.Adam(self.policy_net.parameters(), lr=self.lr)
except Exception as e:
raise ValueError(f"Error initializing RLAgent: {e}")
def remember(self, state: int, action: int, reward: float, next_state: int, done: bool) -> None:
"""
Stores experience in replay memory.
"""
try:
self.memory.append((state, action, reward, next_state, done))
except Exception as e:
raise RuntimeError(f"Error storing experience: {e}")
def act(self, state: int) -> int:
"""
Selects an action using epsilon-greedy policy.
"""
try:
if random.random() < self.epsilon:
return random.randint(0, self.action_size - 1)
state_tensor = self.state_to_tensor(state)
with torch.no_grad():
q_values = self.policy_net(state_tensor)
return torch.argmax(q_values).item()
except Exception as e:
raise RuntimeError(f"Error selecting action: {e}")
def state_to_tensor(self, state: int) -> torch.Tensor:
"""
Converts state to one-hot encoded tensor.
"""
try:
state_one_hot = np.zeros(self.state_size)
state_one_hot[state] = 1
return torch.tensor([state_one_hot], dtype=torch.float32).to(self.device)
except Exception as e:
raise ValueError(f"Error converting state to tensor: {e}")
def replay(self) -> None:
"""
Samples a batch from memory and updates the network.
"""
try:
if len(self.memory) < self.batch_size:
return
batch = random.sample(self.memory, self.batch_size)
states, actions, rewards, next_states, dones = zip(*batch)
states = torch.cat([self.state_to_tensor(s) for s in states]).to(self.device)
actions = torch.tensor(actions, dtype=torch.long).unsqueeze(1).to(self.device)
rewards = torch.tensor(rewards, dtype=torch.float32).unsqueeze(1).to(self.device)
next_states = torch.cat([self.state_to_tensor(s) for s in next_states]).to(self.device)
dones = torch.tensor(dones, dtype=torch.float32).unsqueeze(1).to(self.device)
# Current Q values
current_q = self.policy_net(states).gather(1, actions)
# Target Q values
with torch.no_grad():
max_next_q = self.target_net(next_states).max(1)[0].unsqueeze(1)
target_q = rewards + (self.gamma * max_next_q * (1 - dones))
# Loss calculation
loss = F.mse_loss(current_q, target_q)
# Backpropagation
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
# Epsilon decay
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
except Exception as e:
raise RuntimeError(f"Error during replay: {e}")
def update_target_network(self) -> None:
"""
Updates the target network with policy network weights.
"""
try:
self.target_net.load_state_dict(self.policy_net.state_dict())
except Exception as e:
raise RuntimeError(f"Error updating target network: {e}")
def save_model(self, path: str) -> None:
"""
Saves the policy network weights.
"""
try:
torch.save(self.policy_net.state_dict(), path)
except Exception as e:
raise ValueError(f"Error saving model: {e}")
def load_model(self, path: str) -> None:
"""
Loads the policy network weights.
"""
try:
self.policy_net.load_state_dict(torch.load(path))
self.update_target_network()
except Exception as e:
raise ValueError(f"Error loading model: {e}")
5. Define the Training Loop
The training loop where the agent interacts with the environment and learns from experiences.
def train_agent(
env: AttackDefenseEnv,
agent: RLAgent,
episodes: int = 1000,
target_update: int = 50
) -> Tuple[List[float], List[float]]:
"""
Trains the RL agent in the given environment.
Args:
env (AttackDefenseEnv): The attack-defense environment.
agent (RLAgent): The reinforcement learning agent.
episodes (int): Number of training episodes.
target_update (int): Frequency of target network updates.
Returns:
Tuple[List[float], List[float]]: Rewards and effectiveness per episode.
"""
try:
rewards_per_episode = []
effectiveness_per_episode = []
for episode in range(1, episodes + 1):
state = env.reset()
total_reward = 0.0
effectiveness_count = 0
done = False
while not done:
action = agent.act(state)
next_state, reward, done, info = env.step(action)
agent.remember(state, action, reward, next_state, done)
agent.replay()
state = next_state
total_reward += reward
if info['effectiveness']:
effectiveness_count += 1
# Update target network periodically
if episode % target_update == 0:
agent.update_target_network()
rewards_per_episode.append(total_reward)
effectiveness_per_episode.append(effectiveness_count)
# Print progress every 100 episodes
if episode % 100 == 0:
avg_reward = np.mean(rewards_per_episode[-100:])
avg_effectiveness = np.mean(effectiveness_per_episode[-100:])
print(
f"Episode {episode}/{episodes} - "
f"Average Reward: {avg_reward:.2f} - "
f"Average Effectiveness: {avg_effectiveness:.2f} - "
f"Epsilon: {agent.epsilon:.2f}"
)
return rewards_per_episode, effectiveness_per_episode
except Exception as e:
raise RuntimeError(f"Error during training: {e}")
6. Define the Visualization Function
Uses Plotly to visualize training progress.
def visualize_training(
rewards: List[float],
effectiveness: List[float],
attacks: List[str],
defenses: List[str]
) -> None:
"""
Visualizes training progress using Plotly.
Args:
rewards (List[float]): List of rewards per episode.
effectiveness (List[float]): List of effectiveness counts per episode.
attacks (List[str]): List of attack names.
defenses (List[str]): List of defense names.
"""
try:
fig = go.Figure()
# Plot rewards
fig.add_trace(go.Scatter(
y=rewards,
mode='lines',
name='Rewards'
))
# Plot effectiveness
fig.add_trace(go.Scatter(
y=effectiveness,
mode='lines',
name='Effectiveness'
))
fig.update_layout(
title='Training Progress',
xaxis_title='Episode',
yaxis_title='Value',
legend=dict(x=0, y=1),
template='plotly_dark'
)
fig.show()
except Exception as e:
raise RuntimeError(f"Error during visualization: {e}")
7. Define the Main Function
Initializes the environment and agent, starts training, and visualizes the results.
def main():
"""
Main function to initialize environment, agent, train, and visualize results.
"""
try:
# Define attacks and defenses
attacks = [
"Phishing", "DDoS", "Malware", "SQL Injection", "Man-in-the-Middle",
"Brute Force", "Cross-Site Scripting", "Zero-Day", "Insider Threat", "Ransomware"
]
defenses = [
"Firewall", "Intrusion Detection System", "Antivirus", "Encryption",
"Two-Factor Authentication", "Access Control", "Security Training",
"Patch Management", "Network Segmentation", "Backup Solutions"
]
# Initialize environment
env = AttackDefenseEnv(attacks=attacks, defenses=defenses)
# Initialize agent
agent = RLAgent(
state_size=len(attacks),
action_size=len(defenses),
lr=1e-3,
gamma=0.99,
epsilon_start=1.0,
epsilon_end=0.1,
epsilon_decay=0.995,
batch_size=64,
memory_size=10000,
device='cpu' # Change to 'cuda' if GPU is available
)
# Train agent
rewards, effectiveness = train_agent(env, agent, episodes=1000, target_update=50)
# Visualize training
visualize_training(rewards, effectiveness, attacks, defenses)
except Exception as e:
print(f"An error occurred in main: {e}")
8. Execute the Main Function
if __name__ == "__main__":
main()
Explanation of Features and Methods
-
Environment Methods:
reset(): Initializes or resets the environment to a new attack.
step(action): Executes the chosen defense against the current attack, returns the next observation, reward, done flag, and additional info.
render(): Prints the current attack for human observation.
-
Agent Methods:
act(state): Chooses an action using the epsilon-greedy policy.
remember(state, action, reward, next_state, done): Stores experience tuples in replay memory.
replay(): Samples a batch from memory and trains the policy network.
update_target_network(): Copies the policy network parameters to the target network.
save_model(path): Saves the policy network weights.
load_model(path): Loads the policy network weights.
-
Training Loop (train_agent Function):
- Iterates through episodes where the agent interacts with the environment until the episode ends.
- After each action, the agent's experience is stored and used to train the network.
- Periodically updates the target network and prints training progress.
-
Visualization (visualize_training Function):
- Uses Plotly to create dynamic line charts showing rewards and the number of effective defenses over episodes.
Additional Notes
-
State Representation: The state is represented as a one-hot encoded vector indicating the current attack. This simplification assumes that the agent only needs to know the current attack to choose an appropriate defense.
-
Reward Mechanism: For demonstration, the effectiveness of a defense against an attack is randomly determined. In a real-world scenario, this should be based on specific rules or an effectiveness matrix.
-
Scalability: The agent and environment are designed to handle large lists of attacks and defenses; however, as the number increases, more sophisticated state representations and possibly hierarchical learning might be necessary.
-
Error Handling: Comprehensive try-except blocks ensure that any errors during execution are caught and meaningful messages are displayed.
-
Extensibility: This structure allows for easy addition of new attacks or defenses by simply updating the lists. Further enhancements, such as different network architectures or more complex environments, can be integrated seamlessly.
Running the Code
To run the code, ensure that the required modules are installed. You can install them using pip:
pip install gymnasium torch plotly
Then, save the above code into a Python file, for example, attack_defense_rl.py, and execute:
python attack_defense_rl.py
This will start the training process, periodically printing progress and finally displaying the training visualization.
Enhancements and Future Work
-
Effectiveness Matrix: Replace the random effectiveness determination with a predefined matrix that maps each attack to the effectiveness of each defense.
-
Advanced Visualization: Integrate real-time visualization using Dash or Streamlit for more interactive interfaces.
-
Extended Features: Implement additional RL techniques such as Experience Replay prioritization, Double DQN, or Dueling Networks for improved performance.
-
User Interface: Develop a graphical user interface (GUI) to allow users to observe agent actions and environment interactions in real-time.
Feel free to extend and customize the code to better fit your specific use case and requirements!