Skip to content
ImagineWorld

Getting Started with AI

node_idnode-book_adversarial-ai-defense-strategies_chapter-01-getting-started-with-ai
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num1
chapter_titleGetting Started with AI
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In this increasingly digital age, cybersecurity has never been more critical. However, the meteoric rise of artificial intelligence (AI) and machine learning (ML) challenges cybersecurity with new technologies and concepts. Adversarial AI allows attackers to use advanced techniques to attack AI. This chapter introduces essential concepts of AI and ML that are aimed at cybersecurity and other technical professionals with little or no experience in AI.

By the end of this chapter, you will have a firm grasp of critical concepts such as models, training, validation, testing, inference, and various types of ML. We will cover popular algorithms that are used in ML, what deep learning is, and understand the roles and functions of popular neural networks such as convolutional neural networks (CNNs), recurrent neural networks (RNNs), and large language models (LLMs) such as Bidirectional Encoder Representations from Transformers (BERT) and ChatGPT.

You will also learn about Python, the preferred language for ML, and popular frameworks such as PyTorch, Keras, and TensorFlow.

The knowledge and skills you’ll gain in this chapter will help lay the foundation for understanding the security threats of adversarial AI and how to defend against adversarial attacks on AI systems.

In this chapter, we are going to cover the following main topics:

  • Understanding AI and ML
  • Types of ML and the ML life cycle
  • Key algorithms in ML
  • Neural networks and deep learning
  • ML development tools

Let’s get started and set the foundations for our journey through the new challenges of Adversarial AI for cybersecurity.

AI and ML are often used interchangeably. Let’s try to provide some simple definitions and examples to understand their relationship and how they fit into our work of defending AI from adversarial attacks.

AI is a field in computer science that involves techniques and approaches to creating intelligent machines and applications that can perform tasks with intelligence normally associated with humans. These tasks include understanding natural language and images, recognizing patterns, solving problems, and making decisions.

AI is integrated with applications and systems. In everyday life, we use AI for things such as predictive texting, email spam filters, and recommendations. With its constant progress, AI can be found in smart homes in Internet of Things (IoT) devices such as security cameras, doorbells, vacuum cleaners, and digital assistants such as Siri or Alexa. Autonomous cars and smart medical devices are other examples of using AI to create more intelligent machines.

