22.2.2 Environment Preparation

2025.10.06.
AI Security Blog

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:

Kapcsolati űrlap - EN

Do you have a question about AI Security? Reach out to us here:

  • 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 venv module.

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.

Virtual Environment Isolation Concept Host Operating System Global Python Installation /usr/bin/python3 – requests==2.28.1 – ansible==7.0.0 – other-system-lib Project Virtual Environment ./venv/bin/python – torch==1.13.1 – torchvision==0.14.1 – numpy==1.23.5 – matplotlib==3.6.2 ISOLATION

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.