Link

Lemmatization

Table of contents


Description

The lemmatization module recovers the lemma form for each input word. For example, the input sequence “I ate an apple” will be lemmatized into “I eat a apple”. This type of word normalization is useful in many real-world applications. In Stanza, lemmatization is performed by the LemmaProcessor and can be invoked with the name lemma.

NameAnnotator class nameRequirementGenerated AnnotationDescription
lemmaLemmaProcessortokenize, mwt, posPerform lemmatization on a Word using the Word.text and Word.upos values. The result can be accessed as Word.lemma.Generates the word lemmas for all words in the Document.

Options

Option nameTypeDefaultDescription
lemma_use_identityboolFalseWhen this flag is used, an identity lemmatizer (see models.identity_lemmatizer) will be used instead of a statistical lemmatizer. This is useful when [Word.lemma] is required for languages such as Vietnamese, where the lemma is identical to the original word form.
lemma_batch_sizeint50When annotating, this argument specifies the maximum number of words to batch for efficient processing.
lemma_ensemble_dictboolTrueIf set to True, the lemmatizer will ensemble a seq2seq model with the output from a dictionary-based lemmatizer, which yields improvements on many languages (see system description paper for more details).
lemma_dict_onlyboolFalseIf set to True, only a dictionary-based lemmatizer will be used. For languages such as Chinese, a dictionary-based lemmatizer is enough.
lemma_editboolTrueIf set to True, use an edit classifier alongside the seq2seq lemmatizer. The edit classifier will predict “shortcut” operations such as “identical” or “lowercase”, to make the lemmatization of long sequences more stable.
lemma_beam_sizeint1Control the beam size used during decoding in the seq2seq lemmatizer.
lemma_pretaggedboolFalseAssume the document is tokenized and pretagged. Only run lemma analysis on the document.
lemma_max_dec_lenint50Control the maximum decoding character length in the seq2seq lemmatizer. The decoder will stop if this length is achieved and the end-of-sequence character is still not seen.
lemma_store_resultsboolTrueRemember the lemma predicted for each (word, upos) pair and reuse it the next time that pair appears, skipping the seq2seq model for words it has already seen. Words a contextual classifier decides, such as English 's, are never remembered, since their lemma depends on context.
lemma_store_results_sizeint10000How many (word, upos) pairs lemma_store_results keeps. Once full, the least recently used pair is dropped, so memory stays bounded however long the pipeline runs.

Example Usage

Running the LemmaProcessor requires the TokenizeProcessor, MWTProcessor, and POSProcessor. After the pipeline is run, the Document will contain a list of Sentences, and the Sentences will contain lists of Words. The lemma information can be found in the lemma field of each Word.

Accessing Lemma for Word

Here is an example of lemmatizing words in a sentence and accessing their lemmas afterwards:

import stanza

nlp = stanza.Pipeline(lang='en', processors='tokenize,mwt,pos,lemma')
doc = nlp('Barack Obama was born in Hawaii.')
print(*[f'word: {word.text+" "}\tlemma: {word.lemma}' for sent in doc.sentences for word in sent.words], sep='\n')

As can be seen in the result, Stanza lemmatizes the word was as be.

word: Barack    lemma: Barack
word: Obama     lemma: Obama
word: was       lemma: be
word: born      lemma: bear
word: in        lemma: in
word: Hawaii    lemma: Hawaii
word: .         lemma: .

Lemmatizing pretagged text

If you already have tokenized, tagged text, you can use the lemmatizer to add lemmas without retokenizing or tagging:

import stanza
from stanza.models.common.doc import Document

nlp = stanza.Pipeline(lang='en', processors='tokenize,lemma', lemma_pretagged=True, tokenize_pretokenized=True)
pp = Document([[{'id': 1, 'text': 'puppies', 'upos': 'NOUN'}]])
print("BEFORE ADDING LEMMA")
print(pp)
doc = nlp(pp)
print("AFTER ADDING LEMMA")
print(doc)

The updated doc will have the lemmas attached to the words:

BEFORE ADDING LEMMA
[
  [
    {
      "id": 1,
      "text": "puppies",
      "upos": "NOUN"
    }
  ]
]
AFTER ADDING LEMMA
[
  [
    {
      "id": 1,
      "text": "puppies",
      "lemma": "puppy",
      "upos": "NOUN"
    }
  ]
]

