Skip to content

Latest commit

 

History

History
175 lines (137 loc) · 8.41 KB

README.md

File metadata and controls

175 lines (137 loc) · 8.41 KB

Reproducible miniature examples

These tiny corpora demonstrate the APIs and file formats. Their statistics are not representative language models. Run commands from the project root after installing the package, or set PYTHONPATH=src for a source checkout.

Build all examples

python examples/train_examples.py

This writes word models (orders 1–3), syllable models (including order 7), and dense character models with a legacy CTLS-compatible prefix to examples/generated/. It also builds the two custom-marker/punctuation models described below: eleven miniature models in total.

Word models and sentence boundaries

python -m languagestatisticslibpy train --input examples/words_en.txt --output-dir word_models --unit word --language en --orders 1 2 3 --storage sparse
python -m languagestatisticslibpy inspect word_models/en-word-2gram.ctwm --top 5

The word-training CLI enables <START> and <END> by default. When using the Python API, set sentence_boundaries=True explicitly. The sample produces two occurrences of ("I", "am") and two of ("<START>", "I").

The default sentence splitter recognizes ., !, ? and blank lines, without special knowledge of abbreviations or decimals. Use --sentence-per-line for already segmented sentence files or add_tokens() for exact external NLP segmentation. The program processes corpus files as bounded paragraphs; wrapped lines remain together, while blank lines and separate files reset the sequence.

Explicit syllable inventory

python -m languagestatisticslibpy train --input examples/syllables.txt --output-dir syllable_models --unit syllable --vocabulary examples/syllable_inventory.json --orders 1 2 3 7 --sentence-per-line --storage sparse

Whitespace-separated syllables are the default. For unsegmented input, --syllable-mode greedy selects the longest matching inventory entry; that algorithm is deterministic and must be validated against the desired linguistic rules. Normalization and case settings are applied equally to inventory and corpus. Choose --unknown boundary to skip windows containing unknown material without joining tokens across it, or --unknown unk to count <UNK> explicitly.

Custom sentence markers and selected punctuation

Run the complete, hand-checked Python example:

python examples/train_punctuation_examples.py

It uses the following independent inputs:

File Purpose
punctuation_tokens.json Retain ,, ., !, ? as separate tokens.
sentence_endings.json End a sentence at ! or ?.
words_punctuation_en.txt Two short English sample sequences.
syllables_punctuation.txt Two invented syllable sequences, including attached punctuation.
syllable_inventory.json Fixed lexical inventory: La, Le, Li, Lo, Lu.

The point of the two JSON lists is that retaining a symbol and treating it as a sentence boundary are separate decisions. This example deliberately retains the period without treating it as a boundary. For the usual ., !, ? boundaries, omit sentence_endings or include all three in the list. An empty ending list disables punctuation-based splitting; blank lines can still separate sequences.

The relevant Python configuration is the same for both units:

from languagestatisticslibpy import NGramTrainer

trainer = NGramTrainer(
    orders=(2,),
    unit="word",                    # or unit="syllable" with a syllable inventory
    sentence_boundaries=True,
    start_token="<SENTENCE_START>",
    end_token="<SENTENCE_END>",
    punctuation=[",", ".", "!", "?"],
    sentence_endings=["!", "?"],
)
trainer.add_text("I think, therefore I am. Really!")

Without custom labels, the markers are <START> and <END>. They are ordinary vocabulary entries with their own integer IDs; their structural role and exact labels are also recorded in model metadata. The trainer inserts them automatically. Do not insert marker strings into the raw corpus yourself. Changing the label does not change the counting or lookup rule. The default adds one start and one end marker per sequence; pad_start=True adds n-1 start markers for each order instead. No window crosses into the next sentence.

The word corpus becomes these two token sequences:

<SENTENCE_START> I think , therefore I am . Really ! <SENTENCE_END>
<SENTENCE_START> I am a human ? <SENTENCE_END>

It produces 16 bigram windows and 14 distinct observed bigrams. In particular, ("I", "am") and ("<SENTENCE_START>", "I") each occur twice; (".", "Really") and ("!", "<SENTENCE_END>") each occur once. The saved sparse word model is generated/demo-en-punctuation-word-2gram.ctwm.

The syllable example uses longest-match (greedy) segmentation of La,Le.Li! and LaLo?. The selected punctuation is added to the fixed inventory; you do not have to duplicate it in the syllable JSON file. The resulting sequences are:

<SENTENCE_START> La , Le . Li ! <SENTENCE_END>
<SENTENCE_START> La Lo ? <SENTENCE_END>

It produces 11 bigram windows and 10 distinct observed bigrams. ("<SENTENCE_START>", "La") occurs twice, while ("La", "Lo"), (".", "Li") and ("!", "<SENTENCE_END>") each occur once. The saved dense model is generated/demo-punctuation-syllable-2gram.ctls2. The script checks every hand-counted bigram after saving and loading both files. These small invented inputs demonstrate tokenization and serialization, not linguistic quality or automatic linguistic syllabification.

Equivalent CLI configurations:

python -m languagestatisticslibpy train --input examples/words_punctuation_en.txt --output-dir punctuation_word_models --unit word --language en --orders 2 --storage sparse --sentence-boundaries --start-token '<SENTENCE_START>' --end-token '<SENTENCE_END>' --punctuation-file examples/punctuation_tokens.json --sentence-endings-file examples/sentence_endings.json
python -m languagestatisticslibpy train --input examples/syllables_punctuation.txt --output-dir punctuation_syllable_models --unit syllable --language demo --vocabulary examples/syllable_inventory.json --syllable-mode greedy --orders 2 --storage dense --sentence-boundaries --start-token '<SENTENCE_START>' --end-token '<SENTENCE_END>' --punctuation-file examples/punctuation_tokens.json --sentence-endings-file examples/sentence_endings.json

Use punctuation=True or --include-punctuation for the common punctuation preset. An explicit list keeps only those symbols; other punctuation acts as a discarded separator. An empty list selects none. Internal word apostrophes and hyphens remain inside words by default, even when selected. Set split_word_joiners=True or --split-word-joiners to emit selected internal joiners separately. With punctuation=None (the default), the previous tokenization behavior is retained. add_tokens() always accepts an explicit token sequence and does not apply the raw-text punctuation filter.

Selected sentence-end punctuation precedes the end marker; selected adjacent closing quotes/brackets are retained before that marker as well. The sentence splitter is a configurable punctuation rule without abbreviation or decimal recognition. Use sentence_per_line=True / --sentence-per-line or add_tokens() when segmentation has already been done elsewhere.

Character statistics compatible with old readers

python -m languagestatisticslibpy train --input examples/characters.txt --output-dir character_models --unit character --vocabulary examples/character_inventory.json --orders 2 3 --storage dense --language demo --legacy-compatible
python -m languagestatisticslibpy convert character_models/demo-character-2gram.ctls2 character_models/demo-2gram-nocs.gz --format ctls

Only eligible dense character models can have a legacy-compatible prefix. CTLS1 export intentionally cannot represent multi-character syllable tokens, word vocabularies or retained raw counts.

Preparing a hot lookup loop

from languagestatisticslibpy.formats import load_model

model = load_model("word_models/en-word-2gram.ctwm")
ids = model.encode_tokens(["I", "am"])
key = model.encode_key(ids)
score = model.lookup_key(key)
count = model.count_tokens(["I", "am"])

Map text and token strings to IDs outside the cryptanalysis loop. Prepared numeric keys use the model's dense array or sparse dictionary directly. The model stores log-frequency scores with an unseen count floor of one. This is a scoring convention, not a smoothed conditional probability language model.