Skip to content
ImagineWorld

Building Our Adversarial Playground

node_idnode-book_adversarial-ai-defense-strategies_chapter-02-building-our-adversarial-playground
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num2
chapter_titleBuilding Our Adversarial Playground
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 2 — Building Our Adversarial Playground

Section titled “Chapter 2 — Building Our Adversarial Playground”

In Chapter 1, we introduced core concepts of artificial intelligence (AI) and machine learning (ML) to help lay the foundations for working with adversarial AI. In this chapter, we will provide a hands-on walkthrough of ML development, demonstrating how to create and manage your development environment, utilize the algorithms, and navigate the life cycle we described. We will build models and deploy a neural network (NN) model as a REST prediction service. This will be our adversarial playground, the target of our adversarial AI attacks.

By the end of the chapter, you will have learned how to do the following:

  • Install Python and create a Python virtual environment to manage your dependencies and work.
  • Install Python packages required for data analysis and ML.
  • Register our virtual environment as a Jupyter Notebook kernel.
  • Use a Jupyter notebook to explore baseline ML algorithms and a simple Keras NN for classifying wine samples. We will demonstrate basic techniques for exploring and preprocessing data and training, testing, and evaluating models.
  • Utilize Keras to construct a convolutional NN (CNN) for classifying images and deploy it as an inference REST service for predictions. This will be the initial target of our adversarial attacks.
  • Understand options for ML at scale for demanding workloads, including Google’s Colaboratory (Colab), Lambda Labs Cloud, Amazon’s Amazon Web Service (AWS), and Microsoft’s Azure.

The chapter covers the following topics:

  • Setting up your development environment
  • Hands-on basic baseline ML
  • Developing our target AI service with CNNs
  • ML development at scale

To follow this chapter, you will need a computer running Windows 10 or 11, macOS, or Linux with at least 8 GB of RAM. For Windows users, I strongly recommend using the Windows Subsystem for Linux 2 (WSL2) and Ubuntu 20.04. For more information on WSL2, see https://learn.microsoft.com/en-us/windows/wsl/tutorials/linux. There are some excellent step-by-step guides on ubuntu.com on how to install and use Ubuntu on WSL2. For more information, see https://ubuntu.com/tutorials/install-ubuntu-on-wsl2-on-windows-11-with-gui-support#1-overview.

You will also need to install packages as we go along; we will explain this in the chapter.

To edit or run the examples, you must have a browser or an IDE that supports Jupyter notebooks, such as Visual Studio Code or IntelliJ PyCharm. Both are free and can be found at https://code.visualstudio.com and https://www.jetbrains.com/pycharm. A browser will be more than sufficient for the examples in this chapter.

You can find the complete code for this book in the book’s companion GitHub repository.

The repository is organized by chapters; for example, ch2 for this chapter.

You may want to use cloud services. We cover this at the end of this chapter. These services provide a scalable, simplified façade on ML environments, but the underlying blocks remain the same. We encourage you to go through setting up a local development environment, even if you use a cloud service. By doing so, you will understand and better troubleshoot your cloud ML environments.

In this section, we will walk through step by step how to set up your Python-based development environment, how to use environments to manage library dependencies, and how to make them available to your Jupyter notebook as a kernel. This will help you create reproducible environments and avoid wasting time troubleshooting errors due to mismatched library versions.

Python is available for all major operating systems, and you can install it by following the instructions.

Windows users can visit the official Python website and download the Python installer. Run the installer, make sure to check the box that says Add Python to PATH, and then follow the prompts to install Python. For more information, see https://www.python.org/downloads/.

Linux users (including WSL2 in Windows) will find that recent versions of Ubuntu and Debian come with Python 3 pre-installed. Otherwise, you can install Python using the distribution’s package manager (apt-get, dnf, and so on). For more information, see https://docs.python-guide.org/starting/install3/linux/#install3-linux.

macOS, earlier called Mac OS X, comes with Python pre-installed but may be out of date. We recommend that you install Python 3 using Homebrew. You will have to have Xcode command-line tools installed beforehand. For a detailed guide, see https://docs.python-guide.org/starting/install3/osx/.

