AI Red teamer
Setup
Miniconda
Miniconda is a minimal installer for the Anaconda distribution of the Python programming language. It provides the conda package manager and a core Python environment without automatically installing the full suite of data science libraries available in Anaconda.
Init the project:
Finally, run these two commands to complete the init process:
After installing Miniconda, you'll notice that the base environment is activated by default every time you open a new terminal. This is indicated by the (base) prefix on your path.
To prevent the base environment from activating automatically, you can use the following command:
conda provides a simple way to create virtual environments. For example, to create a new environment named ai with Python 3.11, use the following command:
This will create a virtual environment, ai, which can then be used to contain all ai-related packages.
Activating the Environment:
To deactivate the environment, use:
Dependencies
Use the conda install command to install the following core packages:
Updates:
Install # JupyterLab
Make sure you are running the command from within your ai environment.
To start Jupyter:
JupyterLab's primary component is the notebook, which allows combining code, text, and visualizations in a single document. Notebooks are organized into cells, where each cell can contain either code or markdown text.
Code cells: Execute code in various languages (Python, R, Julia).Markdown cells: Create formatted text, equations, and images using markdown syntax.Raw cells: Untyped raw text.
Click the "Python 3" icon under the "Notebook" section in the Launcher interface to create a new notebook. This will open a notebook with a single empty code cell.
![[jupyter_001.png]]
![[jupyter_002.png]]
Type your Python code into the code cell and press Shift + Enter to execute it. For example:
The output of the code will appear below the cell.
JupyterLab integrates with libraries like pandas, matplotlib, and seaborn for data exploration and visualization. Here's an example of loading a dataset with pandas and creating a simple plot:
JupyterLab uses a kernel to run your code. The kernel is a separate process responsible for executing code and maintaining the state of your computations. Sometimes, you may need to reset your environment if it becomes cluttered with variables or you encounter unexpected behavior.
To restart the kernel:
- Open the
Kernelmenu in the top toolbar. - Select
Restart Kernelto reset the environment while preserving cell outputs, orRestart Kernel and Clear All Outputsto also remove all previously generated outputs from the notebook.
Python Libraries for AI
This section focuses on two prominent Python libraries for AI development: Scikit-learn and PyTorch.
Scikit-learn
Scikit-learn is a comprehensive library built on NumPy, SciPy, and Matplotlib. It offers a wide range of algorithms and tools for machine learning tasks and provides a consistent and intuitive API, making implementing various machine learning models easy.
Supervised Learning:Scikit-learnprovides a vast collection of supervised learning algorithms, including:Linear RegressionLogistic RegressionSupport Vector Machines (SVMs)Decision TreesNaive BayesEnsemble Methods(e.g., Random Forests, Gradient Boosting)
Unsupervised Learning:It also offers various unsupervised learning algorithms, such as:Clustering(K-Means, DBSCAN)Dimensionality Reduction(PCA, t-SNE)
Model Selection and Evaluation:Scikit-learnincludes tools for model selection, hyperparameter tuning, and performance evaluation, enabling developers to optimize their models effectively.Data Preprocessing:It provides functionalities for data preprocessing, including:- Feature scaling and normalization
- Handling missing values
- Encoding categorical variables
Scikit-learn provides various scaling techniques:
StandardScaler: Standardizes features by removing the mean and scaling to unit variance.MinMaxScaler: Scales features to a given range, typically between 0 and 1.RobustScaler: Scales features using statistics that are robust to outliers.
Scikit-learn offers encoding techniques:
OneHotEncoder: Creates binary (0 or 1) columns for each category.LabelEncoder: Assigns a unique integer to each category.
Real-world datasets often contain missing values. Scikit-learn provides methods to handle these missing values:
SimpleImputer: Replaces missing values with a specified strategy (e.g., mean, median, most frequent).KNNImputer: Imputes missing values using the k-Nearest Neighbors algorithm.
Scikit-learn offers tools for selecting the best model and evaluating its performance. Splitting data into training and testing sets is crucial to evaluating the model's generalization ability to unseen data.
Cross-validation provides a more robust evaluation by splitting the data into multiple folds and training/testing on different combinations.
Scikit-learn provides various metrics to evaluate model performance:
accuracy_score: For classification tasks.mean_squared_error: For regression tasks.precision_score,recall_score,f1_score: For classification tasks with imbalanced classes.
Model Training and Prediction: Scikit-learn follows a consistent API for training and predicting with different models. Create an instance of the desired model with appropriate hyperparameters.
Train the model using the fit() method with the training data.
Make predictions on new data using the predict() method.
PyTorch
PyTorch is an open-source machine learning library developed by Facebook's AI Research lab. It provides a flexible and powerful framework for building and deploying various types of machine learning models, including deep learning models.
Deep Learning:PyTorchexcels in deep learning, enabling the development of complex neural networks with multiple layers and architectures.Dynamic Computational Graphs:Unlike static computational graphs used in libraries like TensorFlow,PyTorchuses dynamic computational graphs, which allow for more flexible and intuitive model building and debugging.GPU Support:PyTorchsupports GPU acceleration, significantly speeding up the training process for computationally intensive models.TorchVision Integration:TorchVisionis a library integrated withPyTorchthat provides a user-friendly interface for image datasets, pre-trained models, and common image transformations.Automatic Differentiation:PyTorchusesautogradto automatically compute gradients, simplifying the process of backpropagation.Community and Ecosystem:PyTorchhas a large and active community, leading to a rich ecosystem of tools, libraries, and resources.
Tensors are multi-dimensional arrays that hold the data being processed. They can be constants, variables, or placeholders. PyTorch tensors are similar to NumPy arrays but can run on GPUs for faster computation.
PyTorch provides a flexible and intuitive interface for building and training deep learning models. The torch.nn module contains various layers and modules for constructing neural networks.
The Sequential API allows building models layer by layer, adding each layer sequentially.
The Module class provides more flexibility for building complex models with non-linear topologies, shared layers, and multiple inputs/outputs.
PyTorch provides tools for training and evaluating models.
Optimizers are algorithms that adjust the model's parameters during training to minimize the loss function. PyTorch offers various optimizers:
AdamSGD(Stochastic Gradient Descent)RMSprop
Loss Functions measure the difference between the model's predictions and the actual target values. PyTorch provides a variety of loss functions:
CrossEntropyLoss: For multi-class classification.BCEWithLogitsLoss: For binary classification.MSELoss: For regression.
The training loop updates the model's parameters based on the training data.
PyTorch provides the torch.utils.data.Dataset and DataLoader classes for handling data loading and preprocessing.
PyTorch allows models to be saved and loaded for inference or further training.
Datasets
Datasets are structured collections of data used for analysis and model training. They come in various forms, including:
Tabular Data: Data organized into tables with rows and columns, common in spreadsheets or databases.Image Data: Sets of images represented numerically as pixel arrays.Text Data: Unstructured data composed of sentences, paragraphs, or full documents.Time Series Data: Sequential data points collected over time, emphasizing temporal patterns.
The quality of a dataset is fundamental to the success of any data analysis or machine learning project. Here’s why:
Model Accuracy: High-quality datasets produce more accurate models. Poor-quality data—such as noisy, incomplete, or biased datasets—leads to reduced model performance.Generalization: Carefully curated datasets enable models to generalize effectively to unseen data. This minimizes overfitting and ensures consistent performance in real-world applications.Efficiency: Clean, well-prepared data reduces both training time and computational demands, streamlining the entire process.Reliability: Reliable datasets lead to trustworthy insights and decisions. In critical domains like healthcare or finance, data quality directly affects the dependability of results.
Preparing the dataset
We have a dataset named demo_dataset.csv
We first load it into a pandas DataFrame to begin working with the dataset. A pandas DataFrame is a flexible, two-dimensional labeled data structure that supports a variety of operations for data exploration and preprocessing.
In this code, pd.read_csv("./demo_dataset.csv") loads the downloaded CSV file into a DataFrame named data. From here, inspecting, manipulating, and preparing the dataset for further steps in the analysis pipeline becomes straightforward.
Viewing Sample Entries:
Inspecting Data Structure and Types
The info() method reveals the dataset's shape, column names, data types, and how many entries are present for each column, enabling early detection of columns with missing or unexpected data.
Checking for Missing Values:
This command returns the count of null values for each column, helping to prioritize which features need attention. Addressing these missing values may involve imputation, removal, or other cleaning strategies to ensure the dataset remains reliable and valid for further analysis.
![[jupyter_003.png]]
Data preprocessing transforms raw data into a suitable format for machine learning algorithms. Key techniques include:
Data Cleaning: Handling missing values, removing duplicates, and smoothing noisy data.Data Transformation: Normalizing, encoding, scaling, and reducing data.Data Integration: Merging and aggregating data from multiple sources.Data Formatting: Converting data types and reshaping data structures.
Checking for Invalid IP Addresses:
Checking for Invalid Port Numbers:
Checking for Invalid Protocol Values:
Checking for Invalid Bytes Transferred:
Checking for Invalid Threat Levels:
Strategy 1: Dropping Invalid Entries
The most straightforward approach is to discard the invalid entries entirely. This ensures that the remaining dataset is clean and free of potentially misleading information.
This method is generally preferred when data accuracy is paramount, and the loss of some data points does not significantly compromise the overall analysis. However, it may not always be feasible, especially if the dataset is small or the invalid entries constitute a substantial portion of the data.
After dropping the bad data from our dataset, we are only left with 77 clean entries.
Strategy 2: Imputing Missing Values
Imputing is the process of replacing missing or invalid values in a dataset with estimated values. This is crucial for maintaining the integrity and usability of the data, especially in machine learning and data analysis tasks where missing values can lead to biased or inaccurate results.
First, convert all invalid or corrupted entries, such as MISSING_IP, INVALID_IP, STRING_PORT, UNUSED_PORT, NON_NUMERIC, or ?, into NaN. This approach standardizes the representation of missing values, enabling uniform downstream imputation steps.
After this step, NaN represents all missing or invalid data points.
![[jupyter_004.png]]
For basic numeric columns like bytes_transferred, use simple methods such as the median or mean. For categorical columns like protocol, use the most frequent value.
Strategy 3: meaningful imputations
For more sophisticated scenarios, employ advanced techniques like KNNImputer or IterativeImputer. These methods consider relationships among features to produce contextually meaningful imputations.
After cleaning and imputations, apply domain knowledge. For source_ip values that remain missing, assign a default such as 0.0.0.0. Validate protocol values against known valid protocols. For ports, ensure values fall within the valid range 0-65535, and for protocols that imply certain ports, consider mode-based assignments or domain-specific mappings.
Perform final verification steps to confirm that distributions are reasonable and categorical sets remain valid. Adjust imputation strategies and transformations or remove problematic records if anomalies persist.
Data transformation
Encoding
Encoding converts categorical values into numeric form so machine learning algorithms can utilize these features. Depending on the situation, you can choose:
OneHotEncoderfor binary indicator features that represent each category separately.LabelEncoderfor integer codes, though this may imply unintended order.HashingEncoderor frequency-based methods to handle high-cardinality features and control feature space size.
One-Hot Encoding
This process creates a set of indicator columns that hold 1 or 0, indicating the presence or absence of a particular category in each row.
For example, consider the categorical feature
color, which can take on the valuesred,green, orblue. In a dataset, you might have rows wherecolorisredin one instance,greenin another, and so on. By applyingone-hot encoding, instead of keeping a single column with values likered,green, orblue, the encoding creates three new binary columns:
color_redcolor_greencolor_blueEach of these new columns corresponds to one of the original categories. If a row had
colorset tored, thecolor_redcolumn for that row would be1.
In this case, we are going to encode the protocol feature.
The original protocol feature is replaced with distinct binary columns, ensuring the model interprets each category independently.
Phising site
Downloading and extracting the Dataset
Loading the Dataset
After loading the dataset, it is important to inspect it for basic information, missing values, and duplicates. This helps ensure that the data is clean and ready for analysis.
Preprocessing the dataset
The steps outlined here rely on the nltk library for tasks such as tokenization, stop word removal, and stemming. Before processing any text, you must download the required NLTK data files. These include punkt for tokenization and stopwords for removing common words that do not contribute to meaning.
At this point, the messages are fully preprocessed. Each message is a cleaned, normalized string ready for vectorization and subsequent model training, ultimately improving the classifier’s performance.
Feature Extraction
Feature extraction transforms preprocessed SMS messages into numerical vectors suitable for machine learning algorithms. A common way to represent text numerically is through a bag-of-words model. CountVectorizer from the scikit-learn library efficiently implements the bag-of-words approach. It converts a collection of documents into a matrix of term counts, where each row represents a message and each column corresponds to a term (unigram or bigram). Before transformation, CountVectorizer applies tokenization, builds a vocabulary, and then maps each document to a numeric vector.
Key parameters for refining the feature set:
min_df=1: A term must appear in at least one document to be included. While this threshold is set to1here, higher values can be used in practice to exclude rare terms.max_df=0.9: Terms that appear in more than 90% of the documents are excluded, removing overly common words that provide limited differentiation.ngram_range=(1, 2): The feature matrix captures individual words and common word pairs by including unigrams and bigrams, potentially improving the model’s ability to detect spam patterns.
After this step, X becomes a numerical feature matrix ready to be fed into a classifier, such as Naive Bayes.
Training
After preprocessing the text data and extracting meaningful features, we train a machine-learning model for spam detection. We use the Multinomial Naive Bayes classifier. To streamline the entire process, we employ a Pipeline. A pipeline chains together the vectorization and modeling steps, ensuring that the same data transformation (in this case, CountVectorizer) is consistently applied before feeding the transformed data into the classifier.
With the pipeline in place, we can easily integrate hyperparameter tuning to improve model performance. The objective is to find optimal parameter values for the classifier, ensuring that the model generalizes well and avoids overfitting.
To achieve this, we use GridSearchCV. This method systematically searches through specified hyperparameter values to identify the configuration that produces the best performance. In the case of MultinomialNB, we focus on the alpha parameter, a smoothing factor that adjusts how the model handles unseen words and prevents probabilities from being zero. We can balance bias and variance by tuning alpha, ultimately improving the model’s robustness.
The combination of Pipeline and GridSearchCV ensures a clean, consistent workflow. First, CountVectorizer converts raw text into numeric features suitable for the classifier. Next, MultinomialNB applies its probabilistic principles to distinguish between spam and ham messages.
Finally, by evaluating alpha values and leveraging cross-validation, we reliably select the best configuration based on the F1-score, a balanced metric for precision and recall.
Other example
Preprocessing New Messages
Vectorizing the Processed Messages:
Making Predictions:
Displaying Predictions and Probabilities:
Using joblib for Saving Models
After confirming satisfactory performance, preserving the trained model to be reused later is often necessary. By saving the model to a file, users can avoid the computational expense of retraining it from scratch each time. This is especially helpful in production environments where quick predictions are required.
joblib is a Python library designed to efficiently serialize and deserialize Python objects, particularly those containing large arrays such as NumPy arrays or scikit-learn models. Serialization converts an in-memory object into a format that can be stored on disk or transmitted across networks. Deserialization involves converting the stored representation back into an in-memory object with the exact same state it had when saved.
joblib works by leveraging optimized binary file formats that compress and split objects, if necessary, to handle large datasets or complex models. When a model, such as a scikit-learn pipeline, is saved with joblib, it stores the entire model state including learned parameters and configurations. Later, when the model is reloaded, it will immediately be ready to make predictions as if it had just been trained.
By doing so, joblib helps streamline the deployment process. Instead of retraining the model every time the application restarts, developers and operations teams can load the saved model into memory and start making predictions. This reduces both computational overhead and startup latency.
In this example, best_model likely refers to a finalized and tested pipeline or classifier. The file spam_detection_model.joblib will contain all the necessary information to predict new data. To reuse the model later, load it back into the environment. Remember that new data must be preprocessed the same way as the training data before making predictions:
Model Evaluation (Spam Detection)