Privacy-Preserving AI
local graph
Chapter 10 — Privacy-Preserving AI
Section titled “Chapter 10 — Privacy-Preserving AI”In the previous chapter, we explored the concept of privacy attacks using adversarial attacks and discussed various countermeasures to protect sensitive data from leaks. This chapter will look at the privacy-preserving techniques that underpin the minimization of exposing sensitive data. These techniques are part of the field of privacy-preserving AI and are used to help develop AI systems with privacy in mind from the ground up. This helps minimize risks and meet our obligations under privacy legislation such as the European General Data Protection Regulation (GDPR). We will cover the following topics:
- Simple data anonymization techniques, including hashing, masking, and obfuscation with Python examples
- Advanced anonymization techniques and tools and introduce the concept of k-anonymity
- Understand the challenges of anonymizing complex data such as geolocation and rich media such as images, audio, and video
- Explore and learn techniques for anonymizing geolocation, images, audio, and video
- Discuss the concept of differential privacy with code examples and show how it helps us minimize data exposure
- Explore how distributed AI models such as federated and split learning can help preserve privacy
- Learn how to apply advanced encryption options such as Secure Multi-Party Computation (SMPC) and homomorphic encryption to provide advanced protection to private data, especially in distributed model settings
Let’s start with a brief overview of privacy-preserving AI, its relation to privacy-preserving ML, and our legal and regulatory compliance requirements.
Privacy-preserving ML and AI
Section titled “Privacy-preserving ML and AI”Privacy-preserving AI is an approach in modern data analytics, ML, and AI to protect sensitive information while valuable insights from data are extracted. It incorporates various techniques to safeguard individual privacy and is an essential part of meeting privacy legal compliance, such as the GDPR, while protecting sensitive information in sectors such as healthcare, finance, and social media.
The GDPR is a regulation in EU and UK law that protects individuals’ data and privacy and is considered the gold standard in privacy legislation.
Note
You can learn more about the GDPR in the guidance of the Information Commissioner’s Office (ICO), the UK’s GDPR regulator. This can be found at https://ico.org.uk/for-organisations/uk-gdpr-guidance-and-resources/. Other countries have similar legislation, and the EU recognizes the adequacy in the legislation of Andorra, Argentina, Canada (commercial organizations), Faroe Islands, Guernsey, Israel, Isle of Man, Japan, Jersey, New Zealand, Republic of Korea, and Switzerland. You can find an up-to-date list at https://commission.europa.eu/law/law-topic/data-protection/international-dimension-data-protection/adequacy-decisions_en. The US has a mixture of state-level (e.g., California, Utah, and Colorado) legislation and federal law. The proposed American Data and Privacy Protection Act will provide a GDPR equivalent and is going – at the time of writing – through the legislative process.
The GDPR gives individuals control over their personal data and requires businesses (data controllers and processors ) to ensure the privacy and protection of this data. It imposes hefty fines for data breaches and lack of compliance and introduces the concept of data minimization.
The GDPR requires organizations to identify and use the absolute minimum amount of the data needed to fulfill a specific function. Privacy-preserving AI and ML involve adopting a similar mindset, and offer the techniques and methods to deliver privacy protection support and data minimization.
Privacy-preserving ML focuses on using sensitive information within the domain of ML to ensure that models are developed, trained, and deployed without compromising the privacy of individual data. It focuses on the data used for training and the inferences made by ML models.
Privacy-preserving AI takes this a step further and applies it to the use of data across the entire AI solution.
There are various techniques whose applicability depends on the nature of the application and the use case. We will start exploring privacy-preserving AI with data anonymization techniques.
Simple data anonymization
Section titled “Simple data anonymization”Data anonymization in machine learning involves modifying personally identifiable information (PII) in datasets to prevent individual identification. This process is vital for maintaining data privacy and avoiding disclosure risks.
Different data formats including personal data, images, and videos require different anonymization techniques, balancing data utility with privacy preservation. The simplest way to achieve anonymization is by removing sensitive data not needed for the model or application or preprocessing the data to obscure them in a non-identifiable manner. This includes replacing it with a hash (hashing), using placeholders in a column (masking), or adding random noise to numerical data to obfuscate actual values (obfuscation). Here is an example using Pandas and Keras to show the use of this technique in a machine learning setup.
Let’s assume we have a dataset with user information, including sensitive attributes such as names and email addresses, along with some numerical data that we wish to use to train a Keras model. In this scenario, our model requires age, income, annual expenditure, and house price to determine house affordability.
We protect identifiers with hashing and drop them since they are not really needed. Since we have determined that they are not needed for model decisions, we can drop them without compromising the performance of the model. Outside of model training, we keep them anonymized and saved for traceability and operational validation queries. This will prevent model inversion attacks and memorization of data.
Which items you anonymize and use will depend on your model needs and feature selection. In this scenario, for instance, we have established that house location is an essential factor but do not want to have the full postcode because it is a quasi-identifier; that is, combined with age, it could re-identify an individual.
A privacy-preserving approach would be to rely only on the first part of the postcode, which in the UK is a region too broad to be used for re-identification. We use simple masking to reduce the chance of re-identification of an individual by masking the last three characters of the postcode with the letter X. For instance, SW1 2AB becomes SW1 XXX. This takes advantage of the postcode structure where the first three characters identify an area and the last three a much narrower area, usually a group of around 15 addresses. We could de-anonymize further by only using the first two characters indicating a district. This demonstrates the masking technique and is equivalent to dropping the second part of the postcode.
We can use empirical evaluation, data analytics – e.g. regression – and other data exploration techniques to establish the levels of precision required for a feature. We also apply cross-validation to our classification model to evaluate the robustness and stability of our model and achieve the right balance of utility versus privacy.
In this scenario, we assume that we have established these levels. We can obfuscate the income and annual expenditure with some noise that does not materially affect the model training but would help prevent membership inference attacks:
import pandas as pdimport numpy as npimport hashlibfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense# Example DataFramedata = { 'Name': ['Alice', 'Bob', 'Charlie'], 'Email': ['[email protected]', '[email protected]', '[email protected]'], 'Age': [25, 30, 35], 'Post Code': ['SW1A 1AA', 'W1A 0AX', 'EC1A 1BB'] 'Income': [50000, 60000, 70000], 'Annual Expenditure': [20000, 25000, 30000], 'House Price': [200000, 250000, 300000], 'Affordability': [0.5, 0.9, 0.7]}df = pd.DataFrame(data)# Anonymization - Hashing Names and Emails, adding noise to Income and Expendituredf['Name'] = df['Name'].apply(lambda x: hashlib.sha256(x.encode()).hexdigest())df['Email'] = df['Email'].apply(lambda x: hashlib.sha256(x.encode()).hexdigest())df['Income'] += np.random.normal(0, 1000, df['Income'].shape)df['Annual Expenditure'] += np.random.normal(0, 500, df['Annual Expenditure'].shape)# save df anonymised for further exploration and queries# df.<save method># Preparing data for Keras modelX = df[['Age', 'Income', 'Annual Expenditure', 'House Price']] # Using relevant featuresy = df['Affordability']# Build a Keras modelmodel = Sequential([ Dense(10, input_dim=X.shape[1], activation='relu'), Dense(1)])model.compile(optimizer='adam', loss='mean_squared_error')# Fit the modelmodel.fit(X, y, epochs=10, batch_size=1)Here is an example of evaluating different levels of noise:
# Noise levels to testnoise_levels = [100, 500, 1000, 5000]for noise in noise_levels: # Create a copy of X and add noise X_noised = X + np.random.normal(0, noise, X.shape) # Split data into train and test sets X_train, X_test, y_train, y_test = train_test_split(X_noised, y, test_size=0.33, random_state=42) # Fit the model model.fit(X_train, y_train, epochs=10, batch_size=1, verbose=0) # Evaluate the model predictions = model.predict(X_test) mse = MeanSquaredError() mse_value = mse(y_test, predictions).numpy() print(f'Noise Level: {noise}, MSE: {mse_value}')The preceding code trains and evaluates the Keras model for different levels of noise to evaluate the impact on the performance of the model by using the MSE metric. This would be a more methodical approach to choose and validate random noise.
We can also utilize derived features to eliminate the use of private information. For instance, we can use a purchasing power feature derived from income and annual expenditure to help the model generalize on affordability but without having to use income and expenditure altogether:
# Calculating Purchasing Powerdf['Purchasing Power'] = df['Income'] / df['Annual Expenditure']# Preparing data for Keras modelX = df[['Age', 'Purchasing Power', 'House Price']] # Using Age, Purchasing Power, and House Price as featuresy = df['Affordability']In this section, we looked at simple anonymization techniques we can apply to minimize the exposure of our data to the model development process. Anonymization is not always irreversible; two methods can be used to re-identify individuals:
- Direct re-identification: Carrying out direct re-identification from data within the dataset allows us to infer a user’s identity. AOL’s release of the 20 million search queries in 2006, with anonymized user IDs, allowed the New York Times to easily identify one user from her searches, as they were not obfuscated or anonymized, and publish her name – Thelma Arnold – with her consent.
- Linkage attack: This is a less costly re-identification privacy attack. Unlike direct re-identification attacks, linkage attacks do not attempt to analyze the data painstakingly. Instead, they link it with another auxiliary dataset that allows them to infer the identity of the anonymized individual. This is by far the most popular approach. The Netflix dataset de-anonymization in 2007 used the dataset of movie ratings of 500,000 subscribers for a data mining competition. The dataset anonymized subscriber identities, but researchers at the University of Texas found it possible to de-anonymize the dataset by using movie ratings on IMDb, where identity is not anonymized. They showed that an adversary who knows only a few ratings and dates of a Netflix subscriber can easily identify their record in the dataset and learn all the other ratings and potentially sensitive information. They also demonstrated how to obtain auxiliary data from various sources, such as blogs, forums, and subscribers. To achieve these adversarial goals, the researchers developed an algorithm which then applied to the auxiliary information sources. The algorithm uses a similarity measure to compare the auxiliary information with the anonymized records and outputs the most likely match or a set of candidates. You can find out more about the work of Arvind Narayanan and Vitaly Shmatikov in their 2008 paper Robust De-anonymization of Large Datasets (How to Break Anonymity of the Netflix Prize Dataset) at https://arxiv.org/pdf/cs/0610105.pdf.
These are threats that affect all data-driven applications. In our case, we care about minimizing the re-identification of individuals from data used in developing the model and our AI solution. This minimizes the risks of what an attacker could do with the data used by our model and the AI application.
In the next section, we will see more advanced anonymization techniques, libraries, and tools to enable you to provide more robust anonymization.
Advanced anonymization
Section titled “Advanced anonymization”In this section, we will explore how you can apply anonymization to more complex scenarios and with measurable anonymization, which aims to address linkage attacks by introducing degrees of anonymity reflecting linkage. We will start by looking at k-anonymity to achieve measurable anonymity using techniques such as clustering.
K-anonymity
Section titled “K-anonymity”This technique anonymizes data based on the degree of anonymity (k), which ensures that each record in a dataset is indistinguishable from at least k−1 other records concerning certain identifying attributes. The approach aims to make linking data to an individual harder. For instance, in our previous simple masking example, we masked the last three characters of the postcode. With k-linking, the number of masked attributes would depend on how many individuals could be identified with the postcode and all the other attributes.
You can find an implementation in the k-anonymity library at the book’s companion GitHub repository (k-anonymity), which provides a simple anonymise.py script that you can call as shown in the following command:
python anonymize.py --method=<model_type> --k=<k-anonymity> --dataset=<dataset_name>The dataset should be in CSV files, and there should be an associated folder defining the attribute hierarchies. You can find more information in the library’s GitHub README.md file.
The library uses ML techniques to achieve k-anonymity and supports the use of Random Forests, Support Vector Machines, and K-Nearest Neighbors to deliver different methods of k-anonymity (Datafly, Incognito, Topdown Greedy, Classic Mondrian, and Basic Mondrian).
You can use the library to visualize the results of anonymization with the following:
python visualize.pyThis will generate example visualizations and evaluation of the results using three different anonymization metrics: Equivalent Class size metric (also known as CAVG, an abbreviation for class average), discernibility metric (DM), and normalized certainty penalty (NCP). These metrics are statistical techniques to measure anonymization by measuring, respectively, the variance after anonymization, how distinguishable records are, and the downside of information loss after anonymization.
You can find a more detailed definition of these metrics in the paper A Systematic Comparison and Evaluation of k-Anonymization Algorithms for Practitioners. Transactions on Data Privacy by Ayala-Rivera, Mcdonagh, Cerqueus, and Murphy, published in 2014, which can be found at the following URL: https://www.researchgate.net/publication/287537219_A_Systematic_Comparison_and_Evaluation_of_k-Anonymization_Algorithms_for_Practitioners
Microaggregation is a related technique that can support k-anonymity. The technique partitions the dataset into groups of at least k records and replaces the values of each attribute in each group with the average value of that attribute. Micro-aggregation can be applied to one attribute at a time (univariate) or to several attributes simultaneously (multivariate).
You can also find more information on micro-aggregation, k-privacy, and two of its enhancements (i-diversity and t-closeness) in the book Database Anonymization: Privacy Models, Data Utility, and Microaggregation-based Inter-model Connections by Domingo-Ferrer, Sánchez, and Soria-Comas, published in 2016: https://www.researchgate.net/publication/290229262_Database_Anonymization_Privacy_Models_Data_Utility_and_Microaggregation-based_Inter-model_Connections
In addition to libraries, some tools such as Java-based open source desktop applications can help you explore anonymization techniques with your data, namely ARX, anonimatron, and Amnesia. ARX and anonimatron seem to be less actively developed than Amnesia, with their last updates in 2022 and 2021 respectively. You can read more about them at https://arx.deidentifier.org/ and https://realrolfje.github.io/anonimatron/.
Amnesia seems to be being actively developed with EU funding, with some good tutorials and example data. It also offers a headless run mode where you can run it as a REST server, which could be ideal for automation scenarios (ARX and Anonimatron offer a Java library mode).
You can find more information on Amnesia at the following places:
- Desktop app: https://amnesia.openaire.eu/
- REST API server: https://github.com/dTsitsigkos/Amnesia
Note
Anonymization impacts your compliance with privacy legislation and does not always guarantee the prevention of re-identification. The tools and libraries described here will help you understand and evaluate anonymization approaches. However, you should always involve an experienced data scientist and information governance specialist to review your anonymization approaches.
Anonymization and geolocation data
Section titled “Anonymization and geolocation data”Geolocation data is used widely in data experiments and social application data. They are powerful signals that can help inference attacks using data linkage. A well-known case is the one of Jeffrey Burrill, former general secretary of the US Bishops’ Conference, who was outed as having gay encounters and forced to resign by correlating anonymized data sold to data brokers. Although anonymized, the data contained locations gathered daily. This allowed attackers to correlate locations with Burrill’s residence, office, and professional appearances, as well as gay bars and illicit hookup locations. A more recent investigation by the New York Times in 2019 demonstrated how they could track even the then-president Donald Trump. You can find out more about this investigation at https://www.nytimes.com/interactive/2019/12/19/opinion/location-tracking-cell-phone.html.
These examples demonstrate the ubiquity of the potency of location data and the limits they place upon traditional anonymization techniques.
There are various techniques for anonymizing geographical or spatial data:
- Geographic masking: This technique alters the coordinates of individual locations to reduce the risk of re-identification by reverse geocoding. It can be done using different methods, such as random perturbation, Gaussian displacement, donut masking, or bimodal Gaussian displacement. Here is an example of adding
The preceding code adds some random noise to stop attackers from directly identifying an individual from location coordinates. In a more realistic implementation, we will need to help prevent linkage attacks. To achieve this, the amount of displacement should consider the local population density and the desired level of spatial k-anonymity.import numpy as np# Original geographic coordinates (latitude, longitude)original_coordinates = np.array([[51.5074, -0.1278], # London[48.8566, 2.3522], # Paris[40.7128, -74.0060]]) # New York# Define the amount of noise to add (this could be adjusted based on your needs)noise_scale = 0.01# Generate random noisenoise = np.random.normal(scale=noise_scale, size=original_coordinates.shape)# Add noise to original coordinates to get masked coordinatesmasked_coordinates = original_coordinates + noiseprint("Original Coordinates:\n", original_coordinates)print("\nMasked Coordinates:\n", masked_coordinates)
- Spatial aggregation: This technique groups individual locations into larger spatial units, such as regions and partial postal codes. This reduces the resolution and precision of the data and lowers the re-identification risk. We have already applied this in our earlier example of postal codes. We did this intuitively by restricting it to postal districts. K-anonymity should be used for a more robust implementation to achieve the desired degree of separation.
- Geocoding: This means mapping location coordinates to an address, place, or name. The proprietary what3words encode locations in a system of 3-word addresses using a dictionary for the 57 trillion 3x3 meter squares of Earth’s surface. For instance, as shown in the next figure, Big Ben in London has a location of
///clean.wider.both:
Figure 10.1 – Addressing Big Ben’s location using what3words
This intuitively offers some obfuscation of location but no sufficient privacy and anonymization guarantees.
Geocoding has been attacked by reverse geocoding attacks using geocodes and freely available Geographic Information Systems (GISs) such as ArcGIS. Examples include research on a hypothetical healthcare map, the published map of Katrina Hurricane mortality locations, and a map of incidents in Vienna. In all examples, reverse geocoding combining online queries, fieldwork, and the use of ArcGIS revealed significant portions of patient or victim addresses. You can find out more information on ensuring privacy and geographic information in a book by the National Academies Press, Putting People on the Map: Protecting Confidentiality with Linked Social-Spatial Data, freely available at https://nap.nationalacademies.org/download/11865.
A 2014 research paper, Ensuring Confidentiality of Geocoded Health Data: Assessing Geographic Masking Strategies for Individual-Level Data, by Paul A. Zandbergen, concisely reviews attacks and mitigations. It can be found at https://doi.org/10.1155/2014/567049.
This subsection examined the anonymization challenges and approaches to geographic and spatial data. The following subsection will discuss another area that can be challenging to anonymize, namely, media such as images, video, and audio.
Anonymizing rich media
Section titled “Anonymizing rich media”Anonymizing rich media types of information can be more challenging. This is due to their complexity and the amount of nuanced details they contain. Unlike text data, these media types feature intricate patterns and attributes (such as facial expressions in images, tone variations in audio, and body language in videos) that are harder to modify without losing essential information or context. Furthermore, the application of anonymization techniques must carefully balance effectively obscuring identifiable information and maintaining the integrity and usefulness of the media for its intended purpose. Image, audio, and video processing techniques are helpful in the anonymization of rich media. These techniques will vary depending on the context of the application and identifying which parts of the rich media convey sensitive information. Here are some techniques with code examples to anonymize rich media.
Anonymizing images
Section titled “Anonymizing images”Several techniques can be employed, as follows:
- Blurring: Libraries such as OpenCV (the Open Source Computer Vision library) provide functions for blurring images. For instance,
cv2.GaussianBluris used to protect the privacy of individuals in photos. The following shows an example of image pixelation and blurring in Python. We will blur faces using face detection to demonstrate anonymizing just sensitive information, rather than the entire image. We first need to install OpenCV:We import the libraries we need to use:pip install opencv-pythonWe define a utility function to load and display an example image of a woman:import numpy as npimport cv2import matplotlib.pyplot as pltWe will use the following image of a young woman to demonstrate the technique:def show_image(img, size=-1):if size>0:plt.figure(figsize=(size, size), dpi=80)plt.imshow(img)plt.axis('off')image = cv2.imread('../images/woman.jpg')show_image(image)
Figure 10.2 – Image of a young woman
We use cv2 to detect the face. You may need to adjust the scaleFactors, minNeighbors, and minSize parameters to avoid false positives in your images:
face_classifier = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_alt.xml")faces = face_classifier.detectMultiScale(image, scaleFactor=1.3, minNeighbors=5, minSize=(30, 30))print("{0} Face(s) found!".format(len(faces)))1 Face(s) found!We then use cv2.GaussianBlur to blur the detected face:
# Blurringblurred_image = image.copy()for (x, y, w, h) in faces: cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) roi = image[y:y+h, x:x+w] # applying a gaussian blur over this new rectangle area roi = cv2.GaussianBlur(roi,(99, 99), 0) # impose this blurred image on the original image to get the final image blurred_image[y:y+roi.shape[0], x:x+roi.shape[1]] = roishow_image(blurred_image)The two images show the original and blurred images:

Figure 10.3 – Original image (left) and blurred image (right)
Note that we use the maximum noise by maximizing the Gaussian blur kernel to (``99, 99).
- Pixelation: Despite applying the maximum Gaussian noise, visual inspection makes the image easily recognizable. This may fool inversion or extraction attacks, but we may want a stronger anonymization. We can use pixelation to achieve this using OpenCV’s
cv2.resizemethod. Here is how we can amend the example to pixelate the detected face:The code generates the pixelated face region by resizing it and applying the nearest neighborhood interpolation. It then replaces the face with the pixels. Note that the# pixelatepixelated_image = image.copy()for (x, y, w, h) in faces:roi = pixelated_image[y:y+h, x:x+w]# Pixelate the ROIroi = cv2.resize(roi, (20, 20), interpolation=cv2.INTER_NEAREST)roi = cv2.resize(roi, (w, h), interpolation=cv2.INTER_NEAREST)# Replace the original image area with pixelated ROIpixelated_image[y:y+h, x:x+w] = roishow_image(pixelated_image,size=-1)dsizeparameter(20,20)inresizedefines the coarseness of pixelation. The following images show the different sizes of pixelation:
Figure 10.4 – Range of pixelation
- Masking: Masking draws shapes over sensitive parts of an image. You can use both
cv2and PIL to do this. The following is an example of usingcv2to superimpose a red rectangle over the woman’s face. The following code shows you how to use OpenCV as part of your preprocessing:The following images show the original image next to the one with the effects of masking. Note that you can change the opacity of the mask to achieve the best balance between anonymization and usefulness:# Define the red color and opacityred = (255, 0, 0)opacity = 0.8overlaid_image = image.copy()for (x, y, w, h) in faces:overlay = image.copy()cv2.rectangle(overlay, (x, y), (x + w, y + h), red, -1)cv2.addWeighted(overlay, opacity, overlaid_image, 1 - opacity, 0, overlaid_image)show_image(overlaid_image)
Figure 10.5 – Original image (left) and the masked image (right)
- Data perturbation: You can manipulate pixel values using
numpyand apply transformations using OpenCV to create perturbed versions of images. This can apply to the entire image or just its sensitive sections. Here is an example of addingYou can change the parameters of#Using random noiseperturbed_image = image.copy()for (x, y, w, h) in faces:cv2.rectangle(perturbed_image, (x, y), (x + w, y + h), (0, 255, 0), 2)roi = perturbed_image[y:y+h, x:x+w]# Applying a Gaussian blur over this new rectangle area# Add random noise to the imagenoise = np.random.normal(0, 128, roi.shape).astype(np.uint8)roi = cv2.add(roi, noise)# impose the noised face on original image to get the final imageperturbed_image[y:y+roi.shape[0], x:x+roi.shape[1]] = roishow_image(perturbed_image,size)np.random.normalto get different effects. You can also change the random generation of the noise:
Figure 10.6 – Original image (left) and image with added noise (right)
- Face replacement or removal: A more advanced technique is to remove or replace the face with a known utility face that meets the training requirements and will anonymize the individual. Please note that any utility face used should be from a licensed image and comply with privacy legislation so that it does not violate someone else’s privacy.
- Image creation with GANs: This approach uses GANs to create synthetic data with non-identifiable images that fit our model development requirements. This can vary from creating an anonymized variation of an existing or completely new image. Frameworks such as TensorFlow, Keras, and PyTorch support the implementation of GANs. We will explore GANs and example generation in our next chapter.
This will need to be balanced with the usefulness of the anonymized image to develop and test a model.
We have covered several techniques to preprocess image data, aiming to anonymize them.
Note
When preprocessing data, you must find the right balance between security and utility, that is, the usefulness of data for the specific objectives of your AI solution. For example, you can completely anonymize faces if the AI solution concerns object detection and can recognize humans. If the solution is for face recognition, then anonymizing faces will clash with the ability of the model to generalize. You must find the right balance between adding noise and transformations to recognize a face accurately.
There are many other image preprocessing techniques that you can use. The following links provide a good review of them:
- https://neptune.ai/blog/image-processing-techniques-you-can-use-in-machine-learning
- https://opencv-tutorial.readthedocs.io/en/latest/trans/transform.html
The next subsection will cover similar approaches to anonymizing other rich media, such as audio and video.
Audio and video anonymization
Section titled “Audio and video anonymization”Anonymizing audio is trickier since identification can be subjective. Some of the techniques used include the following:
- Voice alteration: Changing a voice’s pitch, speed, or timbre to prevent identification. Software such as Audacity can be used for this purpose.
- Background noise addition: Adding noise to mask identifiable sounds or voices.
- Speech-to-text and text-to-speech synthetization: Converting speech to text and then back to speech using a different synthetic voice.
The following example illustrates a simple anonymization technique by changing the speed and pitch of the audio to evade the automated recognition attacks employed in sophisticated inversion and inference attacks. The example uses the pydub library that you first have to install using pip with gtts, which we use to generate a sample audio file:
pip install pydubOnce we have installed the packages, we can generate an audio file and save it:
# Text to convert to speechtext = "Hello AI, I hope you are not adversarial. Please take a sit"# Create a gTTS objecttts = gTTS(text=text, lang='en')audio_file_path = "../audio/hello_ai.mp3"# Save the audio filetts.save(audio_file_path)We can then use the AudioSegment class from pydub to load an audio file and increase the speed and pitch:
from pydub import AudioSegmentfrom pydub.playback import play# Load audio fileaudio = AudioSegment.from_file(audio_file_path)# Speed up the audio to 1.5 times the original speed# This will increase the pitch as wellspeed_up = audio.speedup(playback_speed=1.5)# Save the modified audiospeed_up.export("modified_audio.mp3", format="mp3")# Play the modified audio (optional)play(speed_up)This code will increase the playback speed of the audio by 1.5 times, which also results in a higher pitch. You can adjust the playback_speed parameter as needed. You would need more complex libraries and techniques for more advanced voice changes (such as applying filters or using machine learning models for voice conversion). This can include raw audio signal processing in complex scenarios. An excellent introduction to audio signal processing and speech recognition can be found at https://towardsdatascience.com/a-step-by-step-guide-to-speech-recognition-and-audio-signal-processing-in-python-136e37236c24.
Anonymizing video data is more complex since it combines anonymization techniques for both images (frames) and audio. Video editing software can be used, but this will not scale easily.
To anonymize video at scale, you can use a commercial solution or the open source anonymization API offered by BMW’s Innovation Lab. This can be hosted using a Docker container and employs DL to apply anonymization at scale to images, audio, and video. You can find out more about this open source API at https://github.com/BMW-InnovationLab/BMW-Anonymization-API?referral=top-free-anonymization-tools-apis-and-open-source-models.
Note
Using a third-party solution should always entail careful due diligence and evaluation to avoid supply-chain risks.
This concludes our exploration of data anonymization, which can offer protection against privacy attacks. Anonymization changes data samples and can affect their utility. In the next subsection, we will explore differential privacy, which attempts to add privacy guarantees without significantly affecting the model’s output.
Differential privacy (DP)
Section titled “Differential privacy (DP)”DP is a strong approach to protecting data privacy with a specific objective; that is, it requires that the result of a query or an algorithm on a dataset be insensitive to removing or adding any single record in the dataset. Using aggregates of individual data points and adding noise to outputs to avoid personal identification is at the core of DP.
As a result, it protects against leaking information about individual records, such as the training data that goes into an ML model. DP can be applied to various stages of ML, such as data preprocessing, model training, and prediction serving.
DP relies on strong mathematical foundations to make it virtually impossible for an attacker to infer any individual’s data from the output. This makes it the gold standard in privacy but also hard to adopt. For a thorough treatment of DP, please see the extensive paper How to DP-fy ML: A Practical Guide to Machine Learning with Differential Privacy, published by Google Research in 2023, which can be found at: https://arxiv.org/abs/2303.00654.
From a practical point of view, DP involves using framework support to add noise (perturbations) at three different levels:
- Input perturbation is where random noise is added to the input data as part of data collection or preprocessing. Unlike data anonymization, we don’t just empirically try to balance anonymization and data utility. Instead, the frameworks help us identify the right degree of noise.
- Objective perturbation adds noise to the optimization of the objective function. DP=SGD is a popular training algorithm that adds noise to the gradients during stochastic descent. The algorithm calibrates the noise variance using data sampling.
- Output perturbation relies on adding noise to the model’s output sampled from the Laplace or Gaussian distribution. The aim is to make data produced by the model resistant to inference and linkage attacks. Unlike anonymization, DP frameworks help us calibrate the noise variance to the sensitivity of the query (model-specific prediction, classification, and so on).
DP is supported by various frameworks, including the following:
- Google’s TensorFlow Privacy: An extension of TensorFlow that provides tools to apply DP in deep learning (https://github.com/tensorflow/privacy).
- IBM’s Differential Privacy Library: Offers tools for incorporating DP into data analytics (https://github.com/IBM/differential-privacy-library).
- OpenDP: Harvard’s Privacy Tools Project initiative provides an open source library for differential privacy (https://github.com/opendp/opendp). This is also supported and used by Microsoft, which has published an article on how it is used in its products at https://blogs.microsoft.com/ai-for-business/differential-privacy/.
Here is an example of using TF privacy with Keras and introducing DP with objective perturbation to a CNN trained against CIFAR-10, similar to our IMRecS application.
We need to install TensorFlow privacy using the following:
pip install tensorflow-privacyWe then use our usual approach to model training but with a different DP-SGD optimizer. The first code block will be familiar to you. It is the standard code to build a simple Keras Model for CIFAR-10 but we have added the TF privacy library imports:
import tensorflow as tffrom tensorflow.keras.datasets import cifar10from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropoutfrom tensorflow_privacy.privacy.optimizers.dp_optimizer_keras import DPKerasSGDOptimizer# Load CIFAR-10 data(x_train, y_train), (x_test, y_test) = cifar10.load_data()# Preprocess datax_train, x_test = x_train / 255.0, x_test / 255.0# Build CNN modelmodel = Sequential([ Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)), MaxPooling2D(2, 2), Conv2D(64, (3, 3), activation='relu'), MaxPooling2D(2, 2), Flatten(), Dense(64, activation='relu'), Dense(10, activation='softmax')])DP-SPG in TensorFlow consists of first clipping gradients and then adding random noise.
Clipping gradients is done so that by limiting the effect of individual data points on the gradient, we limit individual correlations. The added noise helps make it statistically impossible to know whether a data item was included during model training.
We define the noise we will use for our DP implementation in addition to the standard model training hyperparameters. We use gradient clipping with the l2_norm_clip parameter to clip each gradient during training:
# Differential Privacy parametersnoise_multiplier = 1.1l2_norm_clip = 1.0batch_size = 250learning_rate = 0.01A new type of optimizer – DPKerasSDGoptimizer – incorporates this hyperparameter and seamlessly provides differential privacy to our model:
# Compile the model using DPKerasSGDOptimizeroptimizer = DPKerasSGDOptimizer( l2_norm_clip=l2_norm_clip, noise_multiplier=noise_multiplier, num_microbatches=1, learning_rate=learning_rate)model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy'])# Train the modelmodel.fit(x_train, y_train, epochs=10, batch_size=batch_size, validation_data=(x_test, y_test))Differential privacy offers strong guarantees but requires careful design and implementation with a deep understanding of data associations. It will also require fine-tuning of hyperparameters and model architecture to deal with the loss of accuracy due to the added noise. The preceding sample is to get you started and will produce low accuracy. You will need to fine-tune it to get better accuracy, an exercise left to you, the reader.
The next section will look at a different approach to preserving privacy by separating training datasets and restricting access to different models.
Federated learning (FL)
Section titled “Federated learning (FL)”Google introduced FL in 2016 in response to the increasing concerns about the misuse of personal data. Since then, it has emerged as a standard approach to processing data at source and reducing its exposure, thus protecting its privacy and confidentiality.
The approach utilizes a shared pre-trained foundation model. Collaborating parties download and train the shared model using their own private data and utilize encryption to secure the new model and upload it to the central location. This includes only the trained model or the weights. The split of training data minimizes data exposure and allows regulatory compliance. The following diagram illustrates a typical federated learning configuration:

Figure 10.7 – Typical federated learning system
TensorFlow has introduced some support for FL, and you can find an example of implementing FL with the MNIST dataset using Keras at https://www.tensorflow.org/federated/tutorials/federated_learning_for_image_classification.
More recent research has introduced BrainTorrent, a peer-to-peer federated approach inspired by BitTorrent. You can find out more about BrainTorrent at https://deepai.org/publication/braintorrent-a-peer-to-peer-environment-for-decentralized-federated-learning.
FL adds complexity and has its own risks in securing access control. Its sweet spot is using it across large organizations and data centers to train models while protecting their respective data collaboratively.
FL-related adversarial AI attacks attempt to exploit reliance on third-party data and shared gradients to stage poisoning, inversion, and inference attacks. A review of these attacks can be found in the 2020 work Threats to Federated Learning by Lingjuan Lyu, Han Yu, Jun Zhao and Qiang Yang at https://link.springer.com/chapter/10.1007/978-3-030-63076-8_1.
Split learning
Section titled “Split learning”Split learning is a different and more novel approach in the distributed machine learning domain.
This approach offers a unique way to handle privacy concerns. Unlike FL, where model training happens locally on each device, and only model parameters are shared, split learning splits the neural network. The network is divided between the client and the server: the client processes data up to a specific layer (the cut layer), and only the outputs at this layer are sent to the server, which completes the remaining computation.
This method ensures that raw data never leaves the client’s side, enhancing privacy.
Additionally, split learning is beneficial in scenarios where clients have limited computational resources, as the server performs the bulk of the computation.
However, it requires a more consistent connection between client and server than FL.
Split learning is less adopted compared to FL but emerges as an effective alternative, especially when data privacy is paramount and computational resources are unevenly distributed. It inherits the security risks we highlighted in FL because of its distributed nature. Furthermore, researchers have demonstrated successful adversarial AI attacks, including model extraction, inversion, and inference attacks. You can find this research at https://arxiv.org/abs/2108.09033, which contains the UnSplit: Data-Oblivious Model Inversion, Model Stealing, and Label Inference Attacks Against Split Learning, published in 2021 by Ege Erdogan, Alptekin Kupcu, and A. Ercument Cicek. The researchers also published their code in their GitHub repository at https://github.com/ege-erdogan/unsplit.
Split learning can protect data privacy in complex distributed setups but has its complexity and risks and should be used only after careful consideration. A thorough discussion of split learning and the splitNN architecture can be found in the 2018 paper Split learning for health: Distributed deep learning without sharing raw patient data by Praneeth Vepakomma, O. Gupta, Tristan Swedish, R. Raskar and can be found at https://arxiv.org/abs/1812.00564.
Both federated and split learning use forms of distributed model development to safeguard data. In the next section, we will see how encryption can be used to support privacy-preserving ML.
Advanced encryption options for privacy-preserving ML
Section titled “Advanced encryption options for privacy-preserving ML”We discussed data encryption in Chapter 3 as a security control to protect data confidentiality for data in transit and at rest.
A more advanced approach to using cryptography is to apply encryption to machine learning processes to protect data confidentiality and privacy.
Secure multi-party computation (secure MPC)
Section titled “Secure multi-party computation (secure MPC)”Secure MPC is a cryptographic method allowing multiple parties to jointly compute a function without revealing their individual inputs. Here’s how it works:
- Data splitting with cryptography: Each participant’s data is divided into encrypted shares using cryptographic algorithms. These shares conceal any meaningful information.
- Distributed cryptographic computation: Parties perform computations on their encrypted shares and exchange encrypted intermediate results. Advanced cryptographic methods ensure that these computations and exchanges do not compromise the original data’s confidentiality.
- Cryptographic result aggregation: Like a trained model, the final outcome is securely reconstructed from the encrypted computations. Cryptography ensures that the aggregation process does not expose individual participants’ data.
Secure MPC can be used for a variety of applications, not just ML and AI. This includes join data handling without revealing the raw data, such as joint data analytics, aggregating and tallying vote results in election systems, joint data research, and supply-chain management where the supplier is not cleared to access raw data.
In ML, MPC can be used when training models on a combined dataset while keeping each party’s data confidential. A good example how secure MPC functions have been used in a real-world scenario can be found in a 2020 detailed study of the use of the approach in genomic research, titled Privacy-preserving collaborative machine learning on genomic data using TensorFlow and published in 2020 by Hong, Cheng, et al., available at https://arxiv.org/abs/2002.04344.
Secure MPC was applied to train models capable of classifying healthy and diseased individuals based on their genomic data. This training involved multiple data owners, such as hospitals and universities, who collaboratively trained the model using their private datasets. The use of MPC allowed these parties to benefit from a larger combined dataset, leading to more robust and accurate models while ensuring that no party could access the raw data of others, thereby maintaining strict data privacy. Here is how the main secure MPC functions were applied:
- Data splitting with cryptography: In the context of genomic research, each participant’s genomic data is divided into encrypted shares using cryptographic algorithms. This ensures that the data split retains no meaningful information when viewed individually, maintaining the confidentiality of sensitive genetic information. Each share alone cannot reveal the participant’s genetic makeup or health information, which is crucial for maintaining privacy in highly sensitive areas such as genomic research where data leakage could have significant personal and ethical consequences.
- Distributed cryptographic computation: The participants, such as research institutions or healthcare providers, perform computations on their encrypted shares. These computations include advanced genetic modeling and analysis, such as risk prediction models for diseases or personalized medicine applications. The intermediate results of these computations are exchanged between parties in an encrypted form. The use of advanced cryptographic methods, such as the ABY3 protocol highlighted in the paper, ensures that these intermediate computations do not compromise the original data’s confidentiality. This method allows multiple stakeholders to collaborate on genetic studies without direct access to each other’s datasets, overcoming significant privacy hurdles.
- Cryptographic result aggregation: After computations, the results are aggregated to produce a final outcome, such as a trained model or a statistical analysis report. This aggregation is done in such a way that it only reveals the necessary information (e.g., using model parameters that do not expose any individual data). The cryptographic protocols ensure that the aggregation process does not expose sensitive individual data, adhering to privacy regulations and ethical standards. The final models or reports can be used for further scientific research or clinical applications without revealing any participant’s specific data.
Secure MPC is crucial when data cannot be pooled due to privacy concerns or regulations and can complement both federated and split learning in securing the exchange of gradients and other model information. However, MPC comes with challenges and risks:
- Computational overhead: MPC protocols can be computationally intensive, potentially slowing the learning process.
- Communication costs: The need for constant communication between parties during computation can be bandwidth-intensive.
- Complexity in implementation: Setting up MPC protocols requires careful cryptographic design to avoid vulnerabilities.
- Scalability issues: Scaling MPC to large numbers of participants or large datasets can be challenging.
Despite these challenges, MPC offers a powerful tool for privacy-preserving distributed learning, especially in scenarios where data cannot be shared or revealed.
Homomorphic encryption
Section titled “Homomorphic encryption”Homomorphic encryption (HE) is a form of encryption that allows computations on encrypted data, yielding encrypted results that, when decrypted, match the outcomes of operations performed on the original plaintext. As a result, it eliminates the need to expose keys for decryption and all the associated risks.
Here’s how it works in the context of ML training and inference:
- Data encryption: Input data for ML training or inference is encrypted using HE techniques. This encrypted data can be safely transmitted or stored.
- Performing encrypted computations: ML algorithms perform computations directly on encrypted data. This can include training steps or inference calculations, depending on the application.
- Decryption of results: The outcome of these computations, still in encrypted form, can be safely transmitted back to the owner of the private key, who can then decrypt it to get the actual result.
HE’s relationship with secure MPC is complementary. While secure MPC involves multiple parties jointly computing on divided data shares, HE allows computations on encrypted data by a single party. HE is instrumental in scenarios where secure MPC is not feasible due to high communication overheads or the need for continuous interaction among participants.
The risks and limitations of HE are as follows:
- Computational intensity: HE can significantly increase the computational load, slowing ML training and inference processes
- Complexity: Implementing HE requires specialized knowledge in cryptography
- Limited operations: Some HE forms support only a limited set of operations, which can be a constraint for complex ML models
- Data size and bandwidth: Encrypted data is typically larger in size than plaintext, potentially impacting storage and transmission efficiency
Despite these challenges, HE remains a promising tool for privacy-preserving ML, especially where data confidentiality is paramount.
Microsoft Simple Encrypted Arithmetic Library (SEAL) is an open source cryptographic library that enables homomorphic encryption, allowing computations to be performed on encrypted data. SEAL can be used to ensure data privacy during ML training and inference. Using homomorphic encryption, ML models can be trained and queried without exposing the raw data, making it particularly useful in scenarios where data confidentiality is crucial. The library is written in C++ and has examples of its use in mobile clients and.NET applications.
You can find more information on Microsoft SEAL at https://www.microsoft.com/en-us/research/project/microsoft-seal/.
In the next section, we will explore using tf-encrypt to demonstrate advanced ML encryption techniques in ML, including secure MPC and HE.
Advanced ML encryption techniques in practice
Section titled “Advanced ML encryption techniques in practice”In addition to SEAL, other libraries support advanced encryption and privacy-preserving techniques. This includes OpenMined PySyft, which supports encrypted computation, FL, and DP. You can find more about PySyft at https://github.com/OpenMined/PySyft.
Additionally, tf-encrypted is a framework for encrypted deep learning in TensorFlow 2.x. The genomic study we discussed earlier uses tf-secure. The focus of tf-encrypted is on secure MPC and encrypting gradients and parameters so that they can safely collaborate without revealing input data.
The following is an example of using tf-encrypted with Keras to implement secure computation by encrypting the gradients and other model parameters in a Keras DNN. The example is taken from the tf-encrypted home page at https://tf-encrypted.io/, using network building blocks from tf-encrypted:
import tensorflow as tfimport tf_encrypted as tfe@tfe.local_computation('prediction-client')def provide_input(): # normal TensorFlow operations can be run locally # as part of defining a private input, in this # case on the machine of the input provider return tf.ones(shape=(5, 10))x = provide_input()model = tfe.keras.Sequential([ tfe.keras.layers.Dense(512, batch_input_shape=x.shape), tfe.keras.layers.Activation('relu'), tfe.keras.layers.Dense(10),])# get prediction input from the clientlogits = model(x)with tfe.Session() as sess: result = sess.run(logits.reveal())Note that with tf-secure, we can convert a Keras model into a secure tf-encrypted version as follows:
with tfe.protocol.SecureNN(): tfe_model = tfe.keras.models.clone_model(model)The operation first establishes a secure computational context and uses it to wrap the Keras model. Within that context, tf-secured clones the original model with a TFE version that effectively encrypts all model parameters and gradients. As a result, all subsequent operations on the model’s data – training, inference, and internal data calculations – are performed encrypted.
This can be very useful when implementing secure MPC with TFE because it allows the joint computation of results without ever leaking model or input information.
In addition to encrypted models, the framework hosts encrypted serving. Implementing secure MPC with tf-encrypt involves the following:
- Launch servers to handle the encrypted serving. These are placeholder processes with
players = OrderedDict([('server0', 'localhost:4000'),('server1', 'localhost:4001'),('server2', 'localhost:4002'),])for player_name in players.keys():print("python -m tf_encrypted.player --config ./tfe.config {}".format(player_name))
- Configure the environment and a
config = tfe.RemoteConfig(players)config.save('./tfe.config')config.connect_servers()tfe.set_config(config)tfe.set_protocol(tfe.protocol.SecureNN())
- Create a queue for the requests using the converted Keras model. This will use the shared model the three
q_input_shape = (1, 28, 28, 1)q_output_shape = (1, 10)server = tfe.serving.QueueServer(input_shape=q_input_shape, output_shape=q_output_shape, computation_fn=tfe_model)
- Push the model to
request_ix = 1def step_fn():global request_ixprint("Served encrypted prediction {i} to client.".format(i=request_ix))request_ix += 1server.run(num_steps=3, step_fn=step_fn)
This has created a distributed serving model that uses secure MPC to serve client prediction requests.
You can find many examples, including integration with PySyft, under https://github.com/tf-encrypted/tf-encrypted/tree/master/examples.
tf-secure does not natively offer HE. This is because of the sets of concerns. The framework focuses on secure multi-party computations including encryption, secure computational contexts, and communication. To achieve that, it employs its own cryptography to optimize performance and confidentiality. HE on the other hand is about eliminating the need to decrypt encrypted data to perform operations on it. It is computationally heavy and could impose prohibitively high overheads on an MPC.
Nevertheless, as HE matures, this could become an interesting option. Another library, tf-seal, offers a SEAL bridge to tf-secure.
You can find more about tf-seal bridge and an example at https://medium.com/dropoutlabs/bridging-microsoft-seal-into-tensorflow-b04cc2761ad4. The project’s repository can be found at https://github.com/tf-encrypted/tf-seal.
This concludes our journey through the various approaches to ensure privacy-preserving ML. The following section will discuss a strategy to help us select and combine techniques to protect privacy.
Applying privacy-preserving ML techniques
Section titled “Applying privacy-preserving ML techniques”We have covered many approaches to help us protect data privacy. None of these is a silver bullet. How we apply them will depend on the context of the application, and requires a balancing act between privacy and data utility and a multi-layered defense-in-depth approach:
- Risk and use case assessment: Understanding the specific risks in a given use case, including data governance and compliance requirements, is essential in choosing techniques such as anonymization on sensitive data, how we use them, and where we apply them.
- Threat modeling: Identifying potential threats helps us understand these risks better. This is essential in evaluating privacy attacks that rely on unforeseen data linkage.
- Data minimization. Reducing the amount of sensitive data used minimizes the attack surface and risk. Using DP is an essential tool to help minimize data linking.
- Balancing data utility: Ensuring data remains useful for its purpose while staying secure is essential. This requires iterations of evaluating the threat model and threat mitigations to find the right balance.
- Defense in depth: Applying anonymization does not eliminate the risks of distributed computing or access to the master data used for anonymization. Based on the threat model, we should apply multiple layers of defense, including additional access control and data protection, but we should also evaluate secure MLP for distributed learning.
Summary
Section titled “Summary”In this chapter, we covered privacy-preserving AI and the various techniques it encompasses to help us reduce the risk of exposing sensitive data to systems and attackers.
We discussed and explored a variety of techniques including data anonymization, differential privacy, distributed model training techniques such as federated and split learning, and encryption techniques such as secure multi-party computation and homomorphic encryption.
All these are part of a defense-in-depth approach to protecting sensitive data and staying compliant with privacy legislation such as the GDPR.
This completes our discussion of adversarial AI for predictive AI. In the next chapter, we will start exploring adversarial AI in generative AI.