Skip to main content

Algorithm - Environment Corruptions

Description

  • Robustness plugin with environment corruptions

License

  • Licensed under Apache Software License 2.0

Developers

  • AI Verify

Installation

Each test algorithm can now be installed via pip and run individually.

pip install aiverify-environment-corruptions

Example Usage

Run the following bash script to execute the plugin

#!/bin/bash

root_path="<PATH_TO_FOLDER>/aiverify/stock-plugins/user_defined_files"

python -m aiverify_environment_corruptions \
  --data_path $root_path/data/raw_fashion_image_10 \
  --model_path $root_path/pipeline/sample_fashion_mnist_sklearn \
  --model_type CLASSIFICATION \
  --ground_truth_path $root_path/data/pickle_pandas_fashion_mnist_annotated_labels_10.sav \
  --ground_truth label \
  --file_name_label file_name \
  --set_seed 10

If the algorithm runs successfully, the results of the test will be saved in an output folder.

Including Specific Corruptions

Usage

By default, all corruption functions are applied. You can use the --corruptions flag to specify which functions to run.

--corruptions [FUNCTION_NAME ...]

Options

  • all -> Runs all environment corruption functions (default)
  • snow
  • fog
  • rain

Example: Applying only Snow and Rain corruptions

#!/bin/bash

root_path="<PATH_TO_FOLDER>/aiverify/stock-plugins/user_defined_files"

python -m aiverify_environment_corruptions \
  --data_path $root_path/data/raw_fashion_image_10 \
  --model_path $root_path/pipeline/sample_fashion_mnist_sklearn \
  --model_type CLASSIFICATION \
  --ground_truth_path $root_path/data/pickle_pandas_fashion_mnist_annotated_labels_10.sav \
  --ground_truth label \
  --file_name_label file_name \
  --set_seed 10
  --corruptions snow rain

Customizing Parameters

To fine-tune the corruption parameters, use the Environment Corruption Playground Notebook. This notebook allows you to:

✅ Visualize the effects of different corruption functions.

✅ Experiment with different parameter values.

✅ Apply custom values in the CLI using flags like:

#!/bin/bash

root_path="<PATH_TO_FOLDER>/aiverify/stock-plugins/user_defined_files"

python -m aiverify_environment_corruptions \
  --data_path $root_path/data/raw_fashion_image_10 \
  --model_path $root_path/pipeline/sample_fashion_mnist_sklearn \
  --model_type CLASSIFICATION \
  --ground_truth_path $root_path/data/pickle_pandas_fashion_mnist_annotated_labels_10.sav \
  --ground_truth label \
  --file_name_label file_name \
  --set_seed 10
  --snow_intensity 1.0 2.0 3.0

PyTorch/TensorFlow support

To use a custom PyTorch/TensorFlow model with this plugin, follow the steps below:

  1. Install PyTorch/TensorFlow

    Ensure you have installed a PyTorch/TensorFlow version compatible with your model.

  2. Specify Model Path

    Use the --model_path command-line argument to specify the path to a folder containing:

    • The model class definition (e.g., model.py).
    • The model weights file (e.g., model_weights.pt).
  3. Implement a predict Function

    Your model class must implement a predict function. This function should:

    • Accept a batch of image file paths as input.
    • Return a batch of predictions.

    For reference, see the sample implementation in user_defined_files/pipeline/sample_fashion_mnist_pytorch.

Example Directory Structure

<model_path>/
├── model.py             # Contains the model class definition
├── model_weights.pt     # Contains the trained model weights

Example predict Function (PyTorch)

# model.py
from typing import Iterable

import numpy as np
import torch
from PIL import Image
from torchvision import transforms


class CustomModel(torch.nn.Module):
    def __init__(self):
        super().__init__()
        # Define your model architecture here
        ...

    def forward(self, x):
        # Define the forward pass
        ...

    def predict(self, image_paths: Iterable[str]) -> np.ndarray:
        transform = transforms.Compose([
            transforms.Resize((224, 224)),
            ...,
            transforms.ToTensor(),
        ])
        images = [Image.open(path).convert("RGB") for path in image_paths]
        image_tensors = torch.stack([transform(image) for image in images])

        self.eval()
        with torch.no_grad():
            predictions = self(image_tensors).argmax(dim=1).detach().cpu().numpy()
        return predictions