Improving the Lemmatizer by Providing Key-Value Dictionary

It is possible to improve the lemmatizer by adding entries to its dictionary. The lemmatizer checks the dictionary first, and only uses the statistical model for words which are not in the dictionary.

The dictionary is stored in the model file as {upos: {word: lemma}}, compressed with gzip. The lemmatizer first looks for the word under its UPOS, then under the special key "*", which holds entries for any UPOS. Words are matched exactly, including capitalization, unless the model is caseless.

To add entries, load the model file, unpack the dictionary, add your entries, and save the model under a new name:

import gzip
import json
import os

import stanza
import torch

# find the lemmatizer model used by the default English pipeline
nlp = stanza.Pipeline('en', processors='tokenize,pos,lemma')
model_file = nlp.processors['lemma'].config['model_path']
customized_file = os.path.join(os.path.dirname(model_file), 'customized_lemmatizer.pt')

model = torch.load(model_file, map_location='cpu', weights_only=True)
pos_dict = json.loads(gzip.decompress(model['dicts']))

# myword as a NOUN has the lemma mylemma
pos_dict.setdefault('NOUN', {})['myword'] = 'mylemma'
# myword with any other UPOS has the lemma mylemma as well
pos_dict.setdefault('*', {})['myword'] = 'mylemma'

model['dicts'] = gzip.compress(json.dumps(pos_dict).encode('utf-8'))
torch.save(model, customized_file)

# load the customized model with Stanza
nlp = stanza.Pipeline('en', processors='tokenize,pos,lemma', lemma_model_path=customized_file)
print(nlp('myword'))  # should get lemma 'mylemma'

As can be seen in the result, Stanza should lemmatize the word myword as mylemma.

This dictionary format is used starting with Stanza 1.15. In 1.13 and earlier, model['dicts'] was a tuple of two dictionaries, one mapping (word, upos) to lemma and one mapping word to lemma. Models saved by 1.14 used a pickled version of the current format, which is no longer loaded for security reasons. Models from either version can be converted to the current format with stanza/utils/lemma/convert_lemma_dict.py.

Training-Only Options

Most training-only options are documented in the argument parser of the lemmatizer.

Training with an external dictionary

The scripts and options in this section are part of Stanza 1.15.1. Some changes on the dev branch are described in Coming soon.

A lemmatizer can be trained with an external lexicon as well as a treebank. The default English, German, Greek, Slovenian, and Spanish models do this, with the SPECIALIST Lexicon, German Wiktionary, Greek Wiktionary, Sloleks, and FreeLing. See Combined models for where those lexicons come from and the terms of their licenses.

The lexicon is used in two ways:

  • Every entry goes into the lemmatizer’s dictionary. Where the lexicon and the treebank disagree on the lemma for the same word and UPOS, the treebank’s lemma wins.
  • The seq2seq model also trains on the lexicon, mixed in with the treebank batches. This teaches it inflection patterns which the treebank has too few examples of, so it does better on words which are in neither one.

The lexicon is converted when the dataset is prepared. For de_combined, el_combined, en_combined, es_combined, and sl_combined, prepare_lemma_treebank reads the lexicon from extern_data and writes it next to the train, dev, and test files as {short_name}.dict.conllu:

DatasetLexiconExpected location
en_combinedinflVars.data from the 2026 SPECIALIST Lexicon releaseextern_data/english/specialist/inflVars.data
de_combinedde_wiki_lemmas.conllu.gz, already converted from German Wiktionaryextern_data/handparsed-treebank/german-lemmas-wiki/de_wiki_lemmas.conllu.gz
el_combinedel-extract.jsonl.gz, the kaikki.org extraction of Greek Wiktionaryextern_data/dictionary/greek/el-extract.jsonl.gz (.xz or uncompressed also work)
es_combinedA clone of FreeLing, whose Spanish dictionary is in data/es/dictionary/entriesextern_data/spanish/FreeLing/
sl_combinedSloleks 3.1 XML filesextern_data/slovenian/Sloleks.3.1/

The Greek lexicon is in $DICTIONARY_DIR, which defaults to extern_data/dictionary. Converting it also uses the UD_Greek-GDT training file in $UDBASE, as described in Checking the Greek conventions.