Virtual environments allow you to manage separate package installations for different projects. As discussed in Chapter 1, various options exist for creating and managing Python virtual environments. We will use the Python built-in venv since it’s bundled with Python and requires no additional installations. To create a virtual environment with venv, do the following:

  1. Open your terminal or Command Prompt.
  2. Navigate to the directory where you want to create the virtual environment. Usually, this will be in your project’s directory; for example, adversarial-ai.
  3. To create a virtual environment named .venv, run the
    python3 -m venv .venv

  1. Activate the environment in Linux or macOS using the
    source .venv/bin/activate (Linux/macOS)
    For Windows, use this command:
    .venv\Scripts\activate

The commands create and activate a new Python environment, isolated from your main install and without installed packages. You can verify this by running the following:

pip list

The command will show you what’s installed in your virtual environment:

Figure 2.1 – Listing your installed environments

Figure 2.1 – Listing your installed environments

Since we have not installed any packages yet, the list will only be the package installation tools (that is, pip itself) and setup tools that help package classes and are used by pip under the hood.

You can install the packages you need using pip individually or in groups as command-line parameters; for example:

pip install pandas, matplotlib

Alternatively, you can use a requirements.txt file to specify the libraries and versions needed for your project. Create a requirements.txt file in your project directory with the following content:

numpy==1.22.4
matplotlib==3.5.2
pandas==1.4.3
scikit-learn==1.1.2
Pillow==9.2.0
tensorflow==2.9.1
ipykernel
flask

To install the packages (and of the specified version) included in the requirements file, you need to run a slightly different form of pip:

pip install -r ch2/requirements.txt

Registering your virtual environment with Jupyter notebooks

Section titled “Registering your virtual environment with Jupyter notebooks”

We will be using our virtual environments from Jupyter notebooks and not the traditional Command Prompt after activation. In other words, we want to list our new virtual environment as an IPython kernel. To do this, we need to run the following command while still in the activated virtual environment:

python -m ipykernel install --user --name=secure-ai --display-name="Secure AI"

To verify your installation, deactivate the virtual environment using the following:

deactivate

Start the Jupyter Notebook server by running it in your terminal:

jupyter notebook

You must have Jupyter Notebook in your main Python installation (outside the virtual environment you created). If you receive installation errors, you can install it using pip:

pip install jupyter

Once Jupyter is running, open the verify-environment.ipynb notebook and select the Secure AI kernel:

Figure 2.2 – Selecting our custom kernel in a Jupyter notebook

Figure 2.2 – Selecting our custom kernel in a Jupyter notebook

Step through the cells to verify you have successfully created your environment.

We have covered how to install Python, create an environment, and install the packages with the libraries and frameworks we need for our ML development. We then added this environment to our Jupyter Notebook environment, set it as our kernel, and verified our installation.

We will now use this environment to implement our ML solutions and create a service we will use to attack.

Now that we have a working environment let’s create and step through a Jupyter notebook, implementing and demonstrating the foundational concepts we learned in our previous chapter. The notebook is called basic-ml.ipynb and uses Wine, a sample dataset that comes with scikit-learn. The Wine dataset has 13 different attributes of a wine sample and an associated classification (Class_1, Class_2, Class_3). We will first use the sample dataset to show some basic data exploration techniques, such as printing feature names, target labels, target names, and a data preview:

from sklearn import datasets
import numpy as np
# Load the wine dataset
wine = datasets.load_wine()
# Convert to pandas DataFrame
df = pd.DataFrame(data=np.c_[wine['data'], wine['target']], columns=wine['feature_names'] + ['target'])
print("Features:",df.columns.tolist()[::-1])
print("Targets:",df.target.unique());
print("Target Names:",wine.target_names);
# Display the DataFrame
print()
print("Data Preview")
df.head()

We use sklearn to split the data into training and testing sets by randomly extracting 20% of the data as test data. The random_state parameter allows us to reproduce the split:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(wine.data, wine.target, test_size=0.2, random_state=42)

