v2026.11.3
All Bundles
Bundle

Natural language processing toolkit. Provides tokenization, text preprocessing, TF-IDF vectorization, cosine similarity, and sentiment analysis. Works with plain strings — no external model required. Compile with -lib nlp.

TF_IDF

Term Frequency-Inverse Document Frequency (TF-IDF) vectorizer for document analysis. By default IDF is smoothed as scikit-learn's is, ln((1 + N) / (1 + df)) + 1, and vectors are scaled to unit length, so the cosine similarity of two of them is their dot product.

A term is a word, or, with a min_n/max_n range as scikit-learn's ngram_range, a run of words joined by a space ("not very good"). Vocabulary, document frequencies, smoothed IDF and unit-length vectors follow TfidfVectorizer; two differences: words come from Tokenizer->WordTokenize (which keeps one-letter words) and the term frequency is a share of the document's terms rather than a raw count, which unit length cancels.

Example

documents := ["The cat sat on the mat", "The dog sat on the log", "Cats and dogs are pets"];
tfidf := System.NLP.TF_IDF->New(stem : true);
tfidf->Fit(documents);

a := tfidf->Transform("The cat and the dog");
b := tfidf->Transform("cats and dogs");
System.NLP.TextSimilarity->CosineSimilarity(a, b)->PrintLine();

Operations

EstimateDenseBytes #

The memory a dense TransformAll of some documents needs: 8 bytes times the vocabulary times the documents. Ask before transforming a large corpus.

method : public : EstimateDenseBytes(documents:Int) ~ Int

Parameters

NameTypeDescription
documentsInthow many documents

Return

TypeDescription
Intthe estimate in bytes; 0 when not fitted

Fit #

Fits the TF-IDF model on a corpus of documents, replacing any earlier fit

method : public : Fit(documents:String[]) ~ Bool

Parameters

NameTypeDescription
documentsStringarray of document strings

Return

TypeDescription
Booltrue when a vocabulary was built; false (see GetError) for an invalid setting, a Nil or empty corpus, or a corpus with no term left after min_df and stopwords. A statement call `tfidf->Fit(docs);` still compiles

Example

docs := ["the cat sat on the mat", "the dog ran in the park", "cats and dogs are pets"];
tfidf := TF_IDF->New();
if(<>tfidf->Fit(docs)) {
  tfidf->GetError()->PrintLine();
};
"Vocabulary size: {$tfidf->GetVocabularySize()}"->PrintLine();

# words and word pairs, as scikit-learn's ngram_range=(1, 2)
bigrams := TF_IDF->New(min_n : 1, max_n : 2);
bigrams->Fit(docs);
bigrams->GetVocabulary()->Has("the cat")->PrintLine();

FitTransform #

Fits on a corpus and transforms the same corpus: one row per document.

method : public : FitTransform(documents:String[]) ~ Float[,]

Parameters

NameTypeDescription
documentsStringthe documents

Return

TypeDescription
Float[documents, vocabulary size], or Nil when Fit fails or the matrix would exceed the dense limit (see GetError, EstimateDenseBytes)

Example

X := TF_IDF->New(min_n : 1, max_n : 2, min_df : 2)->FitTransform(texts);

GetError #

Why the vectorizer is not valid, or why the last Fit or TransformAll failed.

method : public : GetError() ~ String

Return

TypeDescription
Stringthe reason; "" when there is nothing to report (never Nil)

GetIdf #

Gets the inverse document frequency of each vocabulary word, indexed as the vocabulary is

method : public : GetIdf() ~ Float[]

Return

TypeDescription
Floata copy of the IDF vector

Example

idf := tfidf->GetIdf();
idx := tfidf->GetVocabulary()->Find("cat")->Get();
"IDF of cat: {$(idf[idx])}"->PrintLine();

GetMaxDenseBytes #

The dense-matrix limit of TransformAll.

method : public : GetMaxDenseBytes() ~ Int

