incerto.ood.KNN#

class incerto.ood.KNN(model, k=50, layer_name='penultimate')[source]#

Bases: OODDetector

KNN-based OOD detection (Sun et al., NeurIPS 2022).

Computes OOD score as distance to k-th nearest neighbor in feature space. Requires fitting on training data.

__init__(model, k=50, layer_name='penultimate')[source]#

Initialize the OOD detector with a trained model.

The model is automatically: 1. Set to eval mode 2. Has gradients disabled (requires_grad=False)

Parameters:

model – A trained PyTorch model (nn.Module)

Methods

__init__(model[, k, layer_name])

Initialize the OOD detector with a trained model.

fit(loader)

Store training features for KNN computation.

load_state_dict(state)

Load KNN training features.

predict(x, threshold)

Predict whether inputs are OOD using a threshold.

save(path)

Save detector state to a file (excluding the model).

score(x)

Compute OOD score as distance to k-th nearest neighbor.

state_dict()

Save KNN training features.

__init__(model, k=50, layer_name='penultimate')[source]#

Initialize the OOD detector with a trained model.

The model is automatically: 1. Set to eval mode 2. Has gradients disabled (requires_grad=False)

Parameters:

model – A trained PyTorch model (nn.Module)

fit(loader)[source]#

Store training features for KNN computation.

score(x)[source]#

Compute OOD score as distance to k-th nearest neighbor.

state_dict()[source]#

Save KNN training features.

Return type:

dict

load_state_dict(state)[source]#

Load KNN training features.

Parameters:

state (dict)

Return type:

None