Skip to Content
OchreML
Utilities & Preprocessing

Feature & Text Extraction

Rust-backed dictionary vectorization, MurmurHash3 feature hashing, and text tokenization/TF-IDF extraction in ochreml.feature_extraction.

ochreml.feature_extraction and ochreml.feature_extraction.text provide six Rust-accelerated vectorizers and transformers (all lazily importable from ochreml) powered by Rayon parallel tokenization, vocabulary indexing, TF-IDF weighting, and MurmurHash3 hashing. (*≧ω≦*)

Overview

ClassSubmodulePurposeOutput.dit Tag
DictVectorizerochreml.feature_extractionMaps lists of dict records to feature matricesSparse CSR or dense28
FeatureHasherochreml.feature_extractionStateless MurmurHash3 hashing trick for dicts/pairs/stringsSparse CSR29
CountVectorizerochreml.feature_extraction.textTokenizes text corpus into term-count CSR matrixSparse CSR30
TfidfTransformerochreml.feature_extraction.textScales count matrix to TF or TF-IDF weightsSparse CSR or dense31
TfidfVectorizerochreml.feature_extraction.textFused tokenization + TF-IDF weightingSparse CSR32
HashingVectorizerochreml.feature_extraction.textStateless hashed token counts (partial_fit supported)Sparse CSR33

ochreml.feature_extraction.text also exports ENGLISH_STOP_WORDS (frozenset[str]).


DictVectorizer

Converts lists of Python dict mappings into numeric feature matrices. Numeric values become feature weights, booleans map to 1.0/0.0, and string values are automatically one-hot encoded as f"{key}{separator}{value}". All constructor parameters are keyword-only.

from ochreml.feature_extraction import DictVectorizer

dv = DictVectorizer(
    dtype=None,
    separator="=",
    sparse=True,
    sort=True,
    device=None,
)
X = dv.fit_transform([
    {"city": "Tokyo", "temp": 22.0},
    {"city": "Paris", "temp": 18.5},
])
records = dv.inverse_transform(X)

Parameters & Attributes

ParameterTypeDefaultDescription
dtypeNumPy dtype or Nonenp.float64Output matrix dtype.
separatorstr"="Separator inserted between key and string value for categorical keys.
sparseboolTrueIf True, returns scipy.sparse.csr_matrix; otherwise dense np.ndarray.
sortboolTrueSort feature_names_ and vocabulary_ lexicographically during fit.
devicestr | NoneNoneTarget compute device.
  • Methods: fit(X, y=None), transform(X), fit_transform(X, y=None), inverse_transform(X, dict_type=dict), restrict(support, indices=False), get_feature_names_out(input_features=None), save(path), load(path, device=None), to(device)
  • Attributes: feature_names_, vocabulary_, device_

FeatureHasher

Stateless MurmurHash3 feature hasher that projects dicts, (feature, value) pairs, or iterables of strings directly into a fixed-width sparse CSR matrix without storing a vocabulary.

from ochreml.feature_extraction import FeatureHasher

fh = FeatureHasher(
    n_features=2**20,
    input_type="dict",
    dtype=None,
    alternate_sign=True,
    device=None,
)
X = fh.transform([{"dog": 1, "cat": 2}, {"dog": 2, "run": 5}])

Parameters

ParameterTypeDefaultDescription
n_featuresint2**20Number of hashed output columns.
input_type{"dict", "pair", "string"}"dict"Keyword-only; input record structure.
dtypeNumPy dtype or Nonenp.float64Keyword-only; output matrix dtype.
alternate_signboolTrueKeyword-only; apply signed hashing to preserve inner products in expectation.
devicestr | NoneNoneKeyword-only; target compute device.
  • Methods: fit(X=None, y=None), transform(raw_X), fit_transform(raw_X, y=None), save(path), load(path, device=None), to(device)
  • Attributes: device_

CountVectorizer

Tokenizes a corpus of documents into a sparse CSR matrix of token counts. Uses a fast Rayon Rust analyzer whenever default tokenization settings are used, and transparently falls back to custom Python callables when strip_accents, preprocessor, tokenizer, or a custom analyzer / token_pattern is provided. All constructor parameters are keyword-only.

from ochreml.feature_extraction.text import CountVectorizer

cv = CountVectorizer(
    input="content",
    encoding="utf-8",
    decode_error="strict",
    strip_accents=None,
    lowercase=True,
    preprocessor=None,
    tokenizer=None,
    stop_words=None,
    token_pattern=r"(?u)\b\w\w+\b",
    ngram_range=(1, 1),
    analyzer="word",
    max_df=1.0,
    min_df=1,
    max_features=None,
    vocabulary=None,
    binary=False,
    dtype=None,
    device=None,
)
X_counts = cv.fit_transform(["rust is fast", "ochreml runs in rust"])

