Source code for pie_extended.pipeline.tokenizers.learned

""" A segmenter that learns where a treebank cuts words, shared by the languages that need it.

Some treebanks make several words of one written word (`զմեղս` -> `զ`, `մեղս`), and models trained on them expect the
same cuts. When no rule can say where (many words legitimately start with the same letters as a proclitic), the cuts are
learned: an averaged perceptron decides, for each position inside a word, whether the treebank cuts there, from the
characters around it (and from the word itself, which makes it a lexicon for the known words).

A language gives its data, nothing more: the letters of its words (`WORD`), its tokenizer (to know the tokens that are to
be cut), and the treebank it learns from (`learn`). Classical Armenian is the first one: `pie_extended.models.hy_xcl`.

The weights are learned *on the machine of the user*, they are not distributed when the license of the treebank (NC, SA...)
would be inherited by a file derived from it.

>>> class Letters(LearnedSegmenter):
...     WORD = re.compile(r"^[a-z]+$")
>>> examples = [("inthe", {2}), ("inside", {2}), ("home", set()), ("inform", {2}), ("hotel", set())] * 4
>>> segmenter = Letters.train(examples, epochs=6)
>>> segmenter.cuts("inthe"), segmenter.cuts("hotel")
([2], [])
>>> segmenter.split("inside")
['in', 'side']
"""
import collections
import json
import os
import random
import tempfile
import warnings
from typing import Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Set, Tuple

import regex as re


