flair.nn.DeepNCMDecoder#

class flair.nn.DeepNCMDecoder(label_dictionary, embeddings_size, use_encoder=True, encoding_dim=None, alpha=0.9, mean_update_method='online', multi_label=False)View on GitHub#

Bases: Module

Deep Nearest Class Mean (DeepNCM) Classifier for text classification tasks.

This model combines deep learning with the Nearest Class Mean (NCM) approach. It uses document embeddings to represent text, optionally applies an encoder, and classifies based on the nearest class prototype in the embedded space.

The model supports various methods for updating class prototypes during training, making it adaptable to different learning scenarios.

This implementation is based on the research paper: Guerriero, S., Caputo, B., & Mensink, T. (2018). DeepNCM: Deep Nearest Class Mean Classifiers. In International Conference on Learning Representations (ICLR) 2018 Workshop. URL: https://openreview.net/forum?id=rkPLZ4JPM

__init__(label_dictionary, embeddings_size, use_encoder=True, encoding_dim=None, alpha=0.9, mean_update_method='online', multi_label=False)View on GitHub#

Initialize a DeepNCMDecoder.

Parameters:
  • label_dictionary (Dictionary) – Label dictionary from the corpus

  • embeddings_size (int) – The dimensionality of the input embeddings, usually the same as the model embeddings

  • use_encoder (bool) – Whether to apply an encoder to the input embeddings (default is True).

  • encoding_dim (Optional[int]) – The dimensionality of the encoded embeddings if an encoder is used (default is the same as the input embeddings).

  • alpha (float) – The decay factor for updating class prototypes (default is 0.9). This only applies when mean_update_method is ‘decay’.

  • mean_update_method (Literal['online', 'condensation', 'decay']) – The method for updating class prototypes (‘online’, ‘condensation’, or ‘decay’). online - condensation - decay - after every batch,

  • multi_label (bool) – Whether to predict multiple labels per sentence (default is False, and performs multi-class clsasification).

Methods

__init__(label_dictionary, embeddings_size)

Initialize a DeepNCMDecoder.

add_module(name, module)

Add a child module to the current module.

apply(fn)

Apply fn recursively to every submodule (as returned by .children()) as well as self.

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

buffers([recurse])

Return an iterator over module buffers.

children()

Return an iterator over immediate children modules.

compile(*args, **kwargs)

Compile this Module's forward using torch.compile().

cpu()

Move all model parameters and buffers to the CPU.

cuda([device])

Move all model parameters and buffers to the GPU.

double()

Casts all floating point parameters and buffers to double datatype.

eval()

Set the module in evaluation mode.

extra_repr()

Set the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(embedded[, label_tensor])

Forward pass of the decoder, which calculates the scores as prototype distances.

get_buffer(target)

Return the buffer given by target if it exists, otherwise throw an error.

get_closest_prototypes(input_vector[, top_k])

Get the k closest prototype vectors to the given input vector using the configured distance metric.

get_extra_state()

Return any extra state to include in the module's state_dict.

get_parameter(target)

Return the parameter given by target if it exists, otherwise throw an error.

get_prototype(class_name)

Get the prototype vector for a given class name.

get_submodule(target)

Return the submodule given by target if it exists, otherwise throw an error.

half()

Casts all floating point parameters and buffers to half datatype.

ipu([device])

Move all model parameters and buffers to the IPU.

load_state_dict(state_dict[, strict, assign])

Copy parameters and buffers from state_dict into this module and its descendants.

modules()

Return an iterator over all modules in the network.

mtia([device])

Move all model parameters and buffers to the MTIA.

named_buffers([prefix, recurse, ...])

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

named_children()

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

named_modules([memo, prefix, remove_duplicate])

Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

named_parameters([prefix, recurse, ...])

Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

parameters([recurse])

Return an iterator over module parameters.

register_backward_hook(hook)

Register a backward hook on the module.

register_buffer(name, tensor[, persistent])

Add a buffer to the module.

register_forward_hook(hook, *[, prepend, ...])

Register a forward hook on the module.

register_forward_pre_hook(hook, *[, ...])

Register a forward pre-hook on the module.

register_full_backward_hook(hook[, prepend])

Register a backward hook on the module.

register_full_backward_pre_hook(hook[, prepend])

Register a backward pre-hook on the module.

register_load_state_dict_post_hook(hook)

Register a post-hook to be run after module's load_state_dict() is called.

register_load_state_dict_pre_hook(hook)

Register a pre-hook to be run before module's load_state_dict() is called.

register_module(name, module)

Alias for add_module().

register_parameter(name, param)

Add a parameter to the module.

register_state_dict_post_hook(hook)

Register a post-hook for the state_dict() method.

register_state_dict_pre_hook(hook)

Register a pre-hook for the state_dict() method.

requires_grad_([requires_grad])

Change if autograd should record operations on parameters in this module.

set_extra_state(state)

Set extra state contained in the loaded state_dict.

set_submodule(target, module)

Set the submodule given by target if it exists, otherwise throw an error.

share_memory()

See torch.Tensor.share_memory_().

state_dict(*args[, destination, prefix, ...])

Return a dictionary containing references to the whole state of the module.

to(*args, **kwargs)

Move and/or cast the parameters and buffers.

to_empty(*, device[, recurse])

Move the parameters and buffers to the specified device without copying storage.

train([mode])

Set the module in training mode.

type(dst_type)

Casts all parameters and buffers to dst_type.

update_prototypes()

Apply accumulated updates to class prototypes.

xpu([device])

Move all model parameters and buffers to the XPU.

zero_grad([set_to_none])

Reset gradients of all model parameters.

Attributes

T_destination

call_super_init

dump_patches

num_prototypes

The number of class prototypes.

training

property num_prototypes: int#

The number of class prototypes.

update_prototypes()View on GitHub#

Apply accumulated updates to class prototypes.

Return type:

None

forward(embedded, label_tensor=None)View on GitHub#

Forward pass of the decoder, which calculates the scores as prototype distances.

Parameters:
  • embedded (Tensor) – Embedded representations of the input sentences.

  • label_tensor (Optional[Tensor]) – True labels for the input sentences as a tensor.

Return type:

Tensor

Returns:

Scores as a tensor of distances to class prototypes.

get_prototype(class_name)View on GitHub#

Get the prototype vector for a given class name.

Parameters:

class_name (str) – The name of the class whose prototype vector is requested.

Returns:

The prototype vector for the given class.

Return type:

torch.Tensor

Raises:

ValueError – If the class name is not found in the label dictionary.

get_closest_prototypes(input_vector, top_k=5)View on GitHub#

Get the k closest prototype vectors to the given input vector using the configured distance metric.

Parameters:
  • input_vector (torch.Tensor) – The input vector to compare against prototypes.

  • top_k (int) – The number of closest prototypes to return (default is 5).

Returns:

Each tuple contains (class_name, distance).

Return type:

list[tuple[str, float]]