Implementation:Online ml River Preprocessing FeatureHasher
| Knowledge Sources | |
|---|---|
| Domains | Online_Learning, Preprocessing, Feature_Engineering |
| Last Updated | 2026-02-08 16:00 GMT |
Overview
Implements the hashing trick for converting feature dictionaries to fixed-size numeric representations.
Description
FeatureHasher applies the hashing trick to convert arbitrary feature name-value pairs into a fixed-dimensional feature space. Each (name, value) pair is hashed to a random integer, then reduced modulo n_features to fit within the desired range. Uses the blake2s hash function with optional seeding for reproducibility. String values are automatically converted to indicator features. This approach enables memory-efficient feature representation without requiring a predefined vocabulary.
Usage
Use this when dealing with high-cardinality categorical features or when memory constraints prevent storing explicit feature mappings. Ideal for text data, categorical variables with many levels, or streaming scenarios where the feature space is unknown or unbounded. The hashing trick trades some accuracy for significant memory savings and constant-time feature extraction.
Code Reference
Source Location
- Repository: Online_ml_River
- File: river/preprocessing/feature_hasher.py
Signature
class FeatureHasher(base.Transformer):
def __init__(self, n_features=1048576, seed: int | None = None)
Import
from river import preprocessing
I/O Contract
| Input | Output |
|---|---|
| Dict[str, Union[int, float, str]] - Features | Counter[int, float] - Hashed features |
Usage Examples
import river
hasher = river.preprocessing.FeatureHasher(n_features=10, seed=42)
X = [
{'dog': 1, 'cat': 2, 'elephant': 4},
{'dog': 2, 'run': 5}
]
for x in X:
print(hasher.transform_one(x))
# Counter({1: 4, 9: 2, 8: 1})
# Counter({4: 5, 8: 2})