python3 -m stanza.utils.datasets.prepare_lemma_treebank en_combined

If the lexicon is missing, preparing the dataset stops with an error. To prepare it without the lexicon, use --no_external_dictionary, which also removes a dictionary file left from an earlier run.

run_lemma then uses data/lemma/{short_name}.dict.conllu automatically if it exists:

python3 -m stanza.utils.training.run_lemma en_combined
OptionScriptDescription
--no_external_dictionaryprepare_lemma_treebankDon’t write the lexicon for a dataset which has one, and remove an existing {short_name}.dict.conllu.
--secondary_filerun_lemmaUse this file as the external dictionary instead of the prepared one. This works for any dataset, not just the ones with a default lexicon.
--no_use_secondary_filerun_lemmaTrain without an external dictionary, even if one was prepared.
--secondary_raterun_lemma, lemmatizerHow many batches of the lexicon the seq2seq model trains on for each batch of the treebank. The default of 0.1 means one lexicon batch after every 10th treebank batch. Batches are counted in words, and the lexicon is reshuffled after each pass through it. 0 uses the lexicon only for the dictionary.

To use a lexicon of your own, write it as CoNLL-U with one word per sentence, filling in the form, lemma, and UPOS:

# sent_id = my_lexicon-NOUN-housewives
# text = housewives
1	housewives	housewife	NOUN	_	_	0	root	_	_

and pass it to run_lemma with --secondary_file.

Capitalized words

The dictionary is case-sensitive, so a word at the start of a sentence or in a headline, such as Beer or Comía, misses the entry for the lowercase word. For en_combined and es_combined, prepare_lemma_treebank also writes {short_name}.exact_dict.conllu, with the Capitalized and UPPERCASE forms of the lowercase words in the training data and the same lemmas: nouns for English, and nouns, verbs, auxiliaries, adjectives, and adverbs for Spanish. Single letters are left out, as are forms the training data already has with that UPOS. The entries come from the prepared training file, not from the lexicon.

These entries only apply to their exact word and UPOS. Each one takes precedence over the training data for that word and UPOS, but the same word with any other UPOS is looked up as before, so Rosa as a PROPN is still Rosa. The seq2seq model does not train on them. They are stored in the model’s dictionary, and the lookup when lemmatizing is the same, so they work with any version of Stanza which can load the model.

run_lemma passes data/lemma/{short_name}.exact_dict.conllu to the lemmatizer if it exists. The lemmatizer can also be given any CoNLL-U file in the same one word per sentence format as a lexicon, for entries which should only apply to their exact word and UPOS.

OptionScriptDescription
--no_exact_dictionaryprepare_lemma_treebankDon’t write the capitalized entries for a dataset which has them, and remove an existing {short_name}.exact_dict.conllu.
--exact_dict_filelemmatizerAdd the entries in this file to the dictionary for their exact word and UPOS only.

Checking the Spanish conventions

The FreeLing conversion changes some lemmas to match the conventions of GSD and AnCora, as described in Combined models. After writing the es_combined training data, prepare_lemma_treebank compares the converted dictionary with the training data on the words each of those changes applies to:

ConventionWords compared
-dora nouns have the -dora lemma (investigadoras → investigadora)NOUNs ending in -dora or -doras
-dora adjectives have the -dor lemma (conservadoras → conservador)ADJs ending in -dora or -doras
Feminine nouns have the feminine singular lemma (hermanas → hermana)NOUNs with Gender=Fem
Ordinals have the masculine singular ordinal as the lemma (primeras → primero)ADJs with NumType=Ord
bueno and malo have the lemmas buen and malADJ forms of bueno and malo

Only words in both the dictionary and the training data are compared, using the most frequent lemma in the training data for each word and UPOS. If any convention agrees on fewer than 90% of its words, or has no words to compare, preparing the dataset stops with a list of the words which disagree. That usually means a treebank has changed one of its conventions, and the rules in convert_es_freeling.py need to change to match. The check is skipped with --no_external_dictionary.

The first sentence of es_combined.dict.conllu records which version of FreeLing it was built from: # freeling_commit if the FreeLing directory is a git clone, and # freeling_entries_sha256, a hash of its dictionary files.

Checking the Greek conventions