[docs] def features(word: str, position: int) -> List[str]: """ Features of the position between `word[:position]` and `word[position:]` """ word = word.lower() left, right = word[:position], word[position:] return [ "bias", "word=%s|%d" % (word, position), # What was seen for this very word: a lexicon "L1=" + left[-1:], "L2=" + left[-2:], "L3=" + left[-3:], "R1=" + right[:1], "R2=" + right[:2], "R3=" + right[:3], "L1R1=%s|%s" % (left[-1:], right[:1]), "start=%d" % min(position, 4), "end=%d" % min(len(word) - position, 4), "left=" + (left if len(left) <= 4 else "_"), "right=" + (right if len(right) <= 4 else "_"), "len=%d" % min(len(word), 10), ]
[docs] def read_conllu(path: str) -> Iterator[Tuple[str, List[str]]]: """ Sentences of a CoNLL-U file: the text, and the words (multiword token ranges and empty nodes are skipped) """ text, words = None, [] with open(path, encoding="utf-8") as f: for line in f: line = line.rstrip("\n") if line.startswith("# text ="): text = line[len("# text ="):].strip() elif not line.strip(): if text is not None: yield text, words text, words = None, [] elif not line.startswith("#"): columns = line.split("\t") if columns[0].isdigit(): words.append(columns[1]) if text is not None: yield text, words
[docs] class LearnedSegmenter: """ Gives where a word has to be cut. A language sets `WORD`: only words that match it can be cut """ WORD = re.compile(r"^\w+$") def __init__(self, weights: Optional[Dict[str, float]] = None): self.weights: Dict[str, float] = weights or {}
[docs] def cuts(self, word: str) -> List[int]: """ Positions (between characters) where `word` is cut """ if len(word) < 2 or not self.WORD.match(word): return [] weights = self.weights return [ position for position in range(1, len(word)) if sum(weights.get(feature, 0.0) for feature in features(word, position)) > 0 ]
[docs] def split(self, word: str) -> List[str]: bounds = [0] + self.cuts(word) + [len(word)] return [word[start:end] for start, end in zip(bounds, bounds[1:])]
[docs] def save(self, path: str) -> None: os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) with open(path, "w", encoding="utf-8") as f: json.dump({"version": 1, "weights": {k: round(v, 4) for k, v in self.weights.items() if abs(v) >= 1e-4}}, f, ensure_ascii=False)
[docs] @classmethod def load(cls, path: str) -> "LearnedSegmenter": with open(path, encoding="utf-8") as f: return cls(json.load(f)["weights"])
[docs] @classmethod def load_or_warn(cls, path: str, warning: str, warn: bool = True) -> Optional["LearnedSegmenter"]: """ The segmenter that was learned, or None (with `warning`) if it was not """ if os.path.exists(path): return cls.load(path) if warn: warnings.warn(warning, UserWarning, stacklevel=3) return None
[docs] @classmethod def train(cls, examples: Sequence[Tuple[str, Set[int]]], epochs: int = 8, seed: int = 0) -> "LearnedSegmenter": """ Averaged perceptron :param examples: A word, and the positions where it has to be cut """ data = [(word, set(cuts)) for word, cuts in examples if len(word) > 1 and cls.WORD.match(word)] weights: Dict[str, float] = collections.defaultdict(float) totals: Dict[str, float] = collections.defaultdict(float) stamps: Dict[str, int] = collections.defaultdict(int) step = 0 shuffler = random.Random(seed) for _ in range(epochs): shuffler.shuffle(data) for word, gold in data: for position in range(1, len(word)): step += 1 # Every instance counts for the average, not only the mistakes feats = features(word, position) expected = position in gold if (sum(weights.get(f, 0.0) for f in feats) > 0) != expected: update = 1.0 if expected else -1.0 for f in feats: totals[f] += (step - stamps[f]) * weights[f] stamps[f] = step weights[f] += update averaged = {f: (totals[f] + (step - stamps[f]) * w) / max(1, step) for f, w in weights.items()} return cls(averaged)
[docs] @staticmethod def training_examples(sentences: Iterable[Tuple[str, List[str]]], tokenizer) -> List[Tuple[str, Set[int]]]: """ Where the treebank cuts the words, for the tokens of our tokenizer (**without** any segmentation) A sentence is skipped if our tokens cannot be rebuilt from its words (different spelling, for example). """ examples: List[Tuple[str, Set[int]]] = [] for text, words in sentences: tokenizer.reset() tokens = tokenizer.word_tokenizer(text) found: List[Tuple[str, Set[int]]] = [] index = 0 for token in tokens: written, cuts = "", set() while written != token and index < len(words) and len(written) < len(token): if written: cuts.add(len(written)) written += words[index] index += 1 if written != token: found = [] break found.append((token, cuts)) examples.extend(found) return examples
[docs] def evaluate(self, sentences: Sequence[Tuple[str, List[str]]], make_tokenizer: Callable[..., object]) -> Dict[str, float]: """ Scores on sentences of a treebank :param make_tokenizer: Makes the tokenizer of the language: `make_tokenizer()` without segmentation, and `make_tokenizer(segmenter=...)` with it :return: Precision, recall and F1 of the cut points, share of words cut as in the treebank, and share of sentences whose words are exactly the ones of the treebank """ true = false = missed = words_ok = words = 0 for word, gold in self.training_examples(sentences, make_tokenizer()): predicted = set(self.cuts(word)) true += len(predicted & gold) false += len(predicted - gold) missed += len(gold - predicted) words_ok += predicted == gold words += 1 tokenizer = make_tokenizer(segmenter=self) exact = 0 for text, gold_words in sentences: tokenizer.reset() exact += tokenizer.word_tokenizer(text) == gold_words precision = true / max(1, true + false) recall = true / max(1, true + missed) return { "precision": precision, "recall": recall, "f1": 2 * precision * recall / max(1e-9, precision + recall), "words_exact": words_ok / max(1, words), "sentences_exact": exact / max(1, len(sentences)), }
[docs] def learn(segmenter: type, treebank: Mapping[str, str], make_tokenizer: Callable[..., object], path: str, download: Callable[[str, str], None]) -> LearnedSegmenter: """ Learns where a treebank cuts the words, and keeps what was learned (a few seconds) :param segmenter: The class of the language (a `LearnedSegmenter`) :param treebank: The URL of the CoNLL-U file for each of `train`, `dev` and `test` :param make_tokenizer: The tokenizer of the language, see `LearnedSegmenter.evaluate` :param path: Where to keep the weights :param download: `download(url, filename)` """ with tempfile.TemporaryDirectory() as directory: sentences = {} for split, url in treebank.items(): filename = os.path.join(directory, split + ".conllu") download(url, filename) sentences[split] = list(read_conllu(filename)) def examples(*splits): return segmenter.training_examples([s for split in splits for s in sentences[split]], make_tokenizer()) # Honest score: what the segmenter does on sentences it has not seen scores = segmenter.train(examples("train")).evaluate(sentences["test"], make_tokenizer) print("Test set of the treebank: cut points F1 = {:.1f}% (P = {:.1f}%, R = {:.1f}%), " "sentences with exactly the words of the treebank: {:.1f}%".format( 100 * scores["f1"], 100 * scores["precision"], 100 * scores["recall"], 100 * scores["sentences_exact"])) # The one that is kept learns from all that is not the test set learned = segmenter.train(examples("train", "dev")) learned.save(path) print("Saved in " + path) return learned