Implementation:Scikit learn Scikit learn FeatureHasher
| Knowledge Sources | |
|---|---|
| Domains | Machine Learning, Feature Extraction |
| Last Updated | 2026-02-08 15:00 GMT |
Overview
Concrete tool for implementing feature hashing (the hashing trick) to convert feature names into sparse matrices, provided by scikit-learn.
Description
The FeatureHasher class turns sequences of symbolic feature names (strings) into scipy.sparse matrices using a hash function (signed 32-bit Murmurhash3) to compute the matrix column corresponding to each name. It is a low-memory alternative to DictVectorizer and CountVectorizer, designed for large-scale online learning and memory-constrained environments.
Usage
Use this class when you need to convert categorical or text features into sparse numerical representations with bounded memory, especially in streaming or large-scale scenarios where building a full vocabulary is impractical.
Code Reference
Source Location
- Repository: scikit-learn
- File: sklearn/feature_extraction/_hash.py
Signature
class FeatureHasher(TransformerMixin, BaseEstimator):
def __init__(
self,
n_features=2**20,
*,
input_type="dict",
dtype=np.float64,
alternate_sign=True,
):
Import
from sklearn.feature_extraction import FeatureHasher
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| n_features | int | No | Number of features (columns) in output matrices (default 2**20) |
| input_type | str | No | Input format: 'dict', 'pair', or 'string' (default 'dict') |
| dtype | numpy dtype | No | Output matrix data type (default np.float64) |
| alternate_sign | bool | No | Whether to alternate sign of hashed values to reduce collisions (default True) |
Outputs
| Name | Type | Description |
|---|---|---|
| X | scipy.sparse matrix of shape (n_samples, n_features) | Sparse feature matrix |
Usage Examples
Basic Usage
from sklearn.feature_extraction import FeatureHasher
h = FeatureHasher(n_features=10, input_type="dict")
D = [{"dog": 1, "cat": 2}, {"dog": 3, "fish": 1}]
X = h.transform(D)
print(X.toarray())