Return

TypeDescription
Intbytes

GetMaxN #

The longest term, in words.

method : public : GetMaxN() ~ Int

Return

TypeDescription
Intmax_n

GetMinN #

The shortest term, in words.

method : public : GetMinN() ~ Int

Return

TypeDescription
Intmin_n

GetVocabulary #

Gets the vocabulary (word to index mapping)

method : public : GetVocabulary() ~ Hash<String,IntRef>

Return

TypeDescription
Hash<String,IntRef>vocabulary hash map

Example

vocab := tfidf->GetVocabulary();
keys := vocab->GetKeys()<String>;
each(k in keys) {
  k->PrintLine();
};

GetVocabularySize #

Gets the size of the vocabulary

method : public : GetVocabularySize() ~ Int

Return

TypeDescription
Intvocabulary size

IsFitted #

Whether the last Fit built a vocabulary.

method : public : IsFitted() ~ Bool

Return

TypeDescription
Booltrue when Transform has terms to work with

IsValid #

Whether the settings given to the constructor make sense: an n-gram range of min_n >= 1 and max_n >= min_n, a min_df of at least 1 and a max_features of at least 0. An invalid vectorizer does not crash and does not fit quietly: Fit returns false, GetError says why, the vocabulary stays empty and Transform gives empty vectors.

method : public : IsValid() ~ Bool

Return

TypeDescription
Booltrue when Fit can build a vocabulary

New # constructor

Constructor. The last four parameters are optional and default to what this class always did: single words, every word kept.

New(smooth_idf:Bool, l2_normalize:Bool, remove_stopwords:Bool, stem:Bool, min_n:Int, max_n:Int, min_df:Int, max_features:Int)

Parameters

NameTypeDescription
smooth_idfBoolsmooth IDF as ln((1 + N) / (1 + df)) + 1, so a word in every document still weighs 1; false gives the raw ln(N / df)
l2_normalizeBoolscale each vector to unit length
remove_stopwordsBooldrop common English stopwords before counting
stemBoolcount words by their Porter stem, so "cat" and "cats" share a column
min_nIntshortest term in words (1 = single words), as the first number of scikit-learn's ngram_range
max_nIntlongest term in words, as the second number of ngram_range; (1, 2) is words and word pairs, (1, 3) adds triples
min_dfIntkeep only terms found in at least this many documents
max_featuresIntkeep only this many terms, those most frequent across the corpus (ties go to the term seen first); 0 keeps all

SetMaxDenseBytes #

Sets the largest dense matrix TransformAll will build.

method : public : SetMaxDenseBytes(bytes:Int) ~ Bool

Parameters

NameTypeDescription
bytesIntthe limit in bytes, at least 1

Return

TypeDescription
Boolfalse (limit unchanged) for a value below 1

Transform #

Transforms a document into a TF-IDF vector, one entry per vocabulary word; words the fit did not see are ignored

method : public : Transform(document:String) ~ Float[]

Parameters

NameTypeDescription
documentStringinput document string

Return

TypeDescription
FloatTF-IDF vector as float array (unit length unless l2_normalize is false, or all zero)

Example

vec := tfidf->Transform("the cat chased the dog");
"Vector length: {$vec->Size()}"->PrintLine();

TransformAll #

Transforms documents into one matrix, a row per document, so no study writes the loop. The matrix is dense: 8 bytes times the vocabulary times the documents (20,000 terms for 40,000 documents is 6.4 GB). Past the limit (SetMaxDenseBytes, 2 GiB by default) this returns Nil rather than exhausting memory; set max_features or min_df, or transform in batches.

method : public : TransformAll(documents:String[]) ~ Float[,]

Parameters

NameTypeDescription
documentsStringthe documents

Return

TypeDescription
Float[documents, vocabulary size]; Nil when not fitted, documents or an entry is Nil, or the size exceeds the limit (see GetError)