Certainly! Below is a comprehensive end-to-end Python solution that adheres strictly to PEP-8 standards, utilizes appropriate modules like typing for type hints, and emphasizes optimization, error handling, and maintainability. This solution encompasses:
- Environment Setup: Utilizing OpenAI Gym-style interface, integrating datasets, models, adversarial attacks, and defenses.
- Agent Implementation: A reinforcement learning agent with a model-based policy to select optimal defenses against adversarial attacks.
- Training Loop: Facilitating the interaction between the agent and the environment, including rendering and logging.
- Utility Functions: For loading models, datasets, and evaluating accuracy.
Prerequisites
Before running the code, ensure you have the following libraries installed:
pip install torch torchvision adversarial-robustness-toolbox gym numpy matplotlib
Code Implementation
import random
import logging
from typing import List, Tuple, Dict, Any
import gym
from gym import spaces
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from art.attacks.evasion import FGSM, PGD
from art.estimators.classification import PyTorchClassifier
from art.defences.preprocessor import GaussianAugmentation
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class AdversarialEnvironment(gym.Env):
"""
Custom Environment for Adversarial Image Classification.
"""
metadata = {'render.modes': ['human']}
def __init__(
self,
model: nn.Module,
device: torch.device,
dataset: torch.utils.data.Dataset,
attack_types: List[str],
defenses: List[str],
batch_size: int = 64
) -> None:
super(AdversarialEnvironment, self).__init__()
self.device = device
self.model = model.to(self.device)
self.model.eval()
self.dataset = dataset
self.batch_size = batch_size
self.data_loader = torch.utils.data.DataLoader(
self.dataset, batch_size=self.batch_size, shuffle=True
)
self.attack_types = attack_types
self.defenses = defenses
# Define action and observation space
# Actions are indices of defenses
self.action_space = spaces.Discrete(len(self.defenses) + 1) # +1 for no defense
# Observations can include statistics like accuracy drop
self.observation_space = spaces.Box(
low=0, high=1, shape=(2,), dtype=np.float32
)
# Initialize ART classifier
self.classifier = self._initialize_classifier()
# Initialize attacks
self.attacks = self._initialize_attacks()
# Initialize defences
self.defence_methods = self._initialize_defences()
self.current_attack = None
self.original_accuracy = 0.0
self.attacked_accuracy = 0.0
def _initialize_classifier(self) -> PyTorchClassifier:
"""
Initialize the ART PyTorchClassifier.
"""
loss = nn.CrossEntropyLoss()
optimizer = optim.Adam(self.model.parameters(), lr=0.001)
classifier = PyTorchClassifier(
model=self.model,
loss=loss,
optimizer=optimizer,
input_shape=(3, 32, 32),
nb_classes=10,
device_type=str(self.device)
)
return classifier
def _initialize_attacks(self) -> Dict[str, Any]:
"""
Initialize adversarial attacks based on the provided attack types.
"""
attacks = {}
for attack_name in self.attack_types:
if attack_name.lower() == 'fgsm':
attacks['FGSM'] = FGSM(estimator=self.classifier, eps=0.3)
elif attack_name.lower() == 'pgd':
attacks['PGD'] = PGD(estimator=self.classifier, eps=0.3, eps_step=0.01, max_iter=40)
else:
logger.warning(f"Attack {attack_name} not recognized.")
return attacks
def _initialize_defences(self) -> Dict[str, Any]:
"""
Initialize defenses based on the provided defenses list.
"""
defences = {}
for defence_name in self.defenses:
if defence_name.lower() == 'gaussian':
defences['GaussianAugmentation'] = GaussianAugmentation(mean=0.0, stddev=0.1)
else:
logger.warning(f"Defence {defence_name} not recognized.")
return defences
def reset(self) -> np.ndarray:
"""
Reset the environment for a new episode.
"""
self.current_attack = random.choice(list(self.attacks.keys()))
self.original_accuracy, _ = self._evaluate_model(self.dataset)
adversarial_dataset = self._apply_attack(self.current_attack)
self.attacked_accuracy, _ = self._evaluate_model(adversarial_dataset)
observation = np.array([self.original_accuracy, self.attacked_accuracy], dtype=np.float32)
logger.info(f"Environment reset: Attack={self.current_attack}, Original Acc={self.original_accuracy:.2f}, Attacked Acc={self.attacked_accuracy:.2f}")
return observation
def step(self, action: int) -> Tuple[np.ndarray, float, bool, Dict]:
"""
Execute one step within the environment.
"""
done = False
info = {}
if action == len(self.defences):
# No defense applied
defended_accuracy = self.attacked_accuracy
logger.info("No defense applied.")
else:
defence_name = self.defenses[action]
defended_accuracy, _ = self._apply_defense(defence_name)
logger.info(f"Defense applied: {defence_name}, Defended Acc={defended_accuracy:.2f}")
# Calculate reward as the recovered accuracy percentage
reward = defended_accuracy - self.attacked_accuracy
logger.info(f"Reward: {reward:.2f}")
# Prepare next observation
observation = np.array([self.original_accuracy, defended_accuracy], dtype=np.float32)
# For simplicity, let's end the episode after one step
done = True
return observation, reward, done, info
def render(self, mode: str = 'human') -> None:
"""
Render the environment. Placeholder for potential future implementations.
"""
pass
def close(self) -> None:
"""
Close the environment.
"""
pass
def _apply_attack(self, attack_name: str) -> torch.utils.data.Dataset:
"""
Apply the specified adversarial attack to the dataset.
"""
attack = self.attacks.get(attack_name)
if not attack:
raise ValueError(f"Attack {attack_name} not initialized.")
x, y = self._get_numpy_data(self.dataset)
logger.info(f"Applying attack: {attack_name}")
x_adv = attack.generate(x=x)
adversarial_dataset = torch.utils.data.TensorDataset(
torch.tensor(x_adv.transpose((0, 3, 1, 2)), dtype=torch.float32),
torch.tensor(y, dtype=torch.long)
)
return adversarial_dataset
def _apply_defense(self, defence_name: str) -> Tuple[float, Any]:
"""
Apply the specified defense to the adversarial dataset and evaluate accuracy.
"""
defence = self.defence_methods.get(defence_name)
if not defence:
raise ValueError(f"Defence {defence_name} not initialized.")
x, y = self._get_numpy_data(self.dataset)
logger.info(f"Applying defence: {defence_name}")
x_def = defence(x=x)
defended_dataset = torch.utils.data.TensorDataset(
torch.tensor(x_def.transpose((0, 3, 1, 2)), dtype=torch.float32),
torch.tensor(y, dtype=torch.long)
)
accuracy, _ = self._evaluate_model(defended_dataset)
return accuracy, defended_dataset
def _evaluate_model(self, dataset: torch.utils.data.Dataset) -> Tuple[float, float]:
"""
Evaluate the model on the provided dataset and return accuracy.
"""
loader = torch.utils.data.DataLoader(
dataset, batch_size=self.batch_size, shuffle=False
)
correct = 0
total = 0
with torch.no_grad():
for data in loader:
images, labels = data
images = images.to(self.device)
labels = labels.to(self.device)
outputs = self.model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = correct / total
return accuracy, correct / total
@staticmethod
def _get_numpy_data(
dataset: torch.utils.data.Dataset
) -> Tuple[np.ndarray, np.ndarray]:
"""
Convert PyTorch dataset to NumPy arrays.
"""
loader = torch.utils.data.DataLoader(
dataset, batch_size=len(dataset), shuffle=False
)
data_iter = iter(loader)
images, labels = data_iter.next()
x = images.numpy().transpose((0, 2, 3, 1)) # Convert to NHWC
y = labels.numpy()
return x, y
class PolicyNetwork(nn.Module):
"""
Simple Policy Network for the Agent.
"""
def __init__(self, input_dim: int, output_dim: int) -> None:
super(PolicyNetwork, self).__init__()
self.fc = nn.Sequential(
nn.Linear(input_dim, 128),
nn.ReLU(),
nn.Linear(128, output_dim),
nn.Softmax(dim=-1)
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.fc(x)
class Agent:
"""
Reinforcement Learning Agent with Model-Based Policy.
"""
def __init__(
self,
state_dim: int,
action_dim: int,
lr: float = 1e-3
) -> None:
self.policy_network = PolicyNetwork(state_dim, action_dim)
self.optimizer = optim.Adam(self.policy_network.parameters(), lr=lr)
self.memory = []
self.gamma = 0.99 # Discount factor
def select_action(self, state: np.ndarray) -> int:
"""
Select an action based on the current state.
"""
state_tensor = torch.from_numpy(state).float()
probs = self.policy_network(state_tensor)
action = torch.multinomial(probs, 1).item()
return action
def store_transition(self, state: np.ndarray, action: int, reward: float) -> None:
"""
Store the transition in memory.
"""
self.memory.append((state, action, reward))
def learn(self) -> None:
"""
Update the policy network based on stored transitions.
"""
if not self.memory:
return
# Compute discounted rewards
rewards = []
G = 0
for _, _, reward in reversed(self.memory):
G = reward + self.gamma * G
rewards.insert(0, G)
rewards = torch.tensor(rewards)
rewards = (rewards - rewards.mean()) / (rewards.std() + 1e-9)
# Compute loss
loss = 0
for i, (state, action, _) in enumerate(self.memory):
state_tensor = torch.from_numpy(state).float()
probs = self.policy_network(state_tensor)
log_prob = torch.log(probs[action] + 1e-9)
loss -= log_prob * rewards[i]
# Backpropagation
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
# Clear memory
self.memory = []
def load_model(device: torch.device) -> nn.Module:
"""
Load a pre-trained ResNet18 model for CIFAR-10.
"""
model = torchvision.models.resnet18(pretrained=False, num_classes=10)
# For demonstration, random weights are used. Replace with actual trained weights.
model.to(device)
return model
def load_dataset() -> torch.utils.data.Dataset:
"""
Load CIFAR-10 dataset.
"""
transform = transforms.Compose([
transforms.ToTensor(),
])
test_dataset = torchvision.datasets.CIFAR10(
root='./data', train=False, download=True, transform=transform
)
return test_dataset
def main() -> None:
"""
Main function to train the agent in the adversarial environment.
"""
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Load model and dataset
model = load_model(device)
dataset = load_dataset()
# Define adversarial attacks and defenses
attack_types = ['FGSM', 'PGD']
defenses = ['GaussianAugmentation']
# Initialize environment and agent
env = AdversarialEnvironment(
model=model,
device=device,
dataset=dataset,
attack_types=attack_types,
defenses=defenses
)
state_dim = env.observation_space.shape[0]
action_dim = env.action_space.n
agent = Agent(state_dim=state_dim, action_dim=action_dim)
num_episodes = 1000
for episode in range(num_episodes):
state = env.reset()
action = agent.select_action(state)
try:
next_state, reward, done, _ = env.step(action)
agent.store_transition(state, action, reward)
if done:
agent.learn()
if (episode + 1) % 100 == 0:
logger.info(f"Episode {episode + 1}/{num_episodes} completed.")
except Exception as e:
logger.error(f"An error occurred during episode {episode+1}: {e}")
logger.info("Training completed.")
if __name__ == '__main__':
main()
Code Explanation
-
Imports and Logging:
- Essential libraries are imported, including
gym for environment simulation, torch and torchvision for model and dataset handling, and adversarial-robustness-toolbox for adversarial attacks and defenses.
- Logging is configured to monitor the training process and debug if necessary.
-
AdversarialEnvironment Class:
- Inherits from
gym.Env to simulate a reinforcement learning environment.
- Initializes the model, dataset, adversarial attacks (FGSM and PGD), and defenses (Gaussian Augmentation in this case).
- Defines the action space as discrete actions corresponding to available defenses plus an option for no defense.
- The observation space consists of two floating-point numbers: original accuracy and accuracy after attack.
- Implements the
reset method to start a new episode by selecting a random attack and evaluating accuracies.
- The
step method applies the chosen defense, calculates the reward based on accuracy recovery, and returns the new state.
- Includes utility methods to apply attacks, defenses, evaluate model accuracy, and convert dataset formats.
-
PolicyNetwork and Agent Classes:
PolicyNetwork is a simple feedforward neural network that outputs a probability distribution over actions.
Agent utilizes the policy network to select actions, stores transitions, and updates the policy based on collected experiences using policy gradients.
-
Utility Functions:
load_model: Loads a pre-defined ResNet18 model. For a real-world scenario, replace the random weights with a trained model.
load_dataset: Loads the CIFAR-10 test dataset.
-
Main Function:
- Sets up the device, model, dataset, environment, and agent.
- Runs a training loop for a specified number of episodes where the agent interacts with the environment and learns to select optimal defenses.
- Logs progress every 100 episodes.
-
Error Handling:
- Comprehensive error handling is implemented within the training loop to catch and log any exceptions without crashing the program.
-
Type Hints and PEP-8 Compliance:
Notes
-
Model Training: The provided load_model function initializes a ResNet18 model with random weights. For meaningful evaluations, you should train the model on the CIFAR-10 training set before deploying it in the environment.
-
Defenses and Attacks: Currently, only FGSM and PGD attacks, along with Gaussian Augmentation defense, are implemented. You can extend the attack_types and defenses lists with more sophisticated methods from the adversarial-robustness-toolbox.
-
Scaling and Optimization: For handling larger datasets or more complex models, consider optimizing data loading, utilizing GPU acceleration, and implementing more efficient algorithms.
-
Rendering and Visualization: The render method is a placeholder. Depending on your requirements, you can implement visualization of attacks, defenses, and model performance.
-
Reproducibility: For consistent results, especially during training, consider setting random seeds for numpy, torch, and other libraries.
Conclusion
This solution provides a solid foundation for developing an adversarial environment with a reinforcement learning agent to select optimal defenses for image classification tasks. It emphasizes clean, maintainable, and efficient code adhering to best practices and PEP-8 standards. You can further enhance this framework by integrating more advanced models, attacks, defenses, and agent strategies as needed.