Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Scikit learn Scikit learn FeatureHasher

From Leeroopedia


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

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())

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment