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
- New
- EstimateDenseBytes
- Fit
- FitTransform
- GetError
- GetIdf
- GetMaxDenseBytes
- GetMaxN
- GetMinN
- GetVocabulary
- GetVocabularySize
- IsFitted
- IsValid
- SetMaxDenseBytes
- Transform
- TransformAll
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) ~ IntParameters
| Name | Type | Description |
|---|---|---|
| documents | Int | how many documents |
Return
| Type | Description |
|---|---|
| Int | the 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[]) ~ BoolParameters
| Name | Type | Description |
|---|---|---|
| documents | String | array of document strings |
Return
| Type | Description |
|---|---|
| Bool | true 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
| Name | Type | Description |
|---|---|---|
| documents | String | the documents |
Return
| Type | Description |
|---|---|
| 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() ~ StringReturn
| Type | Description |
|---|---|
| String | the 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
| Type | Description |
|---|---|
| Float | a 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() ~ IntReturn
| Type | Description |
|---|---|
| Int | bytes |
GetVocabulary #
Gets the vocabulary (word to index mapping)
method : public : GetVocabulary() ~ Hash<String,IntRef>Return
| Type | Description |
|---|---|
| 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() ~ IntReturn
| Type | Description |
|---|---|
| Int | vocabulary size |
IsFitted #
Whether the last Fit built a vocabulary.
method : public : IsFitted() ~ BoolReturn
| Type | Description |
|---|---|
| Bool | true 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() ~ BoolReturn
| Type | Description |
|---|---|
| Bool | true 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
| Name | Type | Description |
|---|---|---|
| smooth_idf | Bool | smooth 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_normalize | Bool | scale each vector to unit length |
| remove_stopwords | Bool | drop common English stopwords before counting |
| stem | Bool | count words by their Porter stem, so "cat" and "cats" share a column |
| min_n | Int | shortest term in words (1 = single words), as the first number of scikit-learn's ngram_range |
| max_n | Int | longest term in words, as the second number of ngram_range; (1, 2) is words and word pairs, (1, 3) adds triples |
| min_df | Int | keep only terms found in at least this many documents |
| max_features | Int | keep 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) ~ BoolParameters
| Name | Type | Description |
|---|---|---|
| bytes | Int | the limit in bytes, at least 1 |
Return
| Type | Description |
|---|---|
| Bool | false (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
| Name | Type | Description |
|---|---|---|
| document | String | input document string |
Return
| Type | Description |
|---|---|
| Float | TF-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
| Name | Type | Description |
|---|---|---|
| documents | String | the documents |
Return
| Type | Description |
|---|---|
| Float | [documents, vocabulary size]; Nil when not fitted, documents or an entry is Nil, or the size exceeds the limit (see GetError) |