The Greek Wiktionary conversion rewrites lemmas to follow UD_Greek-GDT, as described in Combined models. Most of the rewrites are fixed rules. The rest are counted from the GDT training file: when GDT gives most of the forms of a Wiktionary lemma a different lemma, at least twice, the Wiktionary lemma is replaced, such as λέω → λέγω. These are written next to the dictionary as el_combined.dict.rewrites.tsv, one per line as Wiktionary lemma, UPOS, and GDT lemma, so that each conversion leaves a record of them.

After writing the el_combined training data, prepare_lemma_treebank compares the converted dictionary with the training data in the same way as for Spanish, except that each convention has its own minimum. GDT is not consistent about participles itself, so those minimums are lower:

ConventionWords comparedMinimum
Passive verbs have the active lemma (δημιουργήθηκε → δημιουργώ)VERBs with Voice=Pass, other than participles85%
VERB participles have the verb as the lemma (κτισμένο → κτίζω)VERBs with VerbForm=Part ending in -μένος and its forms60%
ADJ participles have the participle as the lemma (αυξημένη → αυξημένος)ADJs ending in -μένος and its forms70%
Comparatives and superlatives have the positive as the lemma (μεγαλύτερο → μεγάλος)ADJs with Degree=Cmp or Degree=Sup70%
Contracted verbs have the -ώ lemma (μιλάει → μιλώ)VERBs whose lemma ends in -ώ or -άω85%

If a check fails, the rules in convert_el_wiktionary.py need to change to match the treebank. The check is skipped with --no_external_dictionary.

Updating a lexicon

After a lexicon is updated, prepare the dataset again and retrain the lemmatizer with run_lemma. extern_data is the default for $STANZA_EXTERN_DIR, extern_data/dictionary for $DICTIONARY_DIR, and extern_data/handparsed-treebank for $HANDPARSED_DIR.

  • SPECIALIST Lexicon (en_combined): download inflVars.data from the LEX_DOC/MISC directory of the new release, replacing extern_data/english/specialist/inflVars.data. The license requires the release number and date of the lexicon to be given with any distribution, so update the release in the table above and in Combined models when models built with it are released.
  • FreeLing (es_combined): run git pull in extern_data/spanish/FreeLing. The convention check runs when the dataset is prepared.
  • Greek Wiktionary (el_combined): download the latest el-extract.jsonl.gz from kaikki.org, replacing extern_data/dictionary/greek/el-extract.jsonl.gz. The convention check runs when the dataset is prepared, and comparing the new el_combined.dict.rewrites.tsv with the previous one shows which of the counted rewrites changed.
  • Sloleks (sl_combined): the converter reads extern_data/slovenian/Sloleks.3.1/, so a new version needs the directory in build_dictionary of convert_sl_sloleks.py changed, along with the citation in Combined models.
  • German Wiktionary (de_combined): the dump is converted ahead of time, and the result is kept in handparsed-treebank, so preparing de_combined doesn’t need the dump or the parser library. To rebuild it, install the wiktionary extra, which needs Python 3.13 or later (pip install -e '.[wiktionary]' from a git checkout of Stanza), download the latest dewiktionary-latest-pages-articles-multistream.xml.bz2 from Wikimedia dumps, and run

    python3 -m stanza.utils.datasets.lemma.convert_de_wiktionary dewiktionary-latest-pages-articles-multistream.xml.bz2 de_wiki_lemmas.conllu.gz
    

    then replace german-lemmas-wiki/de_wiki_lemmas.conllu.gz in handparsed-treebank with the new file. The converter is written for version 0.16.0 of wiktionary-de-parser, whose output has changed between versions, and stops if a different version is installed unless given --allow_other_parser_version.

Adding a lexicon

