Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
Ctrl+K

VectorIndexer#

classpyspark.ml.feature.VectorIndexer(*,maxCategories=20,inputCol=None,outputCol=None,handleInvalid='error')[source]#

Class for indexing categorical feature columns in a dataset ofVector.

This has 2 usage modes:
  • Automatically identify categorical features (default behavior)
    • This helps process a dataset of unknown vectors into a dataset with some continuousfeatures and some categorical features. The choice between continuous and categoricalis based upon a maxCategories parameter.

    • Set maxCategories to the maximum number of categorical any categorical feature shouldhave.

    • E.g.: Feature 0 has unique values {-1.0, 0.0}, and feature 1 values {1.0, 3.0, 5.0}.If maxCategories = 2, then feature 0 will be declared categorical and use indices {0, 1},and feature 1 will be declared continuous.

  • Index all features, if all features are categorical
    • If maxCategories is set to be very large, then this will build an index of uniquevalues for all features.

    • Warning: This can cause problems if features are continuous since this will collect ALLunique values to the driver.

    • E.g.: Feature 0 has unique values {-1.0, 0.0}, and feature 1 values {1.0, 3.0, 5.0}.If maxCategories >= 3, then both features will be declared categorical.

This returns a model which can transform categorical features to use 0-based indices.

Index stability:
  • This is not guaranteed to choose the same category index across multiple runs.

  • If a categorical feature includes value 0, then this is guaranteed to map value 0 toindex 0. This maintains vector sparsity.

  • More stability may be added in the future.

TODO: Future extensions: The following functionality is planned for the future:
  • Preserve metadata in transform; if a feature’s metadata is already present,do not recompute.

  • Specify certain features to not index, either via a parameter or via existing metadata.

  • Add warning if a categorical feature has only 1 category.

New in version 1.4.0.

Examples

>>>frompyspark.ml.linalgimportVectors>>>df=spark.createDataFrame([(Vectors.dense([-1.0,0.0]),),...(Vectors.dense([0.0,1.0]),),(Vectors.dense([0.0,2.0]),)],["a"])>>>indexer=VectorIndexer(maxCategories=2,inputCol="a")>>>indexer.setOutputCol("indexed")VectorIndexer...>>>model=indexer.fit(df)>>>indexer.getHandleInvalid()'error'>>>model.setOutputCol("output")VectorIndexerModel...>>>model.transform(df).head().outputDenseVector([1.0, 0.0])>>>model.numFeatures2>>>model.categoryMaps{0: {0.0: 0, -1.0: 1}}>>>indexer.setParams(outputCol="test").fit(df).transform(df).collect()[1].testDenseVector([0.0, 1.0])>>>params={indexer.maxCategories:3,indexer.outputCol:"vector"}>>>model2=indexer.fit(df,params)>>>model2.transform(df).head().vectorDenseVector([1.0, 0.0])>>>vectorIndexerPath=temp_path+"/vector-indexer">>>indexer.save(vectorIndexerPath)>>>loadedIndexer=VectorIndexer.load(vectorIndexerPath)>>>loadedIndexer.getMaxCategories()==indexer.getMaxCategories()True>>>modelPath=temp_path+"/vector-indexer-model">>>model.save(modelPath)>>>loadedModel=VectorIndexerModel.load(modelPath)>>>loadedModel.numFeatures==model.numFeaturesTrue>>>loadedModel.categoryMaps==model.categoryMapsTrue>>>loadedModel.transform(df).take(1)==model.transform(df).take(1)True>>>dfWithInvalid=spark.createDataFrame([(Vectors.dense([3.0,1.0]),)],["a"])>>>indexer.getHandleInvalid()'error'>>>model3=indexer.setHandleInvalid("skip").fit(df)>>>model3.transform(dfWithInvalid).count()0>>>model4=indexer.setParams(handleInvalid="keep",outputCol="indexed").fit(df)>>>model4.transform(dfWithInvalid).head().indexedDenseVector([2.0, 1.0])

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.

explainParams()

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.

fit(dataset[, params])

Fits a model to the input dataset with optional parameters.

fitMultiple(dataset, paramMaps)

Fits a model to the input dataset for each param map inparamMaps.

getHandleInvalid()

Gets the value of handleInvalid or its default value.

getInputCol()

Gets the value of inputCol or its default value.

getMaxCategories()

Gets the value of maxCategories or its default value.

getOrDefault(param)

Gets the value of a param in the user-supplied param map or its default value.

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 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.

setHandleInvalid(value)

Sets the value ofhandleInvalid.

setInputCol(value)

Sets the value ofinputCol.

setMaxCategories(value)

Sets the value ofmaxCategories.

setOutputCol(value)

Sets the value ofoutputCol.

setParams(self, \*[, maxCategories, ...])

Sets params for this VectorIndexer.

write()

Returns an MLWriter instance for this ML instance.

Attributes

handleInvalid

inputCol

maxCategories

outputCol

params

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
JavaParams

Copy 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

fit(dataset,params=None)#

Fits a model to the input dataset with optional parameters.

New in version 1.3.0.

Parameters
datasetpyspark.sql.DataFrame

input dataset.

paramsdict or list or tuple, optional

an optional param map that overrides embedded params. If a list/tuple ofparam maps is given, this calls fit on each param map and returns a list ofmodels.

Returns
Transformer or a list ofTransformer

fitted model(s)

fitMultiple(dataset,paramMaps)#

Fits a model to the input dataset for each param map inparamMaps.

New in version 2.3.0.

Parameters
datasetpyspark.sql.DataFrame

input dataset.

paramMapscollections.abc.Sequence

A Sequence of param maps.

Returns
_FitMultipleIterator

A thread safe iterable which contains one model for each param map. Eachcall tonext(modelIterator) will return(index, model) where model was fitusingparamMaps[index].index values may not be sequential.

getHandleInvalid()#

Gets the value of handleInvalid or its default value.

getInputCol()#

Gets the value of inputCol or its default value.

getMaxCategories()#

Gets the value of maxCategories or its default value.

New in version 1.4.0.

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.

setHandleInvalid(value)[source]#

Sets the value ofhandleInvalid.

setInputCol(value)[source]#

Sets the value ofinputCol.

setMaxCategories(value)[source]#

Sets the value ofmaxCategories.

New in version 1.4.0.

setOutputCol(value)[source]#

Sets the value ofoutputCol.

setParams(self,\*,maxCategories=20,inputCol=None,outputCol=None,handleInvalid="error")[source]#

Sets params for this VectorIndexer.

New in version 1.4.0.

write()#

Returns an MLWriter instance for this ML instance.

Attributes Documentation

handleInvalid=Param(parent='undefined',name='handleInvalid',doc="Howtohandleinvaliddata(unseenlabelsorNULLvalues).Optionsare'skip'(filteroutrowswithinvaliddata),'error'(throwanerror),or'keep'(putinvaliddatainaspecialadditionalbucket,atindexofthenumberofcategoriesofthefeature).")#
inputCol=Param(parent='undefined',name='inputCol',doc='inputcolumnname.')#
maxCategories=Param(parent='undefined',name='maxCategories',doc='Thresholdforthenumberofvaluesacategoricalfeaturecantake(>=2).Ifafeatureisfoundtohave>maxCategoriesvalues,thenitisdeclaredcontinuous.')#
outputCol=Param(parent='undefined',name='outputCol',doc='outputcolumnname.')#
params#

Returns all params ordered by name. The default implementationusesdir() to get all attributes of typeParam.

uid#

A unique id for the object.


[8]ページ先頭

©2009-2025 Movatter.jp