The technique will be the same for all supervised learning (SL) algorithms. In this example, we will use two algorithms we discussed in the previous chapter (that is, decision trees and their ensemble version of random forest), where we use several decision trees to avoid overfitting and improve performance.

Overfitting, as we discussed in the previous chapter, makes the model memorize features of the training data performing well during training but generalizing poorly; that is, performing poorly on unseen data. Random forests address overfitting by introducing multiple trees with randomly selected features and samples and averaging their predictions to help the model generalize better and perform better on unseen data.

Note how similar their usage is except for the classifier class and the initialization parameters:

from sklearn.tree import DecisionTreeClassifier
# Create and train a decision tree
tree = DecisionTreeClassifier()
tree.fit(X_train, y_train)
# Make predictions on the test set and calculate the accuracy
y_pred_tree = tree.predict(X_test)
accuracy_tree = accuracy_score(y_test, y_pred_tree)
print(f"Decision Tree Accuracy: {accuracy_tree:.2f}" )

Random forests use ensemble learning, which can prevent overfitting and offers better accuracy:

# Now, let's create and train a random forest classifier
from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(n_estimators=100, random_state=42)
forest.fit(X_train, y_train)
# Make predictions on the test set and calculate the accuracy
y_pred_forest = forest.predict(X_test)
accuracy_forest = accuracy_score(y_test, y_pred_forest)
print(f"Random Forest Accuracy: {accuracy_forest:.2f}", )

As expected, the random forest offers better performance of 100% (accuracy of 1) than 94% (accuracy of 0.94) of the decision tree. Wine is a small dataset used here only to show how the interfaces train and test a classifier. The notebook also contains code showing a confusion matrix to help you evaluate model performance. A confusion matrix is a cross-reference of actual versus predicted labels and looks like this:

Figure 2.3 – Random forest confusion matrix

Figure 2.3 – Random forest confusion matrix

When we look at the confusion model, we see how many false positives we have for a class; that is, the number of instances wrongly predicted belonging to that class. This helps us measure the accuracy (Accuracy = Sum of True Positives across all Classes / Total Number of Observations) of the model.

Similarly, we can identify false negatives for a class by looking at instances of that class incorrectly predicted as belonging to a different class.

We will now see how we can implement the same solution using a more advanced algorithm; that is, a simple NN.

We can also solve the wine classification problem using a simple feedforward NN (FNN) with one hidden layer. This type of NN is called a multilayer perceptron (MLP).

The code demonstrates standard preprocessing code for the data, normalizing it to have the same range and avoiding distortions in feature importance:

# Standardize the features to have mean=0 and variance=1
scaler = StandardScaler()
data = scaler.fit_transform(wine.data)

We also apply one-hot encoding to the target variable. This ensures that the target labels (0, 1, 2) are represented as categorical classes rather than a numerical sequence. One-hot encoding achieves this by using a binary vector for each class with a 1 marking the class by position; for example, 100 for 0, 010 for 1, and 001 for 2:

# Convert targets to categorical (one-hot encoding)
targets = to_categorical(wine.target)

The code uses Keras to construct the MLP with 13 inputs, the hidden layer, and a 3-output layer (because of the three classes). It also adds an activation function and hyperparameters, such as batch size and epoch:

# Create a Sequential model
model = Sequential()
model.add(Dense(13, activation='relu', input_shape=(13,)))
model.add(Dense(3, activation='softmax'))
# Compile the model with 'categorical_crossentropy' loss function and 'adam' optimizer
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# Train the model for 20 epochs
model.fit(X_train, y_train, epochs=20, batch_size=1, verbose=1)

Once the training is complete, we can use the predict method to evaluate the model, which seems to have an accuracy of 100%. We use np.argmax on the one-hot encoded values to get the actual class.

We have worked our way into coding a classification solution using basic and more advanced ML algorithms. This allowed us to demonstrate in action the key concepts we discussed in Chapter 1 and use them throughout the book. We are now ready to develop our simple AI service that we will use for adversarial attacks.

Developing our target AI service with CNNs