A lexicon for another dataset needs a license which allows the converted entries to be distributed as part of a model. To add one:

  1. Write a converter in stanza/utils/datasets/lemma, named after the language and the lexicon, such as convert_es_freeling.py. It needs a build_dictionary(paths, output_filename) function which reads the lexicon from a directory named after the language in paths["DICTIONARY_DIR"], such as greek, and writes one word per sentence in the format above. If the lexicon is missing, it should raise FileNotFoundError with where to download it.
  2. Map the lexicon’s categories to UPOS, and change its lemmas to match the treebank’s conventions. Comparing the converted entries with the training data, on the words in both and on the dev set words the training data doesn’t have, turns up most of the differences. Drop a word and UPOS with more than one lemma rather than choosing one, and leave out the closed classes, which the treebank already covers.
  3. Add the dataset and its build_dictionary to EXTERNAL_DICTIONARIES in prepare_lemma_treebank.py. If any of the lemma rules depend on a treebank convention which might change, also add a check to EXTERNAL_DICTIONARY_CHECKS, such as convert_es_freeling.check_conventions. It is run as check_fn(train_file, dict_file) after the training data is written, and should raise an exception if the conventions no longer match.
  4. For the capitalized entries, add the dataset to EXACT_DICTIONARIES, with the UPOS tags to build them for.
  5. Add the lexicon to the table above, and describe its source, its license, and the modifications made to it in Combined models.

Coming soon

These changes are on the dev branch, and will be part of the next code release.

The English, Slovenian, and Spanish lexicons are read from $DICTIONARY_DIR along with the Greek one, so that all of them can be kept in one directory, such as a shared one on a cluster. They keep the same layout:

DatasetExpected location
en_combinedextern_data/dictionary/english/specialist/inflVars.data
es_combinedextern_data/dictionary/spanish/FreeLing/
sl_combinedextern_data/dictionary/slovenian/Sloleks.3.1/

The German file stays in handparsed-treebank.

Each converter writes comments at the start of the first sentence of the dictionary which record the version of the lexicon it was built from. For the SPECIALIST Lexicon, Sloleks, and both Wiktionary dumps, these are a sha256 of the input files and their latest modification date, such as

# specialist_sha256 = 3f2a...
# specialist_modified = 2026-01-15

with the prefixes specialist, sloleks, kaikki, and dewiktionary. For a downloaded file, the modification date is the server’s date for it if the download kept it, as wget does, and otherwise the date it was downloaded. The FreeLing dictionary also has # freeling_commit_date along with the commit.

The lemmatizer keeps these comments from its --secondary_file in the model’s config as secondary_file_source, so a model records which version of the lexicon it was trained with, even after the dictionary file is rebuilt. A lexicon of your own can record its source the same way, with comments before the first word. To see it for a model:

import torch
model = torch.load("saved_models/lemma/en_combined_charlm_lemmatizer.pt", weights_only=True)
print(model['config'].get('secondary_file_source'))

Models trained without this have no secondary_file_source, so this prints None.

Contextual Classifier

As of Stanza 1.10, there is a contextual classifier for ambiguous words whose lemma can be determined by context. For example, in English, the token 's as an AUX can either represent is or has, with the lemma be or have respectively.

The POS is enough to tell apart many ambiguous lemmas, so the contextual classifier is only needed where the two lemmas have the same UPOS. In English, the ambiguity of 's as an AUX or as a possessive PART was never an issue. The classifier also needs enough examples of each lemma in the training data to give reasonable results. Other ambiguous English words, such as saw, wound, and found, don’t have enough examples in the treebanks.

The default models for these languages have a contextual classifier:

LanguageDatasetsWordsUPOSLemmas
Arabicar_padtأنSCONJأَن, أَنَّ
Englishen_combined'sAUXbe, have
Englishen_combinedherPRONher (possessive), she (object)
Greekel_combined, el_gdtτους, μας, του, της, σας, μουPRONμου, εγώ
Hindihi_hdtbकेADPका, के
Japaneseja_combined, ja_gsdだAUXだ, た
Persianfa_perdtشدVERBشد, کرد
Sloveniansl_combined, sl_ssjrok, roka, roke, rokiNOUNrok, roka
Sloveniansl_combined, sl_ssjdela, delu, delom, delih, deliNOUNdel, delo

The classifier is stored in the lemmatizer’s model file, and uses the language’s word vectors, which are downloaded along with the lemmatizer.

When training a lemmatizer for one of these datasets, run_lemma builds the classifier from the data prepared by prepare_lemma_treebank and attaches it to the lemmatizer: the charlm lemmatizer, or the nocharlm lemmatizer if the language has no charlm. --no_lemma_classifier turns this off. The datasets and target words are in DATASET_MAPPING and DATASET_TARGETS in stanza/utils/datasets/prepare_lemma_classifier.py, along with notes on other candidates found in the UD treebanks. Suggestions, or data for ambiguous words which don’t have enough examples yet, are welcome.