incerto.ood.KNN#
- class incerto.ood.KNN(model, k=50, layer_name='penultimate')[source]#
Bases:
OODDetectorKNN-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.
Save KNN training features.