Section titled “Developing our target AI service with CNNs”

MLPs are relatively simple. The main NN in our playground will be CNN, a type of deep NN (DNN) popular in image and object recognition tasks. We will use CIFAR-10, a public dataset bundled with Keras, to create a sample CNN, save it, and then deploy it for predictions.

CIFAR-10 contains 60,000 32 x 32 images for 10 classes. For more information, see https://keras.io/api/datasets/cifar10/.

We have included a detailed explanation of the steps, acting as a guide to how each step works. We will describe the steps here, but we advise you to walk through the Jupyter notebook and read the comments to understand better how each step works. You can find the notebook in our GitHub repository: the book’s companion GitHub repository (ch2/simple-cnn-cifar10.ipynb).

We have also added a deployment function and code to run predictions (inference) as a REST service and test it with some random images from the internet, not in the CIFAR-10 dataset. This will provide you with a simplified end-to-end development and deployment of our target AI service.

Let’s dive into the steps of developing an AI service using ML and the CIFAR-10 dataset.

We start by importing the libraries we need and testing for GPUs with some code to avoid memory errors if you are training in a multi-GPU environment.

Data collection is simple. Keras provides a method to retrieve the CIFAR-10 dataset and return it split into 50,000 training and 10,000 testing images. We split the training dataset further to the training and validation so that we test without using any data the model has seen during training, even indirectly:

# Load CIFAR-10 dataset
dataset = cifar10.load_data()
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
cifar10_class_names = ["airplane", "automobile", "bird", "cat", "deer","dog", "frog", "horse", "ship", "truck"]
num_classes = len(cifar10_class_names)
print(x_train.shape, x_train.shape)

The notebook has the code to explain data representation. Each dataset is an array of images. Each image, in turn, is represented as 32 x 32 pixel locations, and for each pixel location, we have three values for RGB to capture the pixel intensity (color). Those three values are 8-bit integers with values from 0 to 256. We can view the values for the RGB values for the first pixel of the first image of the training dataset using x_train[0][1][2], which returns an RGB array of [190 194 193].

We also see that we have 10 classes represented from 0 to 9. The notebook also contains the code to visualize and display images with their category using matplotlib:

Figure 2.4 – Visualization of CIFAR-10 samples

Figure 2.4 – Visualization of CIFAR-10 samples

Let us move on to data preprocessing.

We apply two types of preprocessing:

  • Normalization, by scaling our training and test image data to be in the region of 0 to 1 without changing the distribution. The range suits the activation function of NNs. We do this by dividing the RGB values by the maximum value they can get. We use floating division to keep the precision rather than turn values to 0 and 1 with
    x_train_norm, x_val_norm, x_test_norm = x_train.astype("float32") / 255.0, x_val.astype("float32") / 255.0, x_test.astype("float32") / 255.0
  • One-hot categorical encoding of the target labels, which turns a number into a binary vector with the category number used as an index; for example, 6 becomes 0000010000:
    y_train_encoded = keras.utils.to_categorical(y_train, num_classes)
    y_val_encoded = keras.utils.to_categorical(y_val, num_classes)
    y_test_encoded = keras.utils.to_categorical(y_test, num_classes)

We do this to ensure numbers are understood as categorical and not ordinal, preventing any potential misinterpretation of the data due to numeric relationships, such as sequential order.

Algorithm selection and building the model

Section titled “Algorithm selection and building the model”

We will use a CNN model because such models are well suited to image recognition. CNNs rely on convolutions, akin to magnifying glasses (called filters or kernels) sliding over the input data to extract and learn spatial hierarchies and patterns.

In our example, we use Keras APIs to build a CNN with multiple convolutional layers and add some helpful utility layers. This includes pooling, batch normalization, and dropout layers. Pooling layers (MaxPooling2D) reduce image quality and eliminate noise to highlight features and avoid overlift. Batch normalization layers improve performance and stability by normalizing the inputs of each layer across a batch to have a mean of 0 and a variance of 1. This reduces internal covariate shift and aids faster convergence. Dropout layers randomly omit neurons during training to apply regularization to prevent overfitting, which helps the model generalize more on unseen data.

