FeatureHasher#
- classpyspark.ml.feature.FeatureHasher(*,numFeatures=262144,inputCols=None,outputCol=None,categoricalCols=None)[source]#
Feature hashing projects a set of categorical or numerical features into a feature vector ofspecified dimension (typically substantially smaller than that of the original featurespace). 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 eithernumeric 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 thefeature value to its index in the feature vector. By default, numeric featuresare not treated as categorical (even when they are integers). To treat themas categorical, specify the relevant columns incategoricalCols.
- 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 of1.0.Thus, categorical features are “one-hot” encoded(similarly to using
OneHotEncoderwithdropLast=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 of1.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 thenumFeatures parameter;otherwise the features will not be mapped evenly to the vector indices.
New in version 2.3.0.
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().featuresSparseVector(262144, {174475: 2.0, 247670: 1.0, 257907: 1.0, 262126: 1.0})>>>hasher.setCategoricalCols(["real"]).transform(df).head().featuresSparseVector(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().featuresTrue
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 ofread().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)#
Clears a param from the param map if it has been explicitly set.
- copy(extra=None)#
Creates a copy of this instance with the same uid and someextra params. This implementation first calls Params.copy andthen make a copy of the companion Java pipeline component withextra params. So both the Python wrapper and the Java pipelinecomponent get copied.
- Parameters
- extradict, optional
Extra parameters to copy to the new instance
- Returns
JavaParamsCopy of this instance
- explainParam(param)#
Explains a single param and returns its name, doc, and optionaldefault value and user-supplied value in a string.
- explainParams()#
Returns the documentation of all params with their optionallydefault values and user-supplied values.
- extractParamMap(extra=None)#
Extracts the embedded default param values and user-suppliedvalues, and then merges them with extra values from input intoa flat param map, where the latter value is used if there existconflicts, i.e., with ordering: default param values <user-supplied values < extra.
- Parameters
- extradict, optional
extra param values
- Returns
- dict
merged param map
- getInputCols()#
Gets the value of inputCols or its default value.
- getNumFeatures()#
Gets the value of numFeatures or its default value.
- getOrDefault(param)#
Gets the value of a param in the user-supplied param map or itsdefault value. Raises an error if neither is set.
- getOutputCol()#
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 hasa default value.
- isSet(param)#
Checks whether a param is explicitly set by user.
- classmethodload(path)#
Reads an ML instance from the input path, a shortcut ofread().load(path).
- classmethodread()#
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)[source]#
Sets the value of
categoricalCols.New in version 2.3.0.
- setNumFeatures(value)[source]#
Sets the value of
numFeatures.
- setParams(self,\*,numFeatures=1<<18,inputCols=None,outputCol=None,categoricalCols=None)[source]#
Sets params for this FeatureHasher.
New in version 2.3.0.
- transform(dataset,params=None)#
Transforms the input dataset with optional parameters.
New in version 1.3.0.
- Parameters
- dataset
pyspark.sql.DataFrame input dataset
- paramsdict, optional
an optional param map that overrides embedded params.
- dataset
- Returns
pyspark.sql.DataFrametransformed dataset
- write()#
Returns an MLWriter instance for this ML instance.
Attributes Documentation
- categoricalCols=Param(parent='undefined',name='categoricalCols',doc='numericcolumnstotreatascategorical')#
- inputCols=Param(parent='undefined',name='inputCols',doc='inputcolumnnames.')#
- numFeatures=Param(parent='undefined',name='numFeatures',doc='Numberoffeatures.Shouldbegreaterthan0.')#
- outputCol=Param(parent='undefined',name='outputCol',doc='outputcolumnname.')#
- params#
Returns all params ordered by name. The default implementationuses
dir()to get all attributes of typeParam.
- uid#
A unique id for the object.