In the context of machine learning (ML), flaky tests can be troublesome as they introduce uncertainty into the evaluation process, potentially leading to incorrect conclusions about model performance or behavior.
In this article, we’ll:
Introduction to Flaky TestsFlaky tests refer to automated tests that produce non-deterministic results, meaning they may pass or fail inconsistently under the same conditions, without any changes to the code. In other words, they’re unpredictable and can pass or fail when re-run, even if there have been no modifications to the code base, dependencies, or test environment.
In the context of ML, flaky tests can manifest in various forms, causing issues that include, among others:
Issues Caused by Flaky Tests in Machine LearningDue to their nature, flaky tests introduce two different sets of issues in the context of machine learning:
Let’s discuss both of them.
Infrastructure-related IssuesIn ML environments, flaky tests can introduce several significant issues on the side of the infrastructure, complicating the development, deployment, and maintenance of ML models.
We can recall the following:
Model-related issuesFlaky tests can significantly impact various aspects of the machine learning model lifecycle, including training, validation, and generalization. These impacts can compromise the model’s performance, its reliability in production environments, and ultimately the project’s success.
We can recall the following:
Examples of Flakiness in Machine LearningIn this section, I want to consider flakiness due to ML models themself. In other words, in machine learning, flakiness also exists due to the statistical nature of the models.
In the context of machine learning, in fact, flaky tests can arise due to various reasons such as:
Let’s see an overview of some Python examples demonstrating common scenarios where flakiness might occur in ML.
Example 1: Flakiness Due to Random InitializationLet’s consider the following code:
import numpy as npfrom sklearn.datasets import make_classificationfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestClassifier# Generate synthetic dataX, y = make_classification(n_samples=1000, n_features=20, random_state=42)# Split data into train and test setsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# Train Random Forest classifierclf = RandomForestClassifier(n_estimators=100, random_state=np.random.randint(100))clf.fit(X_train, y_train)# Evaluate classifieraccuracy = clf.score(X_test, y_test)print("Accuracy:", accuracy)
In this example, the accuracy of the Random Forest classifier varies across runs due to the random_state parameter used for initialization.
In this case, setting random_state=42 in the make_classification() function results in an accuracy of 0.895 approximately.
Instead, setting random_state=0 make_classification() results in an accuracy of 0.945 approximately.
To verify the different results that the modification of this parameter leads to, good tests involve:
make_classification() (which generates the classification data) and train_test_split()(which splits the generated data into the train and test set) functions.random_state parameter are set randomly.Example 2: Flakiness Due to Data ShufflingLet’s consider the following scenario:
from sklearn.datasets import load_irisfrom sklearn.model_selection import KFoldfrom sklearn.svm import SVC# Load iris datasetiris = load_iris()X, y = iris.data, iris.target# Initialize SVM classifierclf = SVC(kernel='linear', random_state=42)# K-fold cross-validationkf = KFold(n_splits=5, shuffle=True, random_state=42)accuracies = []for train_index, test_index in kf.split(X): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] clf.fit(X_train, y_train) accuracy = clf.score(X_test, y_test) accuracies.append(accuracy)mean_accuracy = np.mean(accuracies)print("Mean Accuracy:", mean_accuracy)print(accuracies)
This results in:
Mean Accuracy: 0.9733333333333334[1.0, 1.0, 0.9666666666666667, 0.9333333333333333, 0.9666666666666667]
In this example, the K-fold cross-validation produces different accuracy values across runs due to the shuffling of data during each split, leading to flakiness in test results.
Also, in such cases, every time we run the code, the value of accuracy we get may be different because of the shuffle=Trueparameter in the KFold() function.
Example 3: Flakiness Due to Algorithm VariabilityLet’s consider the following:
from sklearn.datasets import load_irisfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_split# Load Iris datasetiris = load_iris()X, y = iris.data, iris.target# Introduce flakiness due to randomness in bootstrappingaccuracies = []for _ in range(10): # Split data into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=None) # Train Random Forest classifier clf = RandomForestClassifier(n_estimators=100) clf.fit(X_train, y_train) # Evaluate classifier accuracy = clf.score(X_test, y_test) accuracies.append(accuracy)print("Mean Accuracy:", sum(accuracies) / len(accuracies))
In this case, every time you run the code you get a slightly different value of the accuracy. This is due to variability in the algorithm’s process that, in this particular case, is due to randomness in bootstrapping that estimates the distribution of a statistic.
Note that flakiness due to the algorithms’ variability involves different ML models (not only the Random Forest).
Strategies to Avoid Flaky Tests in Machine LearningAs we’ve considered flakiness due to ML models’ management, in this paragraph we’ll consider some strategies to avoid it.
Strategy 1: Ensure ReproducibilityOne strategy to avoid flakiness in ML is to ensure reproducibility across ML experiments.
To do so, you can consider the following:
random_state parameter. The random_state parameter in scikit-learn serves as a seed for the random number generator. It ensures that you get the same results each time you run a piece of code, which is crucial for reproducibility in machine learning experiments. Common choices are integers like 0, 42, or any other fixed integer. In particular, if you’re comparing different algorithms, preprocessing steps, or model parameters, use the same random_state across all the experiments to ensure that the differences in results come from the changes you’re investigating, not the randomness in data shuffling or initialization.random_state parameter allows you to study for flakiness due to other factors. Good tests can be made on the actual data at your disposal, as well as on the code you’ve written. To do so, a good practice is to create different experiments and freeze them, using version control for each different experiment: this way you can investigate different scenarios being sure to save everything. Finally, consider that there are also AI tools that can help you with version control like DVC.Strategy 2: Stabilize The Training ProcessThe training process can introduce flakiness if you don’t follow standardized procedures. A strategy that eliminates flakiness can consider the following:
Min-Max scaling or Standardization (if you’re not familiar with the concept of scaling features, you can read this article).random_state across multiple runs. This helps in obtaining stable estimates of model performance by averaging results over different data splits.Strategy 3: Implement Quality Assurance PracticesEnsuring the reliability and stability of ML workflows is fundamental to mitigating flakiness in ML. In this scenario, a good practice is to introduce quality assurance best practices to identify potential sources of variability and randomness in ML experiments.
For example, you can consider the following:
ConclusionsIn this article, we’ve shown how flaky tests can affect ML models.
Due to the stochastic nature of the ML models, there are a lot of ways to reduce and mitigate the effect of randomness. To do so, we’ve investigated how ML models can be affected by randomness and strategies to reduce it, by standardizing processes and procedures.
The post Flaky Tests in Machine Learning: Challenges and Countermeasures appeared first on Semaphore.