Before we can craft an adversarial example using the Fast Gradient Sign Method, we need a controlled and reproducible workspace. A properly configured environment prevents dependency conflicts and ensures that the code you write will behave as expected. This section guides you through setting up the necessary tools and libraries.
Core Components
Our lab environment is built on a standard Python data science stack. The primary components you will need are:
- Python: Version 3.8 or newer is recommended.
- Pip: The standard Python package installer, which typically comes with modern Python installations.
- A Virtual Environment: An isolated space for our project’s dependencies. We will use Python’s built-in
venvmodule.
Creating an Isolated Environment
Working within a virtual environment is a critical best practice in software development and data science. It isolates your project’s libraries from your system’s global Python installation, preventing version conflicts and ensuring project portability. Think of it as a clean, self-contained workshop for this specific task.
Follow these steps in your terminal or command prompt:
1. Create a Project Directory
# Create a new folder for our lab and navigate into it
mkdir fgsm-lab
cd fgsm-lab
2. Create the Virtual Environment
We’ll use the venv module to create an environment named .venv inside our project directory.
# This creates a '.venv' folder containing a copy of the Python interpreter
python3 -m venv .venv
3. Activate the Environment
Activating the environment modifies your shell’s path to prioritize the executables and libraries within .venv.
On macOS / Linux:
source .venv/bin/activate
On Windows (Command Prompt):
.venvScriptsactivate.bat
Once activated, your command prompt will usually be prefixed with (.venv), indicating that the isolated environment is active.
Installing Required Libraries
With the virtual environment active, we can now install the necessary Python packages. These libraries will be installed only inside .venv, leaving your global Python installation untouched.
| Library | Purpose in this Lab |
|---|---|
torch |
The core deep learning framework. Used for tensor operations, automatic differentiation, and running neural networks. |
torchvision |
Provides access to popular computer vision datasets, pre-trained model architectures (like ResNet), and image transformation utilities. |
numpy |
A fundamental package for numerical computing, essential for manipulating image data represented as arrays. |
matplotlib |
A plotting library used to visualize the original and adversarial images, allowing us to see the results of our attack. |
Run the following command to install all of them at once:
# Ensure your virtual environment is active before running this
pip install torch torchvision numpy matplotlib
Note on Reproducibility
For larger projects, it’s common practice to save dependencies to a file. You could run pip freeze > requirements.txt to create a list of installed packages and their exact versions. This allows others to replicate your environment perfectly by running pip install -r requirements.txt.
Verifying the Installation
A quick check ensures all components are correctly installed and accessible. Create a file named verify_setup.py and add the following code:
# verify_setup.py
import torch
import torchvision
import numpy as np
import matplotlib
def verify():
"""Prints the versions of the installed libraries."""
print("Environment Verification:")
print("-" * 25)
print(f"PyTorch version: {torch.__version__}")
print(f"Torchvision version: {torchvision.__version__}")
print(f"NumPy version: {np.__version__}")
print(f"Matplotlib version: {matplotlib.__version__}")
print("-" * 25)
# Check if a GPU is available for PyTorch
if torch.cuda.is_available():
print("✅ Success: PyTorch can access a CUDA-enabled GPU.")
else:
print("ℹ️ Info: PyTorch is running on CPU. No CUDA-enabled GPU detected.")
if __name__ == "__main__":
verify()
Run the script from your terminal:
python verify_setup.py
If the script executes without any ModuleNotFoundError and prints the version numbers, your environment is correctly configured and ready for the next step: implementing the FGSM attack.