Key Parameters

ParameterTypeDefaultDescription
input{"content", "filename", "file"}"content"Whether inputs are raw strings/bytes, file paths, or file-like objects.
encoding / decode_errorstr"utf-8" / "strict"Byte decoding settings.
strip_accents{"ascii", "unicode"}, Callable, or NoneNoneAccent stripping applied during preprocessing.
lowercaseboolTrueConvert all characters to lowercase before tokenizing.
stop_words"english", Iterable[str], or NoneNoneStop words removed from word tokens.
ngram_rangetuple[int, int](1, 1)Inclusive (min_n, max_n) range of n-grams.
analyzer{"word", "char", "char_wb"} or Callable"word"Feature unit extraction mode.
max_df / min_dfint | float1.0 / 1Document frequency thresholds (float = proportion, int = absolute count).
max_featuresint | NoneNoneKeep only the top max_features terms ordered by corpus term frequency.
vocabularydict[str, int] | Iterable[str] | NoneNoneOptional fixed vocabulary.
binaryboolFalseIf True, clip all non-zero counts to 1.
dtypeNumPy dtype or Nonenp.int64Output matrix dtype.
  • Methods: fit(raw_documents, y=None), transform(raw_documents), fit_transform(raw_documents, y=None), inverse_transform(X), get_feature_names_out(input_features=None), build_preprocessor(), build_tokenizer(), build_analyzer(), save(path), load(path, device=None), to(device)
  • Attributes: vocabulary_, fixed_vocabulary_, stop_words_, device_

TfidfTransformer

Transforms a dense or sparse count matrix into a normalized TF or TF-IDF representation. All constructor parameters are keyword-only.

from ochreml.feature_extraction.text import TfidfTransformer

tf = TfidfTransformer(
    norm="l2",
    use_idf=True,
    smooth_idf=True,
    sublinear_tf=False,
    device=None,
)
X_tfidf = tf.fit_transform(X_counts)

Parameters & Attributes

ParameterTypeDefaultDescription
norm{"l1", "l2"} or None"l2"Row-wise output normalization.
use_idfboolTrueMultiply term frequencies by inverse document frequency weights.
smooth_idfboolTrueAdd 1 to document frequencies (log((1 + n) / (1 + df)) + 1) to prevent division by zero.
sublinear_tfboolFalseReplace term frequency tf with 1 + log(tf).
devicestr | NoneNoneTarget compute device.
  • Methods: fit(X, y=None), transform(X, copy=True), fit_transform(X, y=None), save(path), load(path, device=None), to(device)
  • Attributes: idf_, n_features_in_, device_

TfidfVectorizer

Subclasses CountVectorizer and fuses tokenization with TfidfTransformer in a single Rust pass when using the default analyzer. Accepts all CountVectorizer parameters plus TfidfTransformer parameters (norm="l2", use_idf=True, smooth_idf=True, sublinear_tf=False), defaulting dtype to np.float64.

from ochreml.feature_extraction.text import TfidfVectorizer

vec = TfidfVectorizer(
    ngram_range=(1, 2),
    stop_words="english",
    sublinear_tf=True,
    norm="l2",
)
X_tfidf = vec.fit_transform(["fast rust ml", "zero copy python buffers"])
  • Additional Attribute: idf_ (inherited attributes: vocabulary_, fixed_vocabulary_, stop_words_, device_)
  • Persistence: .dit tag 32 (stores both vocabulary and IDF weights).

HashingVectorizer

Stateless text vectorizer that hashes tokens directly into a fixed-size sparse matrix of width n_features using MurmurHash3. Supports streaming via partial_fit and requires zero memory for a vocabulary dictionary. All constructor parameters are keyword-only.

from ochreml.feature_extraction.text import HashingVectorizer

hv = HashingVectorizer(
    input="content",
    encoding="utf-8",
    decode_error="strict",
    strip_accents=None,
    lowercase=True,
    preprocessor=None,
    tokenizer=None,
    stop_words=None,
    token_pattern=r"(?u)\b\w\w+\b",
    ngram_range=(1, 1),
    analyzer="word",
    n_features=2**20,
    binary=False,
    norm="l2",
    alternate_sign=True,
    dtype=None,
    device=None,
)
X_hashed = hv.transform(["streaming text document"])
  • Methods: fit(X=None, y=None), partial_fit(X=None, y=None), transform(X), fit_transform(X, y=None), build_preprocessor(), build_tokenizer(), build_analyzer(), save(path), load(path, device=None), to(device)
  • Attributes: device_

On this page