By following these steps, you can integrate your custom PyTorch/TensorFlow model into the corruption plugin.

Develop plugin locally

Execute the below bash script in the project root

#!/bin/bash

# setup virtual environment
python -m venv .venv
source .venv/bin/activate

# install plugin
cd aiverify/stock-plugins/aiverify.stock.image-corruption-toolbox/algorithms/environment_corruptions/
pip install .

python -m aiverify_environment_corruptions --data_path  <data_path> --model_path <model_path> --model_type CLASSIFICATION --ground_truth_path <ground_truth_path> --ground_truth <str> --file_name_label <str> --set_seed <int>

Build Plugin

cd aiverify/stock-plugins/aiverify.stock.image-corruption-toolbox/algorithms/environment_corruptions/
hatch build

Tests

Run the following steps to execute the unit and integration tests inside the tests/ folder

cd aiverify/stock-plugins/aiverify.stock.image-corruption-toolbox/algorithms/environment_corruptions/
pytest .

Run using Docker

In the aiverify root directory, run the below command to build the docker image

docker build -t aiverify-environment-corruptions -f stock-plugins/aiverify.stock.image-corruption-toolbox/algorithms/environment_corruptions/Dockerfile .

Run the below bash script to run the algorithm

#!/bin/bash
docker run \
  -v $(pwd)/stock-plugins/user_defined_files:/input \
  -v $(pwd)/stock-plugins/aiverify.stock.image-corruption-toolbox/algorithms/environment_corruptions/output:/app/aiverify/output \
  aiverify-environment-corruptions \
  --data_path /input/data/raw_fashion_image_10 \
  --model_path /input/pipeline/sample_fashion_mnist_sklearn \
  --model_type CLASSIFICATION \
  --ground_truth_path /input/data/pickle_pandas_fashion_mnist_annotated_labels_10.sav \
  --ground_truth label \
  --file_name_label file_name \
  --set_seed 10

If the algorithm runs successfully, the results of the test will be saved in an output folder in the algorithm directory.

Tests

Run the following steps to execute the unit and integration tests inside the tests/ folder

docker run \
  --entrypoint python3 \
  -w /app/aiverify/stock-plugins/aiverify.stock.image-corruption-toolbox/algorithms/environment_corruptions \
  aiverify-environment-corruptions \
  -m pytest .

Metadata

Release files for aiverify-environment-corruptions 2.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for aiverify-environment-corruptions 2.2.1
File Size Uploaded Provenance Actions
aiverify_environment_corruptions-2.2.1.tar.gz 23.3 kB Without provenance Details for aiverify_environment_corruptions-2.2.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for aiverify-environment-corruptions 2.2.1
File Interpreter ABI Platform Actions
aiverify_environment_corruptions-2.2.1-py3-none-any.whl Python 3 none any Details for aiverify_environment_corruptions-2.2.1-py3-none-any.whl

Total release size: 50.0 kB

Release files / aiverify_environment_corruptions-2.2.1.tar.gz

Download URL aiverify_environment_corruptions-2.2.1.tar.gz
Size 23.3 kB
Tags Source
SHA-256 checksum
How to use checksums
2e2ae62a4b29a0dda22a0d498e6abe324db78a3027f8d784b4739403fd618221
BLAKE2b-256 checksum
How to use checksums
fd9de302109174ae41d4b72ebee48549ecca45acf29a3feef8fd9eb59d47f79b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via Hatch/1.16.5 cpython/3.11.15 HTTPX/0.28.1

Release files / aiverify_environment_corruptions-2.2.1-py3-none-any.whl

Download URL aiverify_environment_corruptions-2.2.1-py3-none-any.whl
Size 26.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1dadafaaa92b7ce7337923a6474fafc48175983e107f9b45f689902837569cc9
BLAKE2b-256 checksum
How to use checksums
3e0de02acc26c7aaac9cf6977cf7c0350751f0edf71a5eb4bc3f910c2eabb503
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via Hatch/1.16.5 cpython/3.11.15 HTTPX/0.28.1

Security for aiverify-environment-corruptions 2.2.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page