FeatureHasher¶
-
class
pyspark.ml.feature.
FeatureHasher
(*, numFeatures: int = 262144, inputCols: Optional[List[str]] = None, outputCol: Optional[str] = None, categoricalCols: Optional[List[str]] = None)¶ Feature hashing projects a set of categorical or numerical features into a feature vector of specified dimension (typically substantially smaller than that of the original feature space). This is done using the hashing trick (https://en.wikipedia.org/wiki/Feature_hashing) to map features to indices in the feature vector.
The FeatureHasher transformer operates on multiple columns. Each column may contain either numeric or categorical features. Behavior and handling of column data types is as follows:
- Numeric columns:
For numeric features, the hash value of the column name is used to map the feature value to its index in the feature vector. By default, numeric features are not treated as categorical (even when they are integers). To treat them as categorical, specify the relevant columns in categoricalCols.
- String columns:
For categorical features, the hash value of the string “column_name=value” is used to map to the vector index, with an indicator value of 1.0. Thus, categorical features are “one-hot” encoded (similarly to using
OneHotEncoder
with dropLast=false).
- Boolean columns:
Boolean values are treated in the same way as string columns. That is, boolean features are represented as “column_name=true” or “column_name=false”, with an indicator value of 1.0.
Null (missing) values are ignored (implicitly zero in the resulting feature vector).
Since a simple modulo is used to transform the hash function to a vector index, it is advisable to use a power of two as the numFeatures parameter; otherwise the features will not be mapped evenly to the vector indices.
Examples
>>> data = [(2.0, True, "1", "foo"), (3.0, False, "2", "bar")] >>> cols = ["real", "bool", "stringNum", "string"] >>> df = spark.createDataFrame(data, cols) >>> hasher = FeatureHasher() >>> hasher.setInputCols(cols) FeatureHasher... >>> hasher.setOutputCol("features") FeatureHasher... >>> hasher.transform(df).head().features SparseVector(262144, {174475: 2.0, 247670: 1.0, 257907: 1.0, 262126: 1.0}) >>> hasher.setCategoricalCols(["real"]).transform(df).head().features SparseVector(262144, {171257: 1.0, 247670: 1.0, 257907: 1.0, 262126: 1.0}) >>> hasherPath = temp_path + "/hasher" >>> hasher.save(hasherPath) >>> loadedHasher = FeatureHasher.load(hasherPath) >>> loadedHasher.getNumFeatures() == hasher.getNumFeatures() True >>> loadedHasher.transform(df).head().features == hasher.transform(df).head().features True
Methods
clear
(param)Clears a param from the param map if it has been explicitly set.
copy
([extra])Creates a copy of this instance with the same uid and some extra params.
explainParam
(param)Explains a single param and returns its name, doc, and optional default value and user-supplied value in a string.
Returns the documentation of all params with their optionally default values and user-supplied values.
extractParamMap
([extra])Extracts the embedded default param values and user-supplied values, and then merges them with extra values from input into a flat param map, where the latter value is used if there exist conflicts, i.e., with ordering: default param values < user-supplied values < extra.
Gets the value of binary or its default value.
Gets the value of inputCols or its default value.
Gets the value of numFeatures or its default value.
getOrDefault
(param)Gets the value of a param in the user-supplied param map or its default value.
Gets the value of outputCol or its default value.
getParam
(paramName)Gets a param by its name.
hasDefault
(param)Checks whether a param has a default value.
hasParam
(paramName)Tests whether this instance contains a param with a given (string) name.
isDefined
(param)Checks whether a param is explicitly set by user or has a default value.
isSet
(param)Checks whether a param is explicitly set by user.
load
(path)Reads an ML instance from the input path, a shortcut of read().load(path).
read
()Returns an MLReader instance for this class.
save
(path)Save this ML instance to the given path, a shortcut of ‘write().save(path)’.
set
(param, value)Sets a parameter in the embedded param map.
setCategoricalCols
(value)Sets the value of
categoricalCols
.setInputCols
(value)Sets the value of
inputCols
.setNumFeatures
(value)Sets the value of
numFeatures
.setOutputCol
(value)Sets the value of
outputCol
.setParams
(self, \*[, numFeatures, …])Sets params for this FeatureHasher.
transform
(dataset[, params])Transforms the input dataset with optional parameters.
write
()Returns an MLWriter instance for this ML instance.
Attributes
Returns all params ordered by name.
Methods Documentation
-
clear
(param: pyspark.ml.param.Param) → None¶ Clears a param from the param map if it has been explicitly set.
-
copy
(extra: Optional[ParamMap] = None) → JP¶ Creates a copy of this instance with the same uid and some extra params. This implementation first calls Params.copy and then make a copy of the companion Java pipeline component with extra params. So both the Python wrapper and the Java pipeline component get copied.
- Parameters
- extradict, optional
Extra parameters to copy to the new instance
- Returns
JavaParams
Copy of this instance
-
explainParam
(param: Union[str, pyspark.ml.param.Param]) → str¶ Explains a single param and returns its name, doc, and optional default value and user-supplied value in a string.
-
explainParams
() → str¶ Returns the documentation of all params with their optionally default values and user-supplied values.
-
extractParamMap
(extra: Optional[ParamMap] = None) → ParamMap¶ Extracts the embedded default param values and user-supplied values, and then merges them with extra values from input into a flat param map, where the latter value is used if there exist conflicts, i.e., with ordering: default param values < user-supplied values < extra.
- Parameters
- extradict, optional
extra param values
- Returns
- dict
merged param map
-
getCategoricalCols
() → List[str]¶ Gets the value of binary or its default value.
-
getInputCols
() → List[str]¶ Gets the value of inputCols or its default value.
-
getNumFeatures
() → int¶ Gets the value of numFeatures or its default value.
-
getOrDefault
(param: Union[str, pyspark.ml.param.Param[T]]) → Union[Any, T]¶ Gets the value of a param in the user-supplied param map or its default value. Raises an error if neither is set.
-
getOutputCol
() → str¶ Gets the value of outputCol or its default value.
-
getParam
(paramName: str) → pyspark.ml.param.Param¶ Gets a param by its name.
-
hasDefault
(param: Union[str, pyspark.ml.param.Param[Any]]) → bool¶ Checks whether a param has a default value.
-
hasParam
(paramName: str) → bool¶ Tests whether this instance contains a param with a given (string) name.
-
isDefined
(param: Union[str, pyspark.ml.param.Param[Any]]) → bool¶ Checks whether a param is explicitly set by user or has a default value.
-
isSet
(param: Union[str, pyspark.ml.param.Param[Any]]) → bool¶ Checks whether a param is explicitly set by user.
-
classmethod
load
(path: str) → RL¶ Reads an ML instance from the input path, a shortcut of read().load(path).
-
classmethod
read
() → pyspark.ml.util.JavaMLReader[RL]¶ Returns an MLReader instance for this class.
-
save
(path: str) → None¶ Save this ML instance to the given path, a shortcut of ‘write().save(path)’.
-
set
(param: pyspark.ml.param.Param, value: Any) → None¶ Sets a parameter in the embedded param map.
-
setCategoricalCols
(value: List[str]) → pyspark.ml.feature.FeatureHasher¶ Sets the value of
categoricalCols
.
-
setInputCols
(value: List[str]) → pyspark.ml.feature.FeatureHasher¶ Sets the value of
inputCols
.
-
setNumFeatures
(value: int) → pyspark.ml.feature.FeatureHasher¶ Sets the value of
numFeatures
.
-
setOutputCol
(value: str) → pyspark.ml.feature.FeatureHasher¶ Sets the value of
outputCol
.
-
setParams
(self, \*, numFeatures=1 << 18, inputCols=None, outputCol=None, categoricalCols=None)¶ Sets params for this FeatureHasher.
-
transform
(dataset: pyspark.sql.dataframe.DataFrame, params: Optional[ParamMap] = None) → pyspark.sql.dataframe.DataFrame¶ Transforms the input dataset with optional parameters.
- Parameters
- dataset
pyspark.sql.DataFrame
input dataset
- paramsdict, optional
an optional param map that overrides embedded params.
- dataset
- Returns
pyspark.sql.DataFrame
transformed dataset
-
write
() → pyspark.ml.util.JavaMLWriter¶ Returns an MLWriter instance for this ML instance.
Attributes Documentation
-
categoricalCols
: pyspark.ml.param.Param[List[str]] = Param(parent='undefined', name='categoricalCols', doc='numeric columns to treat as categorical')¶
-
inputCols
= Param(parent='undefined', name='inputCols', doc='input column names.')¶
-
numFeatures
= Param(parent='undefined', name='numFeatures', doc='Number of features. Should be greater than 0.')¶
-
outputCol
= Param(parent='undefined', name='outputCol', doc='output column name.')¶
-
params
¶ Returns all params ordered by name. The default implementation uses
dir()
to get all attributes of typeParam
.