Finally, we flatten the 3D outputs of convolutions to feed them into the more general-purpose fully connected (dense) layers. These layers will perform the classification using the softmax activation function at the end.

Once we define the model architecture, we select an optimization and loss function using popular choices for CNNs. We also set the metric we will use to train our model. We do this as part of compiling the model into an object:

model.compile(optimizer='adam', loss=keras.losses.categorical_crossentropy, metrics=['accuracy'])

Now that we have the model as an object, we call its fit method to train it. When training a model, we define hyperparameters. These are external configurations and define the model’s structure and how it learns, such as learning rate, number of layers, and batch size, influencing its performance and efficiency. In our example, we define two hyperparameters as part of calling the train method: batch_size is the number of training examples used in one iteration of model training, and epochs is a complete pass through the entire training dataset during the training process:

history = model.fit(x_train_norm, y_train_encoded, batch_size=64, epochs=100, validation_data=(x_test_norm, y_test_encoded))

We use a high number of epochs (100), which was the result of experimentation to identify the optimal number of epochs that the validation accuracy stabilizes.

The notebook includes code to visualize the accuracy curve during training using the history object:

Figure 2.5 – Training and validation accuracy curves showing NN convergence

Figure 2.5 – Training and validation accuracy curves showing NN convergence

At epoch 100, further training does not significantly improve the model’s performance. We call this convergence, and it indicates that the model’s weights and biases have stabilized and optimal learning has been achieved. Once the model training has converged, we save the model as a file for further evaluation:

model.save(model_filename)

We use the trained model or load it from the file to see its accuracy on the test data and look at its confusion matrix to detect any irregularities. As expected, the accuracy is around 87%, but we note that dogs and cats are the most significant source of misclassification:

Figure 2.6 – Confusion matrix for the CIFAR-10 CNN

Figure 2.6 – Confusion matrix for the CIFAR-10 CNN

Finally, the notebook has code to deploy the model so that the prediction REST service can use it. The code is very simple, copying the model to a deployment directory and renaming existing models by adding a version to their filename. This allows us to track changes and have backups. The code is for education purposes only. Production-grade systems will use MLOps model registries and pipelines. MLOps stands for ML Operations and is beyond the scope of this chapter. You can find comprehensive information on the use of the Model Registry in MLOps at this link: https://docs.aws.amazon.com/sagemaker/latest/dg/model-registry.html.

Once the model has been deployed, you can test it with an inference_service.py sample REST prediction service. The service is a simple Flask REST service that resizes an uploaded image and uses the deployed model to predict its class.

To use the service from a Terminal window, activate our virtual environment with the following:

source <src base dir>/.venv/activate

Then, navigate to the ch2 folder and run the following:

python inference_service.py

The service will run on port 5000 (you can change that in the code):

Figure 2.7 – Model inference listening as a REST API

Figure 2.7 – Model inference listening as a REST API

From another terminal window, navigate to <src base dir>/ch2 and use the test_client.py sample to test the service. We have collected random images from the web to test the service. You can find them under ch2/images. You can test the service by typing the following:

python test_client.py <full image path>

For example, you can try the following:

python test_client.py images/dog.jpg

The service will return a prediction JSON with both the numeric class and the class name; for example, {'prediction': {'class_name': 'automobile', ' label': 1}}:

Figure 2.8 – Testing the inference API

To stop the inference service, go back to the terminal window where we started the service and press Ctrl + C.

We have learned how to create a simple AI service from training to deployment. Sometimes, training may require more powerful resources than our development workstation can offer. In the next section, we will explore options to help us with this in an affordable manner.

Models may require GPU resources to train in reasonable times. GPUs use specialized hardware designed for parallel processing and simple mathematical operations, similar to the ones used in AI. As a result, they are preferred over CPUs for training large-dataset ML models due to their ability to handle multiple computations simultaneously. This significantly speeds up the training process. Our simple CIFAR-10 dataset, for instance, takes 90 minutes to train on a computer without a GPU and less than 5 minutes with an NVIDIA RTX 4090. GPUs are expensive and have high power requirements. An alternative is to use CPU and GPU computing on demand from cloud vendors.