More advanced AI systems tend to be more autonomous and general-purpose solutions. Autonomous systems are capable of achieving their goal within a defined scope without human intervention and are capable of adapting to operational and environmental conditions. These include robots, some of which are humanoid, such as Grace, a humanoid nurse robot in Hong Kong, and Ai-Da, the first humanoid robot to become a painter (read more here: https://www.theguardian.com/technology/2022/apr/04/mind-blowing-ai-da-becomes-first-robot-to-paint-like-an-artist) and give evidence in UK Parliament (read more here: https://www.euronews.com/next/2022/10/12/ai-da-makes-history-after-becoming-the-first-robot-to-be-grilled-by-uks-house-of-lords). Most are experimental, but Boston Dynamics has some staggering examples of industrial-grade AI robots. The recent explosion of ChatGPT and Generative AI is creating more autonomous chatbots in various fields, including software development (read more here: https://github.com/features/copilot) and experimental medical diagnosis (read more here: https://www.scientificamerican.com/article/ai-chatbots-can-diagnose-medical-conditions-at-home-how-good-are-they/).

These newer autonomous systems signify a departure of AI from problem-specific AI solutions to a more generalized AI known as artificial general intelligence (AGI). AGI is still in its early stages and has raised many ethical questions and public debate.

In almost all these AI solutions, ML is the heart – or rather, the brain – of AI, giving AI solutions their intelligence. Some AI solutions use other technologies, such as expert rules, but ML is the main technology that AI uses for its intelligence.

ML has a radically new approach to building analytical models, allowing programs to learn from and make decisions or predictions based on data. How model parameters are adjusted is ruled by the ML algorithm we use. This allows us to model and solve complex problems that traditional systems struggle to do.

It is the ML models and this adaptive process that enable AI systems to perform tasks without being explicitly programmed to do so. Their adaptive nature helps ML systems learn from data and evolve without changing the application logic. As a result, this increases the attack vector, and ML models become the main target of adversarial attacks.

We will look into algorithms and how models learn and use them in more detail.

Depending on how models learn, ML can be classified into three types:

  • Supervised learning, where each data sample must have a label indicating the correct outcome. The model learns from labeled structured data, such as CSV files, by adjusting its internal parameters based on its error when it guesses the result. Supervised learning is by far the most used type of learning in classification images, voice and language recognition, numerical forecasting, and more.
  • Unsupervised learning, on the other hand, involves training on data, usually unstructured, without labels. Unsupervised learning uses clustering and other techniques to understand the underlying structure of data, identify patterns, and perform anomaly detection, fraud detection, social network analysis, market segmentation, and supervised learning.
  • Reinforcement learning relies on an agent to behave in an environment and learn by performing certain actions, observing the results/rewards, and adjusting accordingly. It has been used to play complex games such as Chase and Go (where it defeated the world champion). It is also used in autonomous vehicles, robotics, and financial trading.

Now, let’s consider some key concepts and how ML is used by delving into the process it follows. Google has introduced seven steps of ML that have become popular among data scientists and newcomers.

You can watch the Google video at https://www.youtube.com/watch?v=nKW8Ndu7Mjw.

We will simplify them so that we’re not using specialized terminology and use them to highlight key concepts based on a more detailed discussion that can be found at the preceding link. ML typically involves the following steps:

  1. Data collection: The initial step is to gather relevant data that we will use for training and testing and capture the domain we will be modeling. This data can be of various forms – images, emails, medical records, social media posts, and so on – and is dictated by what we want the model to learn. The process could be manual or employ crawlers, software that automates data extraction.
  2. Data pre-processing: The collected data is then pre-processed, which may involve handling missing values, removing outliers, or encoding categorical variables. This is also known as data wrangling in the data science field. In this step, a key concern is that the data should be representative and not skewed. This stage also ensures that the data is in a form that the ML algorithm can process. Bear in mind that models can only accept vectors (that is, arrays) of numerical data. As a result, we use encoding for text, images, categorical values, and so on.
  3. Algorithm selection: This will depend on the type of problem and amount of data we have. We will discuss algorithms in the next section, Key algorithms in ML.
  4. Model training: We split pre-processed data into training and testing sets. The training set, which makes up most of the data, is used to train the model. Often, we reserve some samples from the training set as the validation set, which we use to test during training. This is to reserve test data in our model evaluation. In supervised learning, the ML algorithm makes predictions on the training data. The learning algorithm gradually adjusts the model’s internal parameters to minimize the difference between its predictions and the actual values; this is known as error minimization or loss minimization. In the case of unsupervised learning, the algorithm is provided with inputs but not the desired outputs. It identifies patterns and structures in the input data, which are often used for clustering or anomaly detection tasks.
  5. Model testing and evaluation: After training, the model is tested with the testing set, which contains data it has not encountered before. This phase evaluates the model’s performance, assessing how well it can generalize its learning to new data. Models that memorize their training data perform (generalize) poorly and overfit data. Some key concepts that you will encounter are inference, which involves asking the model to make a decision based on a sample; bias, which is the model’s tendency to consistently learn the wrong thing by not taking into account all the information in the data (underfitting); and variance, which is the model’s ability to memorize small fluctuations in the training set (overfitting), making the model perform poorly on unseen data. These concepts are discussed in detail at https://www.datasciencecentral.com/data-science-simplified-key-concepts-of-statistical-learning/.
  6. Model optimization: If the model’s performance on the testing data is unsatisfactory, further adjustments may be needed. This can involve fine-tuning the model’s hyperparameters – adjustable parameters not affected by training, such as batches of data – or collecting more data to retrain the model.
  7. Deployment and updating: Once the model reaches satisfactory performance levels, we need to deploy it to solve real-world problems. The deployment will most likely be done via a REST API to respond. This is often called an inference endpoint. Importantly, ML models typically need continuous monitoring and updating, even after deployment. As new data becomes available, we can retrain and update our models, enabling them to refine their predictive abilities over time.

You may also find references to the DM-CRISP model, which offers a higher-level view of the process. You can find more details about the model at https://www.datascience-pm.com/crisp-dm-2/.

Cybersecurity professionals must understand both viewpoints and articulate risks and defenses in different audiences and contexts. It will be helpful to keep both in mind. The following diagram relates the Google-based life cycle steps to the DM-CRISP model:

Figure 1.1 – DM-CRISP and Google’s ML life cycle steps

Figure 1.4 – DM-CRISP and Google’s ML life cycle steps

Finally, while development takes place in data science environments, machine learning operations (MLOps) involves adapting DevOps and data engineering to streamline and automate the ML life cycle.

In this section, we covered general ML concepts such as ML types and the life cycle of ML, including two different life cycle viewpoints. These concepts and steps help us develop AI applications and rely on ML algorithms, which bring real intelligence into ML. We will review some key algorithms in the next section.

Several algorithms in ML have pros and cons and suit different use cases.

In supervised learning, we have the following:

  • Linear regression, which predicts a continuous output variable based on input features. It’s used in economics for forecasting and in healthcare for predicting disease progression.
  • Logistic regression, which, despite its name, is an algorithm for binary classification problems and estimates the probability an instance belongs to a class. It’s used in credit scoring and medical testing.
  • Decision tree, which learns simple decision rules inferred from data features. It’s useful in business decision-making and customer segmentation.
  • Random forest, which uses multiple decision trees to prevent overfitting. This makes it an ensemble algorithm and is used in predicting disease risk, loan defaulters, and customer preferences.
  • Support vector machine (SVM), which can model complex decision boundaries and separate them. SVM is used in bioinformatics, image recognition, and handwriting recognition for both regression and classification.

In unsupervised learning, we have the following:

  • K-means clustering, a popular algorithm that uses feature similarity to find groups in data. It’s commonly used in market and image segmentation.
  • Principal component analysis (PCA), which reduces the number of input variables while retaining as much of the critical information as possible. You will often find the term dimensionality reduction used in PCA because input variables or features define dimensions.

In reinforcement learning, we have Q-learning, a reinforcement learning algorithm where an agent learns to perform actions to maximize the cumulative reward it receives in a particular environment. Deep Q networks is an extension that uses neural networks.

Finally, neural networks are a family of algorithms that can use supervised, unsupervised, or reinforcement learning. They have revolutionized ML as part of deep learning. We will discuss both in the next section.

Inspired by human brain biology, artificial neural networks (ANNs) are good at processing unstructured data such as images, audio, and text and are widely used in image recognition, speech recognition, and natural language processing (NLP). These are their fundamental blocks:

  • Neurons and layers: ANNs apply parallel processing by using nodes called neurons. Each node has a weight and a bias, both of which are used to produce their output based on outputs. Neurons are organized in layers, and typically, there is an initial input and final output layer, and layers in between called hidden layers where the actual computation takes place. Inputs to each layer are derived from the outputs of the previous layer.
  • Training and weights update: Training an ANN involves adjusting the weights and biases of neurons based on error. This consists of a process called backpropagation and an optimization method, such as batch gradient descent and/or stochastic gradient descent (SGD); backpropagation calculates gradients of the loss or error concerning weights for the specific inputs and iterates using the optimization technique to update the weights and iterate to reduce the error. This has proven to be a very effective way to approximate a model. Similarly, SGD iteratively updates the weights based on a subset (or a single instance) of the training data, which minimizes the loss function more efficiently than the alternative traditional batch gradient descent, which updates the weights using the entire training dataset.
  • Deep learning is a term denoting the use of multiple hidden layers to enable ANNs to learn more complex features. For instance, in image recognition, while the initial layers may only learn local edge patterns, deeper layers can combine these edges to learn larger patterns, and even deeper layers may identify whole objects. The ability to learn from raw, unstructured data differentiates deep learning from traditional ML techniques.

These complex architectures need large datasets so that they can be exposed to a wide range of samples and avoid memorizing (overfitting) the data, which becomes easier as more and more neurons are added (often in the millions).

Similarly, these large-scale parallel architectures require significant computation power to perform their calculations in one step. Their operations are matrix calculations, and graphical processing units (GPUs) are well suited to their parallel execution. As a result, GPUs have been game changers in ML, with NVIDIA cards and their Compute Unified Device Architecture (CUDA) parallel computing API becoming a standard in accelerating the time we need to develop deep neural networks.

There are many different neural network architectures. Here are some key ones that we will encounter in our Adversarial AI journey:

  • CNNs: Mainly used in image processing, models such as AlexNet, VGG, and ResNet have achieved top performance in the ImageNet competition.
  • RNNs: Widely used in language modeling and speech recognition. Long short-term memory (LSTM) is a popular type of RNN that helps mitigate the vanishing gradient problem of squashed inputs in traditional RNNs and slows down or stops training.
  • Transformers (BERT, GPT): BERT has been a go-to model for various NLP tasks, such as question-answering and sentiment analysis, as it considers the context from both the left and right of a word. GPT-3.5 and GTP-4, the latest models in the GPT series, have shown remarkable performance in generating human-like text. Both are examples of LLMs. Unlike BERT, GPT is unidirectional, using an autoregressive approach to predict each word in a sentence based on the words that came before it. This makes it remarkably effective in generating coherent and contextually relevant text.

LLMs tend to be massive and are part of Generative AI, a broader genre of AI that’s designed to generate content, including images, music, and text. Other examples of Generative AI include generative adversarial networks (GANs), which are famous for their use in deepfake technology. We also have variational autoencoders (VAEs), which have been used to create new molecules for drugs or new faces from other images. Existing ANNs, such as RNNs, have also been used for Generative AI. OpenAI’s MuseNet, for example, uses an RNN to create music and combine styles from Mozart to the Beatles.

We can develop ML models in many languages, ranging from Python, R, C++, Java, and Julia to scientific tools such as proprietary MATLAB and open source Octave. Python is by far the most widely used language in academia, the scientific community, and industry. This makes it a near de facto standard for mainstream ML development. We will be using Python throughout this book.

Python’s simplicity and readability contribute to its popularity, but what sets it apart is the rich ecosystem of scientific and data analysis libraries. NumPy for numeric computing, pandas for data analysis, and Matplotlib for charting are three libraries that are widely used in ML work.

These are available as standard Python packages. The default packager in Python is pip, and you can find and install packages from package repositories, such as the Python Package Index (PyPI). In some operating systems and environments, you may find pip as pip3.

Packages sometimes have other system-level dependencies. Conda is another popular package manager that handles both Python packages and their system-level dependencies. This can be useful for GPU-based acceleration with NVIDIA cards sitting on top of NVIDIA’s drivers and CUDA APIs.

To provide isolation and help use multiple versions of packages, Python offers virtual environments, with Python’s venv module being a built-in way to create environments in Python. Conda offers its own version of environment management.

ML frameworks offer the functionality to train, validate, test, and use models. The most popular are open source frameworks, available as Python packages, that can be installed via pip or conda. These include the following:

  • scikit-learn, a foundational and near-ubiquitous ML framework offering a wide range of algorithms for supervised and unsupervised learning. The framework supports all the algorithms we’ve covered, except neural networks. It offers auxiliary functions (such as splitting data) that are used with other frameworks.
  • TensorFlow, by Google Brain, offers comprehensive support for complex data and neural networks and a rich ecosystem of tools, libraries, and resources. It is a mature framework that dominates the deep learning area and allows both Pythonic eager execution and static graph computation.
  • PyTorch, by Facebook’s AI Research Lab, is a deep learning framework noted for its dynamic computational graph, being more Pythonic and having efficient parallelism and memory usage. It has been gaining popularity recently with a strong community movement.
  • Keras, a high-level neural network API running on top of TensorFlow, offers user-friendliness and the ability to work with complex neural networks.

We will use Keras throughout this book to take advantage of its user-friendliness and demonstrate Adversarial AI concepts and techniques to non-AI practitioners.

We can use all these packages in traditional Python programming and Jupyter Notebooks. Jupyter Notebooks are web-based and offer an interactive environment that integrates code, visuals, and text in one place. This makes them ideal for exploratory data analysis, prototyping ML models, and creating reproducible research documents, facilitating collaboration and knowledge transfer.

In this section, we discussed the tools we can use for ML, including various programming languages, frameworks, and libraries, and the popular Jupyter Notebooks environment that’s used by data scientists and ML engineers. In the next chapter, we will demonstrate how to use these tools by building a few examples of what have learned so far while using our Adversarial AI target service.

In this chapter, we set the foundations of AI for the rest of this book. We covered some important topics:

  • What AI is and its shift toward AGI.
  • How ML creates models adaptively by ingesting data and how it is the brain of AI. This makes it the focus of adversarial AI attacks and defenses.
  • The different types of ML based on how models learn – that is, supervised, unsupervised, and reinforcement learning.
  • The seven typical steps in the ML life cycle, which include data collection and pre-processing, selecting an algorithm based on the problem we are solving, model training, testing and evaluation, fine-tuning and optimization, and, finally, deploying and using the model.
  • Key ML algorithms and where they are used. This included linear and logistic regression, decision trees, and their ensemble version with random forests in supervised learning. We looked at K-means clustering and PCA, two popular unsupervised models, and Q-learning in reinforcement learning.
  • Neural networks, which are advanced ML algorithms that support supervised, unsupervised, and reinforcement learning. We discussed their layered architecture and how multiple layers achieve deep learning, something that has revolutionized ML.
  • Types of neural networks, such as CNNs, RNNs, and the more recent LLMs, such as BERT and ChatGPT. We highlighted LLMs as part of Generative AI, which includes other types of neural networks, such as GANs, which are involved in deepfakes.

Finally, we reviewed the development tools that are used in ML, emphasizing Python, the de facto language for ML, its package and environment options, and some popular packages, including ML frameworks such as TensorFlow, PyTorch, and Keras. We also highlighted the ubiquitous role of Jupyter Notebooks in ML development.

AI and ML are vast topics on their own. This chapter aimed to provide a basic understanding of what’s required to protect them from Adversarial AI. Many titles have been published that can help you dive in deeper, including the ones in the Further reading section at the end of this chapter.

In the next chapter, we will walk through setting up our environment and make sense of all the concepts we learned about in this chapter by developing and deploying a simple model.

To learn more about the topics that were covered in this chapter, take a look at the following resources:

  • Hands-On Data Preprocessing in Python, by Roy Jafari
  • Mastering Machine Learning Algorithms - Second Edition, by Giuseppe Bonaccorso
  • Deep Learning with TensorFlow 2 and Keras - Second Edition, by Antonio Gulli, Amita Kapoor, and Sujit Pal