snad_logo_3.png

MNIST dataset#

This notebook gives an example of Active Anomaly Detection with coniferest and MNIST dataset.

Developers of conferest:

Run this NB in Google Colab

[1]:
## Install and import the required libraries
[2]:
# Install packages
%pip install coniferest
%pip install datasets
Requirement already satisfied: coniferest in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (0.2.2)
Requirement already satisfied: click>=8.2 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from coniferest) (8.5.1)
Requirement already satisfied: numpy in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from coniferest) (2.5.4)
Requirement already satisfied: scipy in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from coniferest) (1.18.1)
Requirement already satisfied: onnx in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from coniferest) (1.23.2)
Requirement already satisfied: onnxconverter-common in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from coniferest) (1.16.0)
Requirement already satisfied: clarabel in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from coniferest) (0.11.1)
Requirement already satisfied: cffi in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from clarabel->coniferest) (2.1.1)
Requirement already satisfied: pycparser in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from cffi->clarabel->coniferest) (3.12)
Requirement already satisfied: protobuf>=6.31.1 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from onnx->coniferest) (7.36.2)
Requirement already satisfied: typing_extensions>=4.7.1 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from onnx->coniferest) (4.16.0)
Requirement already satisfied: ml_dtypes>=0.5.4 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from onnx->coniferest) (0.6.0)
Requirement already satisfied: packaging in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from onnxconverter-common->coniferest) (26.3)
Note: you may need to restart the kernel to use updated packages.
Requirement already satisfied: datasets in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (5.1.0)
Requirement already satisfied: filelock in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from datasets) (4.2.10)
Requirement already satisfied: numpy>=1.17 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from datasets) (2.5.4)
Requirement already satisfied: pyarrow>=24.0.0 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from datasets) (26.0.1)
Requirement already satisfied: dill<0.4.2,>=0.3.0 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from datasets) (0.4.1)
Requirement already satisfied: pandas in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from datasets) (3.1.1)
Requirement already satisfied: tqdm>=4.66.3 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from datasets) (4.70.1)
Requirement already satisfied: xxhash in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from datasets) (4.1.0)
Requirement already satisfied: multiprocess<0.70.20 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from datasets) (0.70.19)
Requirement already satisfied: fsspec<=2026.7.0,>=2023.1.0 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from fsspec[http]<=2026.7.0,>=2023.1.0->datasets) (2026.7.0)
Requirement already satisfied: huggingface-hub<3.0,>=1.31.0 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from datasets) (2.4.0)
Requirement already satisfied: packaging in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from datasets) (26.3)
Requirement already satisfied: pyyaml>=5.1 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from datasets) (6.0.3)
Requirement already satisfied: aiohttp!=4.0.0a0,!=4.0.0a1 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from fsspec[http]<=2026.7.0,>=2023.1.0->datasets) (3.14.5)
Requirement already satisfied: click<9.0.0,>=8.4.2 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from huggingface-hub<3.0,>=1.31.0->datasets) (8.5.1)
Requirement already satisfied: hf-xet<2.0.0,>=1.6.0 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from huggingface-hub<3.0,>=1.31.0->datasets) (1.8.0)
Requirement already satisfied: httpx2<3,>=2.0.0 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from huggingface-hub<3.0,>=1.31.0->datasets) (2.16.0)
Requirement already satisfied: typing-extensions>=4.1.0 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from huggingface-hub<3.0,>=1.31.0->datasets) (4.16.0)
Requirement already satisfied: anyio>=4.10 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from httpx2<3,>=2.0.0->huggingface-hub<3.0,>=1.31.0->datasets) (4.16.0)
Requirement already satisfied: httpcore2==2.16.0 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from httpx2<3,>=2.0.0->huggingface-hub<3.0,>=1.31.0->datasets) (2.16.0)
Requirement already satisfied: idna>=3.18 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from httpx2<3,>=2.0.0->huggingface-hub<3.0,>=1.31.0->datasets) (3.20)
Requirement already satisfied: truststore>=0.10 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from httpx2<3,>=2.0.0->huggingface-hub<3.0,>=1.31.0->datasets) (0.10.5)
Requirement already satisfied: h11>=0.16 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from httpcore2==2.16.0->httpx2<3,>=2.0.0->huggingface-hub<3.0,>=1.31.0->datasets) (0.16.0)
Requirement already satisfied: aiohappyeyeballs>=2.5.0 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2026.7.0,>=2023.1.0->datasets) (2.7.1)
Requirement already satisfied: aiosignal>=1.4.0 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2026.7.0,>=2023.1.0->datasets) (1.4.0)
Requirement already satisfied: attrs>=17.3.0 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2026.7.0,>=2023.1.0->datasets) (26.1.0)
Requirement already satisfied: frozenlist>=1.1.1 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2026.7.0,>=2023.1.0->datasets) (1.8.0)
Requirement already satisfied: multidict<8.0,>=4.5 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2026.7.0,>=2023.1.0->datasets) (7.2.1)
Requirement already satisfied: propcache>=0.2.0 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2026.7.0,>=2023.1.0->datasets) (0.5.4)
Requirement already satisfied: yarl<2.0,>=1.25.1 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2026.7.0,>=2023.1.0->datasets) (1.25.1)
Requirement already satisfied: python-dateutil>=2.9.0 in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from pandas->datasets) (4.0.0)
Requirement already satisfied: tzdata in /home/docs/checkouts/readthedocs.org/user_builds/coniferest/envs/latest/lib/python3.13/site-packages (from python-dateutil>=2.9.0->pandas->datasets) (2026.6)
Note: you may need to restart the kernel to use updated packages.
[3]:
import datasets
import matplotlib.pyplot as plt
import numpy as np