Google Colab is a free, cloud-based service provided by Google that offers an interactive environment for ML development. It supports Python and provides a platform to create and execute Jupyter notebooks stored in Google Drive or imported from GitHub repositories.

Its focus is on collaboration and ease of use, and it may lack some features out of the box. The free offering allows the use of the NVIDIA T4 GPU. Other GPUs require upgrades to paid models. Training our simple model using the free edition and T4 took about 20 minutes.

For more information on using Google Colab, see https://colab.research.google.com and https://colab.research.google.com/notebooks/gpu.ipynb.

AWS is a cloud platform that has SageMaker, an ML development. It includes SageMaker notebook instances, easy-to-use AWS instances offering libraries, and hosted Jupyter notebooks. It also integrates with GitHub repositories and the AWS ecosystem (for example, Simple Storage Service (S3) buckets). For more details and how to create and instantiate a notebook instance using its Jupyter functionality, see https://docs.aws.amazon.com/sagemaker/latest/dg/gs-setup-working-env.html.

AWS offers a free tier, but none of the tiers cover GPUs. The cheapest GPU instance is g4dn.xlarge with one NVIDIA T4 GPU. You may need to ask AWS to allow them to use them as, by default, the service quote for this instance type is 0. For up-to-date pricing and specs, see https://aws.amazon.com/ec2/instance-types/g4/.

SageMaker offers a sophisticated and secure ML development and operations environment. If you already use AWS, using SageMaker notebook instances as your environment would make sense.

As part of Microsoft’s Azure cloud platform, the Azure Machine Learning services offer an integrated ML Studio service that supports Jupyter notebooks, custom virtual environments, integration with MLOps and Azure features, and so on. For more information on using Jupyter notebooks on Azure Machine Learning services, see https://learn.microsoft.com/en-GB/azure/machine-learning/tutorial-cloud-workstation?view=azureml-api-2.

The cheapest GPU-backed VM on Azure when writing is NC6, which offers a single Tesla K80 GPU. Costs vary depending on the region. For up-to-date pricing and specs, see https://azure.microsoft.com/en-us/pricing/details/machine-learning/.

Azure also offers a 30-day free trial that you can use for your learning.

Lambda Labs Cloud is a dedicated ML platform of on-demand GPU servers, preconfigured with the most popular ML frameworks. Although the platform does not offer the breadth of features other cloud vendors do, it provides high-end GPUs at a very low cost, cheaper than all other vendors.

They are simple to set up and access either via SSH or their web cloud IDE, a pre-installed version of Jupyter Labs (a superset of Jupyter Notebooks). They also provide a persistent storage feature mounted when a new instance is launched. The feature allows the storage of data and configurations (for example, virtual environments), code, and so on. There is an API, but SSH is essential to configure and use this platform continuously. Overall, the platform is closer to using your own computer due to the lack of built-in services.

We used an NVIDIA A100 instance charged at $0.80, which trained our model within 8 minutes, costing less than 20 cents. For more information on using Lambda Labs Cloud, see https://lambdalabs.com/service/gpu-cloud.

We have covered options for using ML at scale. This will be needed when developing and testing some of our adversarial attacks and mitigations.

Congratulations! You have developed your first end-to-end image recognition AI service.

We also learned how to create your Python ML development environment and install and manage your dependencies using pip and virtual environments. We saw how to register these virtual environments in Jupyter notebooks. We walked through two notebooks to develop baseline ML models, a simple NN, and a more advanced CNN for image classification. We looked at how to evaluate and deploy the model and use a simple REST service to host the model and respond to prediction requests. We tested the service with a sample Python client and some random images.

This service will be our main target when we describe adversarial attacks and defenses in the following chapters.

In the next chapter, we will discuss how traditional security applies to our new service and stage our first adversarial attack to demonstrate why traditional security is not enough to stop adversarial AI attacks.