papie lemmatization · tagging · any language

Data

TSV reader, label encoders, the Lightning data module, input noise and rare-label sampling.

Generated from the source by tools/make_api.py; do not edit by hand.

papie.data.label_encoder

Original code from pie.data.dataset (LabelEncoder, MultiLabelEncoder): https://github.com/emanjavacas/pie/blob/master/pie/data/dataset.py

identity

identity(*args)

compose

compose(*fns)

class LabelEncoder (object)

LabelEncoder(self, level='token', name=None, lower=False, utfnorm=False, utfnorm_type='NFKD', drop_diacritics=False, max_size=None, min_freq=1, pad=True, eos=False, bos=False, mask=False, encoding='char', reserved=(), **meta)
Label encoder

LabelEncoder.get_type_stats

get_type_stats(self)
Compute number of known types, total number of types and ratio

LabelEncoder.get_token_stats

get_token_stats(self)
Compute number of known tokens, total number of types and ratio

LabelEncoder.add

add(self, seq)

LabelEncoder.compute_vocab

compute_vocab(self)

LabelEncoder.expand_vocab

expand_vocab(self)

LabelEncoder.register_upper

register_upper(self)
Params registers the same vocabulary but in full uppercase

Important when using the upper strategy

LabelEncoder.preprocess_text

preprocess_text(self, seq)
Apply surface level preprocessing such as lowering, unicode normalization

LabelEncoder.preprocess

preprocess(self, tseq)
Full preprocessing pipeline including possible token-level transformations

LabelEncoder.transform

transform(self, seq)

LabelEncoder.inverse_transform

inverse_transform(self, seq)

LabelEncoder.stringify

stringify(self, seq, length=None)

LabelEncoder.get_pad

get_pad(self)

LabelEncoder.get_eos

get_eos(self)

LabelEncoder.get_bos

get_bos(self)

LabelEncoder.get_unk

get_unk(self)

LabelEncoder.get_mask

get_mask(self)

LabelEncoder.jsonify

jsonify(self)

LabelEncoder.from_json

from_json(cls, obj)

class MultiLabelEncoder (object)

MultiLabelEncoder(self, tasks: List[Task], word_max_size=None, word_min_freq=1, word_lower=False, char_max_size=None, char_min_freq=None, char_lower=False, char_eos=True, char_bos=True, char_encoding='char', **sublekwargs)
Complex Label encoder for all tasks.

MultiLabelEncoder.all_label_encoders

all_label_encoders(self)

MultiLabelEncoder.set_tasks

set_tasks(self, tasks)

MultiLabelEncoder.add_task

add_task(self, name, **meta)

MultiLabelEncoder.fit

fit(self, lines, expand_mode=False, skip_fitted=False)
Fit all LabelEncoder objects contained in this instance on the given data to create their label-to-id tables

Parameters
===========
lines (iterator): tuples of (Input, Tasks)
expand_mode (bool): True to continue fitting all LabelEncoders with new data,
    keeping all labels already assigned and adding new ones as seen in the new data.
skip_fitted (bool): True to skip already fitted label encoders instead of raising an error.
    skip_fitted and expand_mode are exclusive.

MultiLabelEncoder.fit_reader

fit_reader(self, reader, expand_mode=False, skip_fitted=False)
fit reader in a non verbose way (to warn about parsing issues)

MultiLabelEncoder.set_known_and_ambiguous_tokens

set_known_and_ambiguous_tokens(self, train_reader)
Retrieves known and ambiguous token for all label encoders, for one dataset