from coniferest.isoforest import IsolationForest
from coniferest.pineforest import PineForest
from coniferest.session import Session
from coniferest.session.callback import TerminateAfter, prompt_decision_callback, Label

Download and load the MNIST dataset#

Download data from Hugging Faces with datasets library

[4]:
mnist = datasets.load_dataset("ylecun/mnist")
Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.

Load the data into numpy arrays

[5]:
images_train = np.asarray(mnist['train']['image'])
images_test = np.asarray(mnist['test']['image'])
digits_train = np.asarray(mnist['train']['label'])
digits_test = np.asarray(mnist['test']['label'])

images = np.concatenate([images_train, images_test])
digits = np.concatenate([digits_train, digits_test])

Plot some examples

[6]:
fig, ax = plt.subplots(2, 5, figsize=(10, 5))
for i in range(10):
    ax[i // 5, i % 5].imshow(images[digits == i][0], cmap='gray')
    ax[i // 5, i % 5].set_title(f'Digit {i}')
    ax[i // 5, i % 5].axis('off')
../_images/notebooks_mnist_11_0.png

Preprocess the data#

Select the data to use:

  • image : the original images

  • fft : the power spectrum of the images

  • both : the original images and the power spectrum together

[7]:
DATA = 'both'  # 'image', 'fft', 'both'

Make 2-d FFT of the images

[8]:
# Make 2-d FFT of the images
data_fft = np.fft.fft2(images)
# Get power spectrum
power_spectrum = np.square(np.abs(data_fft))
# Normalize the power spectrum by zero frequency
power_spectrum = power_spectrum / power_spectrum[:, 0, 0][:, None, None]

Plot some examples of power spectrum

[9]:
fig, ax = plt.subplots(2, 5, figsize=(10, 5))
for i in range(10):
    ax[i // 5, i % 5].imshow(np.log(power_spectrum[digits == i][0]), cmap='gray')
    ax[i // 5, i % 5].set_title(f'Digit {i}')
    ax[i // 5, i % 5].axis('off')
../_images/notebooks_mnist_18_0.png

Concatenate images and power spectrum

[10]:
if DATA == 'image':
    final = np.asarray(images, dtype=np.float32)
elif DATA == 'fft':
    final = np.asarray(power_spectrum.reshape(-1, 28 * 28), dtype=np.float32)
elif DATA == 'both':
    final = np.concatenate([images.reshape(-1, 28 * 28), power_spectrum.reshape(-1, 28 * 28)], axis=1)
else:
    raise ValueError(f"Unknown value for DATA: {DATA}")

Classic anomaly detection with Isolation forest#

[11]:
model = IsolationForest(random_seed=10, n_trees=1000)
model.fit(np.array(final))
scores = model.score_samples(np.array(final))
ordered_index = np.argsort(scores)
ordered_digits = digits[ordered_index]

print(f"Top 10 weirdest digits : {ordered_digits[:10]}")
print(f"Top 10 most normal digits : {ordered_digits[-10:]}")
Top 10 weirdest digits : [6 5 5 5 5 3 7 9 5 5]
Top 10 most normal digits : [1 9 1 1 1 1 1 9 8 1]

Plot the top 10 weirdest digits and the top 10 most normal digits

[12]:
fig, ax = plt.subplots(2, 10, figsize=(20, 5))
for i in range(10):
    ax[0, i].imshow(images[ordered_index[i]], cmap='gray')
    ax[0, i].set_title(f'Digit {ordered_digits[i]}')
    ax[0, i].axis('off')
    ax[1, i].imshow(images[ordered_index[-i - 1]], cmap='gray')
    ax[1, i].set_title(f'Digit {ordered_digits[-i - 1]}')
    ax[1, i].axis('off')
fig.text(0.1, 0.9, 'Top 10 weirdest digits', ha='left', va='center', fontsize=16)
fig.text(0.1, 0.5, 'Top 10 most normal digits', ha='left', va='center', fontsize=16)
[12]:
Text(0.1, 0.5, 'Top 10 most normal digits')
../_images/notebooks_mnist_24_1.png

Anomaly detection with PineForest#

Set expert budget

[13]:
EXPERT_BUDGET = 20

First, we need a function which would show us an image, its label and ask us if it is an anomaly.

Let’s say that even numbers are anomalies

[14]:
def decision(index, x, session):
    digit, image = digits[index], images[index]
    fig, ax = plt.subplots(1, 1, figsize=(2, 2))
    ax.imshow(image, cmap='gray')
    ax.set_title(f'Digit {digit}')
    ax.axis('off')
    plt.show()

    ### UNCOMMENT TO MAKE IT INTERACTIVE
    # return prompt_decision_callback(index, x, session)

    # Non-interactive
    return Label.ANOMALY if digit % 2 == 0 else Label.REGULAR

Create a model and a session.

[15]:
model = PineForest(
    # Number of trees to use for predictions
    n_trees=256,
    # Number of new tree to grow for each decision
    n_spare_trees=768,
    # Fix random seed for reproducibility
    random_seed=0,
)
session = Session(
    data=final,
    metadata=np.arange(len(final)),
    model=model,
    decision_callback=decision,
    on_decision_callbacks=[
        TerminateAfter(EXPERT_BUDGET),
    ],
)
session.run()
../_images/notebooks_mnist_31_0.png
../_images/notebooks_mnist_31_1.png
../_images/notebooks_mnist_31_2.png
../_images/notebooks_mnist_31_3.png
../_images/notebooks_mnist_31_4.png
../_images/notebooks_mnist_31_5.png
../_images/notebooks_mnist_31_6.png
../_images/notebooks_mnist_31_7.png
../_images/notebooks_mnist_31_8.png
../_images/notebooks_mnist_31_9.png
../_images/notebooks_mnist_31_10.png
../_images/notebooks_mnist_31_11.png
../_images/notebooks_mnist_31_12.png
../_images/notebooks_mnist_31_13.png
../_images/notebooks_mnist_31_14.png
../_images/notebooks_mnist_31_15.png
../_images/notebooks_mnist_31_16.png
../_images/notebooks_mnist_31_17.png
../_images/notebooks_mnist_31_18.png
../_images/notebooks_mnist_31_19.png
[15]:
<coniferest.session.Session at 0x7e24da914050>

Let’s see what we have selected

[16]:
n_anomalies = len(session.known_anomalies)
n_total = len(session.known_labels)
print(f"Anomalies: {n_anomalies}/{n_total} ({n_anomalies / n_total:.2%})")
Anomalies: 12/20 (60.00%)

Let’s do the opposite: odd numbers are anomalies

[17]:
def decision(index, x, session):
    digit, image = digits[index], images[index]
    fig, ax = plt.subplots(1, 1, figsize=(2, 2))
    ax.imshow(image, cmap='gray')
    ax.set_title(f'Digit {digit}')
    ax.axis('off')
    plt.show()

    ### UNCOMMENT TO MAKE IT INTERACTIVE
    # return prompt_decision_callback(index, x, session)

    # Non-interactive
    return Label.ANOMALY if digit % 2 == 1 else Label.REGULAR


model = PineForest(
    # Number of trees to use for predictions
    n_trees=256,
    # Number of new tree to grow for each decision
    n_spare_trees=768,
    # Fix random seed for reproducibility
    random_seed=0,
)
session = Session(
    data=final,
    metadata=np.arange(len(final)),
    model=model,
    decision_callback=decision,
    on_decision_callbacks=[
        TerminateAfter(EXPERT_BUDGET),
    ],
)
session.run()

n_anomalies = len(session.known_anomalies)
n_total = len(session.known_labels)
print(f"Anomalies: {n_anomalies}/{n_total} ({n_anomalies / n_total:.2%})")
../_images/notebooks_mnist_35_0.png
../_images/notebooks_mnist_35_1.png
../_images/notebooks_mnist_35_2.png
../_images/notebooks_mnist_35_3.png
../_images/notebooks_mnist_35_4.png
../_images/notebooks_mnist_35_5.png
../_images/notebooks_mnist_35_6.png
../_images/notebooks_mnist_35_7.png
../_images/notebooks_mnist_35_8.png
../_images/notebooks_mnist_35_9.png
../_images/notebooks_mnist_35_10.png
../_images/notebooks_mnist_35_11.png
../_images/notebooks_mnist_35_12.png
../_images/notebooks_mnist_35_13.png
../_images/notebooks_mnist_35_14.png
../_images/notebooks_mnist_35_15.png
../_images/notebooks_mnist_35_16.png
../_images/notebooks_mnist_35_17.png
../_images/notebooks_mnist_35_18.png
../_images/notebooks_mnist_35_19.png
Anomalies: 18/20 (90.00%)

Change decision function to make it interactive and try your own experiments. For example, say yes to weird sevens only