flair.models.Lemmatizer#
- class flair.models.Lemmatizer(embeddings=None, label_type='lemma', rnn_input_size=50, rnn_hidden_size=256, rnn_layers=2, encode_characters=True, char_dict='common-chars-lemmatizer', max_sequence_length_dependent_on_input=True, max_sequence_length=20, use_attention=True, beam_size=1, start_symbol_for_encoding=True, end_symbol_for_encoding=True, bidirectional_encoding=True)View on GitHub#
Bases:
Classifier
[Sentence
]- __init__(embeddings=None, label_type='lemma', rnn_input_size=50, rnn_hidden_size=256, rnn_layers=2, encode_characters=True, char_dict='common-chars-lemmatizer', max_sequence_length_dependent_on_input=True, max_sequence_length=20, use_attention=True, beam_size=1, start_symbol_for_encoding=True, end_symbol_for_encoding=True, bidirectional_encoding=True)View on GitHub#
Initializes a Lemmatizer model.
The model consists of a decoder and an encoder. The encoder is either a RNN-cell (torch.nn.GRU) or a Token-Embedding from flair if an embedding is handed to the constructor (token_embedding). The output of the encoder is used as the initial hidden state to the decoder, which is an RNN-cell (GRU) that predicts the lemma of the given token one letter at a time. Note that one can use data in which only those words are annotated that differ from their lemma or data in which all words are annotated with a (maybe equal) lemma.
- Parameters:
encode_characters (
bool
) – If True, use a character embedding to additionally encode tokens per character.start_symbol_for_encoding (
bool
) – If True, use a start symbol for encoding characters.end_symbol_for_encoding (
bool
) – If True, use an end symbol for encoding characters.bidirectional_encoding (
bool
) – If True, the character encoding is bidirectional.embeddings (
Optional
[TokenEmbeddings
]) – Embedding used to encode sentencernn_input_size (
int
) – Input size of the RNN(‘s). Each letter of a token is represented by a hot-one-vector over the given character dictionary. This vector is transformed to a input_size vector with a linear layer.rnn_hidden_size (
int
) – size of the hidden state of the RNN(‘s).rnn_layers (
int
) – Number of stacked RNN cellsbeam_size (
int
) – Number of hypothesis used when decoding the output of the RNN. Only used in prediction.char_dict (
Union
[str
,Dictionary
]) – Dictionary of characters the model is able to process. The dictionary must contain <unk> for the handling of unknown characters. If None, a standard dictionary will be loaded. One can either hand over a path to a dictionary or the dictionary itself.label_type (
str
) – Name of the gold labels to use.max_sequence_length_dependent_on_input (
bool
) – If set to True, the maximum length of a decoded sequence in the prediction depends on the sentences you want to lemmatize. To be precise the maximum length is computed as the length of the longest token in the sentences plus one.max_sequence_length (
int
) – If set to True and max_sequence_length_dependend_on_input is False a fixed maximum length for the decoding will be used for all sentences.use_attention (
bool
) – whether to use attention. Only sensible if encoding via RNN
Methods
__init__
([embeddings, label_type, ...])Initializes a Lemmatizer model.
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.
decode
(decoder_input_indices, ...)double
()Casts all floating point parameters and buffers to
double
datatype.encode
(sentences)encode_token
(token)eval
()Set the module in evaluation mode.
evaluate
(*args, **kwargs)Evaluates the model.
extra_repr
()Set the extra representation of the module.
float
()Casts all floating point parameters and buffers to
float
datatype.forward
(encoder_input_indices, lengths, ...)Define the computation performed at every call.
forward_loss
(sentences)Performs a forward pass and returns a loss tensor for backpropagation.
forward_pass
(sentences)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, ...])Predict lemmas of words for a given (list of) sentence(s).
print_model_card
()This method produces a log message that includes all recorded parameters the model was trained with.
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
.words_to_char_indices
(tokens[, end_symbol, ...])For a given list of strings this function creates index vectors that represent the characters of the strings.
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
Each model predicts labels of a certain type.
model_card
training
- property label_type#
Each model predicts labels of a certain type.
- words_to_char_indices(tokens, end_symbol=True, start_symbol=False, padding_in_front=False, seq_length=None)View on GitHub#
For a given list of strings this function creates index vectors that represent the characters of the strings.
Each string is represented by sequence_length (maximum string length + entries for special symbol) many indices representing characters in self.char_dict. One can manually set the vector length with the parameter seq_length, though the vector length is always at least maximum string length in the list.
- Parameters:
seq_length – the maximum sequence length to use, if None the maximum is taken..
tokens (
list
[str
]) – the texts of the toekens to encodeend_symbol – add self.end_index at the end of each representation
start_symbol – add self.start_index in front of each representation
padding_in_front – whether to fill up with self.dummy_index in front or in back of strings
- forward_pass(sentences)View on GitHub#
- decode(decoder_input_indices, initial_hidden_states, all_encoder_outputs)View on GitHub#
- forward(encoder_input_indices, lengths, token_embedding_hidden)View on GitHub#
Define the computation performed at every call.
Should be overridden by all subclasses. :rtype:
tuple
[Tensor
,Optional
[Tensor
]]Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- encode(sentences)View on GitHub#
- encode_token(token)View on GitHub#
- forward_loss(sentences)View on GitHub#
Performs a forward pass and returns a loss tensor for backpropagation.
Implement this to enable training.
- Return type:
tuple
[Tensor
,int
]
- predict(sentences, mini_batch_size=16, return_probabilities_for_all_classes=False, verbose=False, label_name='predicted', return_loss=False, embedding_storage_mode='none')View on GitHub#
Predict lemmas of words for a given (list of) sentence(s).
- Parameters:
sentences (
Union
[list
[Sentence
],Sentence
]) – sentences to predictlabel_name – label name used for predicted lemmas
mini_batch_size (
int
) – number of tokens that are send through the RNN simultaneously, assuming batching_in_rnn is set to Trueembedding_storage_mode – default is ‘none’ which is always best. Only set to ‘cpu’ or ‘gpu’ if you wish to not only predict, but also keep the generated embeddings in CPU or GPU memory respectively.
return_loss – whether to compute and return loss. Setting it to True only makes sense if labels are provided
verbose (
bool
) – If True, lemmatized sentences will be printed in the console.return_probabilities_for_all_classes (
bool
) – unused parameter.
- evaluate(*args, **kwargs)View on GitHub#
Evaluates the model. Returns a Result object containing evaluation results and a loss value.
Implement this to enable evaluation.
- Parameters:
data_points – The labeled data_points to evaluate.
gold_label_type – The label type indicating the gold labels
out_path – Optional output path to store predictions.
embedding_storage_mode – One of ‘none’, ‘cpu’ or ‘gpu’. ‘none’ means all embeddings are deleted and freshly recomputed, ‘cpu’ means all embeddings are stored on CPU, or ‘gpu’ means all embeddings are stored on GPU
mini_batch_size – The batch_size to use for predictions.
main_evaluation_metric – Specify which metric to highlight as main_score.
exclude_labels – Specify classes that won’t be considered in evaluation.
gold_label_dictionary – Specify which classes should be considered, all other classes will be taken as <unk>.
return_loss – Weather to additionally compute the loss on the data-points.
**kwargs – Arguments that will be ignored.
- Return type:
Result
- Returns:
The evaluation results.