:param train_reader: instance of a subclass of papie.data.dataset.dataset_base.Reader
:return: Known set of tokens, ambiguous token par task (Dict[task, Set[str])

MultiLabelEncoder.transform

transform(self, sents: Union[List[Sentence], List[Tuple[Sentence, DictGT]]])
Parameters
===========
sents : list of Example's

Returns
===========
tuple of (word, char), task_dict

    - word: list of integers
    - char: list of integers where each list represents a word at the
        character level
    - task_dict: Dict to corresponding integer output for each task

MultiLabelEncoder.jsonify

jsonify(self)

MultiLabelEncoder.save

save(self, path)

MultiLabelEncoder.from_dict

from_dict(cls, contents)

MultiLabelEncoder.from_json

from_json(cls, path)

papie.data.dataset.datamodule

class PieDataModule (L.LightningDataModule)

PieDataModule(self, path_train, path_val, path_test, tasks: List[Task], multilabelencoder: dict, dataset_params: dict, reader_params: dict, dataloader_hparams: dict, sampling: Optional[dict]=None, noise: Optional[dict]=None)
sampling: up-sample sentences with rare labels in the training set (see
papie.data.sampling). noise: input-noise strategies for the training set only
(see papie.data.noise). Both are top-level data keys so a small yaml can be layered
on any config with -c.

PieDataModule.get_subset_opts

get_subset_opts(opts, subset)

PieDataModule.prepare_data

prepare_data(self)

PieDataModule.setup

setup(self, stage: str)

PieDataModule.train_dataloader

train_dataloader(self)

PieDataModule.val_dataloader

val_dataloader(self)

PieDataModule.test_dataloader

test_dataloader(self)

class DataCollatorForPIE

DataCollatorForPIE(self, label_encoder: MultiLabelEncoder)
Data collator for PieDataset inputs


for input = {
    "raw_words": list sent_words,
    "word_ids": list word_ids,
    "word_lengths": int len(sent_words),
    "char_ids": list char_ids,
    "char_lengths": list char_lengths,
    "raw_tasks": dict {task: list sent_task_labels},
    "tasks_encoded": dict {task: list task_encoded}
}
returns:
batch = {
    "raw_words": list [sent_1_words, sent_2_words, ...],
    "word_ids": padded tensor [word_ids_1, word_ids_2, ...],
    "word_lengths": tensor [len(sent_1_words),len(sent_2_words)],
    "char_ids": padded tensor [char_ids_1, char_ids_2, ...],
    "char_lengths": padded tensor [char_lengths_1, char_lengths_2, ...],
    "raw_tasks": dict {task: list [sent_1_task_labels, sent_2_task_labels, ...]},
    "tasks_encoded": dict {task: padded tensor [task_encoded_1, tasks_encoded_2, ...]
}

papie.data.dataset.dataset_tsv

class TSVReader (Reader)

TSVReader(self, path, tasks, sep='\t', tasks_columns: dict=None, header=None, encoding='utf-8', max_sents=None)

TSVReader.check_tasks

check_tasks(self)

TSVReader.readsents

readsents(self)

split_lengths

split_lengths(forms, max_len, split_chars=None, min_ratio=0.25)
Chunk lengths for a sentence of forms (one string per token) longer than max_len.

Without split_chars the sentence is cut every max_len tokens. With it, each cut is moved back
to just after the last token whose *last character* is in split_chars (punctuation, also when glued
to the word), provided that leaves a chunk of at least min_ratio * max_len tokens; otherwise the cut
stays at max_len.

class PieDatasetFromTSV (PieDataset, TSVReader)

PieDatasetFromTSV(self, path, tasks_names, label_encoder, sep='\t', tasks_columns: dict=None, header=None, max_sents=None, max_sent_len=None, encoding='utf-8', noise=None, split_chars=None)
noise: input-noise strategies applied to the words of each sample (see
papie.data.noise); labels are never changed. Set it for the training set only.

PieDatasetFromTSV.sentence_labels

sentence_labels(self, task)
Gold labels of task for every sample, in dataset order (one pass over the file).

PieDatasetFromTSV.create_sent_start_index

create_sent_start_index(self)
Offsets of all samples (sentences are split across multiple lines, 1 per token).

A sentence longer than max_sent_len tokens is cut into chunks (split_lengths), each indexed
as its own sample; self.sent_lengths[i] is the number of tokens of sample i.

papie.data.dataset.dataset_base

class Reader (ABC)

Reader(self, path, tasks, encoding='utf-8', max_sents=None)

Reader.check_tasks

check_tasks(self)

class PieDataset (Reader, Dataset)

PieDataset(self, path, tasks, label_encoder, max_sents=None, max_sent_len=None, encoding='utf-8')

papie.data.noise

Input noise for training (data augmentation): the input words are perturbed, the gold labels are not.

Configure under data.noise (training set only)::

  data:
    noise:
        uppercase:      {ratio: 0.1}                      # whole sentence in capitals (PaPie's strategy)
        titlecase:      {ratio: 0.1, word_ratio: 0.3}     # capitalise some words
        drop_diacritics: {ratio: 0.1, word_ratio: 0.5}    # strip combining marks
        char_noise:     {ratio: 0.1, char_ratio: 0.03, ops: [delete, duplicate, swap, substitute]}
        char_map:       {ratio: 0.2, word_ratio: 0.5, map: {u: v, v: u, i: j, j: i}}   # orthographic variants

ratio is the probability that a strategy is applied to a given sentence; the other ratios act inside the
sentence. Strategies run in the order listed. With a character (non-byte) vocabulary, uppercase and
titlecase need the upper-case characters in the vocabulary (multilabelencoder.noise_strategies.uppercase
registers them, as in PaPie); byte encoding needs nothing.

uppercase

uppercase(words, rng, **_)

lowercase

lowercase(words, rng, **_)

titlecase

titlecase(words, rng, word_ratio=0.3, **_)

drop_diacritics

drop_diacritics(words, rng, word_ratio=0.5, **_)

char_noise

char_noise(words, rng, char_ratio=0.03, ops=('delete', 'duplicate', 'swap', 'substitute'), **_)

char_map

char_map(words, rng, map=None, word_ratio=0.5, char_ratio=1.0, **_)

validate

validate(noise: Optional[dict])

apply_noise

apply_noise(words: List[str], noise: Optional[dict], rng: Optional[random.Random]=None) -> List[str]
Return the (possibly) perturbed copy of a sentence's words; noise as described above.

papie.data.sampling

Training-set sampling that up-samples sentences containing rare labels (typically rare lemmas).

Configure under data.sampling (training set only)::

  data:
    sampling:
        task: lemma            # task whose label frequencies drive the weights
        method: power          # power | threshold
        alpha: 0.5             # power: token weight = (freq / median freq) ** -alpha
        rare_threshold: 5      # threshold: labels seen <= this many times are rare
        boost: 4.0             # threshold: weight of a rare token
        aggregate: max         # sentence weight from its tokens: max | mean
        max_weight: 10         # clip token weights to [1, max_weight]
        epoch_size: null       # sentences drawn per epoch (default: the training-set size)

Sentences are drawn with replacement in proportion to their weight, so rare labels are seen more often per
epoch and frequent ones slightly less. describe reports the effect before training starts.

label_frequencies

label_frequencies(sent_labels: Sequence[Sequence[str]]) -> Counter

sentence_weights

sentence_weights(sent_labels: Sequence[Sequence[str]], method='power', alpha=0.5, reference_count=50, rare_threshold=5, boost=4.0, aggregate='max', max_weight=10.0) -> List[float]

describe

describe(sent_labels: Sequence[Sequence[str]], weights: Sequence[float], rare_threshold=5) -> Dict[str, float]
Expected share of rare-label tokens per epoch, uniform vs weighted sampling.