flair.models.PrefixedSequenceTagger#

class flair.models.PrefixedSequenceTagger(*args, augmentation_strategy, **kwargs)View on GitHub#

Bases: SequenceTagger

__init__(*args, augmentation_strategy, **kwargs)View on GitHub#

Constructor for this class.

Parameters:
  • embeddings – Embeddings to use during training and prediction

  • tag_dictionary – Dictionary containing all tags from corpus which can be predicted

  • tag_type – type of tag which is going to be predicted in case a corpus has multiple annotations

  • use_rnn – If true, use a RNN, else Linear layer.

  • rnn – Takes a torch.nn.Module as parameter by which you can pass a shared RNN between different tasks.

  • rnn_type – Specifies the RNN type to use, default is ‘LSTM’, can choose between ‘GRU’ and ‘RNN’ as well.

  • hidden_size – Hidden size of RNN layer

  • rnn_layers – number of RNN layers

  • bidirectional – If True, RNN becomes bidirectional

  • use_crf – If True, use a Conditional Random Field for prediction, else linear map to tag space.

  • reproject_embeddings – If True, add a linear layer on top of embeddings, if you want to imitate fine tune non-trainable embeddings.

  • dropout – If > 0, then use dropout.

  • word_dropout – If > 0, then use word dropout.

  • locked_dropout – If > 0, then use locked dropout.

  • train_initial_hidden_state – if True, trains initial hidden state of RNN

  • loss_weights – Dictionary of weights for labels for the loss function. If any label’s weight is unspecified it will default to 1.0.

  • init_from_state_dict – Indicator whether we are loading a model from state dict since we need to transform previous models’ weights into CRF instance weights

  • allow_unk_predictions – If True, allows spans to predict <unk> too.

  • tag_format – the format to encode spans as tags, either “BIO” or “BIOES”

Methods

RNN(rnn_type, rnn_layers, hidden_size, ...)

Static wrapper function returning an RNN instance from PyTorch.

__init__(*args, augmentation_strategy, **kwargs)

Constructor for this class.

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.

augment_sentences(sentences[, annotation_layers])

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.

evaluate(data_points, gold_label_type[, ...])

Evaluates the model.

extra_repr()

Set the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(sentence_tensor, lengths)

Forward pass through the SequenceTagger.

forward_loss(sentences)

Conducts a forward pass through the SequenceTagger using labeled sentences and return the loss.

get_buffer(target)

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

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_submodule(target)

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

get_used_tokens(corpus[, context_length, ...])

half()

Casts all floating point parameters and buffers to half datatype.

ipu([device])

Move all model parameters and buffers to the IPU.

load(model_path)

Loads a Flair model from the given file or state dictionary.

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.

predict(sentences[, mini_batch_size, ...])

Call this method to predict labels for sentences.

print_model_card()

This method produces a log message that includes all recorded parameters the model was trained with.

push_to_hub(repo_id[, token, private, ...])

Uploads the Sequence Tagger model to a Hugging Face Hub repository.

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.

save(model_file[, checkpoint])

Saves the current model to the provided file.

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.

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

label_type

Each model predicts labels of a certain type.

model_card

training

classmethod load(model_path)View on GitHub#

Loads a Flair model from the given file or state dictionary.

Parameters:

model_path (Union[str, Path, dict[str, Any]]) – Either the path to the model (as string or Path variable) or the already loaded state dict.

Return type:

PrefixedSequenceTagger

Returns:

The loaded Flair model.

forward_loss(sentences)View on GitHub#

Conducts a forward pass through the SequenceTagger using labeled sentences and return the loss.

Parameters:

sentences (Union[list[Sentence], list[PrefixedSentence]]) – A batch of labeled sentences.

Return type:

tuple[Tensor, int]

Returns:

A tuple consisting of the loss tensor and the number of tokens in the batch.

predict(sentences, mini_batch_size=32, return_probabilities_for_all_classes=False, verbose=False, label_name=None, return_loss=False, embedding_storage_mode='none', force_token_predictions=False)View on GitHub#

Call this method to predict labels for sentences.

Predictions are directly added to the Sentence objects that are passed to this method. This means that the predict() method does not return predictions. Rather, predictions are stored at each sentence and can be retrieved by calling flair.data.Sentence.get_labels() on each flair.data.Sentence.

Parameters:
  • sentences (Union[list[Sentence], Sentence, list[PrefixedSentence], PrefixedSentence]) – List of sentences in batch

  • mini_batch_size (int) – batch size for test data

  • return_probabilities_for_all_classes (bool) – Whether to return probabilities for all classes

  • verbose (bool) – whether to use progress bar

  • label_name (Optional[str]) – which label to predict

  • return_loss – whether to return loss value

  • embedding_storage_mode – determines where to store embeddings - can be “gpu”, “cpu” or None.

  • force_token_predictions (bool) – add labels per token instead of span labels, even if self.predict_spans is True

augment_sentences(sentences, annotation_layers=None)View on GitHub#
Return type:

list[PrefixedSentence]