2014-10-07 19:43:34 -04:00
|
|
|
#
|
|
|
|
# Licensed to the Apache Software Foundation (ASF) under one or more
|
|
|
|
# contributor license agreements. See the NOTICE file distributed with
|
|
|
|
# this work for additional information regarding copyright ownership.
|
|
|
|
# The ASF licenses this file to You under the Apache License, Version 2.0
|
|
|
|
# (the "License"); you may not use this file except in compliance with
|
|
|
|
# the License. You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
#
|
|
|
|
|
|
|
|
"""
|
|
|
|
Python package for feature in MLlib.
|
|
|
|
"""
|
2014-10-28 06:50:22 -04:00
|
|
|
import sys
|
|
|
|
import warnings
|
|
|
|
from py4j.protocol import Py4JJavaError
|
|
|
|
|
2015-12-16 18:48:11 -05:00
|
|
|
from pyspark import since
|
2020-07-13 22:22:44 -04:00
|
|
|
from pyspark.rdd import RDD
|
2014-10-31 01:25:18 -04:00
|
|
|
from pyspark.mllib.common import callMLlibFunc, JavaModelWrapper
|
2020-08-08 11:51:57 -04:00
|
|
|
from pyspark.mllib.linalg import Vectors, _convert_to_vector
|
2015-07-02 18:55:16 -04:00
|
|
|
from pyspark.mllib.util import JavaLoader, JavaSaveable
|
2014-10-28 06:50:22 -04:00
|
|
|
|
|
|
|
__all__ = ['Normalizer', 'StandardScalerModel', 'StandardScaler',
|
2015-05-08 18:48:39 -04:00
|
|
|
'HashingTF', 'IDFModel', 'IDF', 'Word2Vec', 'Word2VecModel',
|
2015-06-18 01:08:38 -04:00
|
|
|
'ChiSqSelector', 'ChiSqSelectorModel', 'ElementwiseProduct']
|
2014-10-28 06:50:22 -04:00
|
|
|
|
|
|
|
|
|
|
|
class VectorTransformer(object):
|
|
|
|
"""
|
|
|
|
Base class for transformation of a vector or RDD of vector
|
|
|
|
"""
|
|
|
|
def transform(self, vector):
|
|
|
|
"""
|
|
|
|
Applies transformation on a vector.
|
|
|
|
|
|
|
|
:param vector: vector to be transformed.
|
|
|
|
"""
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
|
|
|
|
class Normalizer(VectorTransformer):
|
2018-09-12 23:19:43 -04:00
|
|
|
r"""
|
2014-12-17 17:12:46 -05:00
|
|
|
Normalizes samples individually to unit L\ :sup:`p`\ norm
|
2014-10-28 06:50:22 -04:00
|
|
|
|
2014-12-17 17:12:46 -05:00
|
|
|
For any 1 <= `p` < float('inf'), normalizes samples using
|
|
|
|
sum(abs(vector) :sup:`p`) :sup:`(1/p)` as norm.
|
2014-10-28 06:50:22 -04:00
|
|
|
|
2015-02-25 19:13:17 -05:00
|
|
|
For `p` = float('inf'), max(abs(vector)) will be used as norm for
|
|
|
|
normalization.
|
2014-10-28 06:50:22 -04:00
|
|
|
|
2015-05-30 19:24:07 -04:00
|
|
|
:param p: Normalization in L^p^ space, p = 2 by default.
|
|
|
|
|
2020-08-08 11:51:57 -04:00
|
|
|
>>> from pyspark.mllib.linalg import Vectors
|
2014-10-28 06:50:22 -04:00
|
|
|
>>> v = Vectors.dense(range(3))
|
|
|
|
>>> nor = Normalizer(1)
|
|
|
|
>>> nor.transform(v)
|
|
|
|
DenseVector([0.0, 0.3333, 0.6667])
|
|
|
|
|
|
|
|
>>> rdd = sc.parallelize([v])
|
|
|
|
>>> nor.transform(rdd).collect()
|
|
|
|
[DenseVector([0.0, 0.3333, 0.6667])]
|
|
|
|
|
|
|
|
>>> nor2 = Normalizer(float("inf"))
|
|
|
|
>>> nor2.transform(v)
|
|
|
|
DenseVector([0.0, 0.5, 1.0])
|
2015-09-15 00:58:52 -04:00
|
|
|
|
|
|
|
.. versionadded:: 1.2.0
|
2014-10-28 06:50:22 -04:00
|
|
|
"""
|
|
|
|
def __init__(self, p=2.0):
|
|
|
|
assert p >= 1.0, "p should be greater than 1.0"
|
|
|
|
self.p = float(p)
|
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.2.0')
|
2014-10-28 06:50:22 -04:00
|
|
|
def transform(self, vector):
|
|
|
|
"""
|
|
|
|
Applies unit length normalization on a vector.
|
|
|
|
|
2014-11-11 01:26:16 -05:00
|
|
|
:param vector: vector or RDD of vector to be normalized.
|
2014-10-28 06:50:22 -04:00
|
|
|
:return: normalized vector. If the norm of the input is zero, it
|
2015-05-30 19:24:07 -04:00
|
|
|
will return the input vector.
|
2014-10-28 06:50:22 -04:00
|
|
|
"""
|
2014-11-11 01:26:16 -05:00
|
|
|
if isinstance(vector, RDD):
|
|
|
|
vector = vector.map(_convert_to_vector)
|
|
|
|
else:
|
|
|
|
vector = _convert_to_vector(vector)
|
2014-10-31 01:25:18 -04:00
|
|
|
return callMLlibFunc("normalizeVector", self.p, vector)
|
2014-10-28 06:50:22 -04:00
|
|
|
|
|
|
|
|
2014-10-31 01:25:18 -04:00
|
|
|
class JavaVectorTransformer(JavaModelWrapper, VectorTransformer):
|
2014-10-28 06:50:22 -04:00
|
|
|
"""
|
|
|
|
Wrapper for the model in JVM
|
|
|
|
"""
|
2014-10-07 19:43:34 -04:00
|
|
|
|
2014-11-11 01:26:16 -05:00
|
|
|
def transform(self, vector):
|
2015-06-29 21:50:23 -04:00
|
|
|
"""
|
|
|
|
Applies transformation on a vector or an RDD[Vector].
|
|
|
|
|
2016-11-22 06:40:18 -05:00
|
|
|
.. note:: In Python, transform cannot currently be used within
|
|
|
|
an RDD transformation or action.
|
|
|
|
Call transform directly on the RDD instead.
|
2015-06-29 21:50:23 -04:00
|
|
|
|
|
|
|
:param vector: Vector or RDD of Vector to be transformed.
|
|
|
|
"""
|
2014-11-11 01:26:16 -05:00
|
|
|
if isinstance(vector, RDD):
|
|
|
|
vector = vector.map(_convert_to_vector)
|
|
|
|
else:
|
|
|
|
vector = _convert_to_vector(vector)
|
|
|
|
return self.call("transform", vector)
|
2014-10-28 06:50:22 -04:00
|
|
|
|
|
|
|
|
2014-10-31 01:25:18 -04:00
|
|
|
class StandardScalerModel(JavaVectorTransformer):
|
2014-10-28 06:50:22 -04:00
|
|
|
"""
|
|
|
|
Represents a StandardScaler model that can transform vectors.
|
2015-09-15 00:58:52 -04:00
|
|
|
|
|
|
|
.. versionadded:: 1.2.0
|
2014-10-28 06:50:22 -04:00
|
|
|
"""
|
2015-09-15 00:58:52 -04:00
|
|
|
|
|
|
|
@since('1.2.0')
|
2014-10-28 06:50:22 -04:00
|
|
|
def transform(self, vector):
|
2014-10-07 19:43:34 -04:00
|
|
|
"""
|
2014-10-28 06:50:22 -04:00
|
|
|
Applies standardization transformation on a vector.
|
|
|
|
|
2016-11-22 06:40:18 -05:00
|
|
|
.. note:: In Python, transform cannot currently be used within
|
|
|
|
an RDD transformation or action.
|
|
|
|
Call transform directly on the RDD instead.
|
2015-02-25 19:13:17 -05:00
|
|
|
|
2014-11-11 01:26:16 -05:00
|
|
|
:param vector: Vector or RDD of Vector to be standardized.
|
2015-02-25 19:13:17 -05:00
|
|
|
:return: Standardized vector. If the variance of a column is
|
|
|
|
zero, it will return default `0.0` for the column with
|
|
|
|
zero variance.
|
2014-10-28 06:50:22 -04:00
|
|
|
"""
|
2014-10-31 01:25:18 -04:00
|
|
|
return JavaVectorTransformer.transform(self, vector)
|
2014-10-28 06:50:22 -04:00
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.4.0')
|
2015-04-13 01:17:16 -04:00
|
|
|
def setWithMean(self, withMean):
|
|
|
|
"""
|
|
|
|
Setter of the boolean which decides
|
|
|
|
whether it uses mean or not
|
|
|
|
"""
|
|
|
|
self.call("setWithMean", withMean)
|
|
|
|
return self
|
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.4.0')
|
2015-04-13 01:17:16 -04:00
|
|
|
def setWithStd(self, withStd):
|
|
|
|
"""
|
|
|
|
Setter of the boolean which decides
|
|
|
|
whether it uses std or not
|
|
|
|
"""
|
|
|
|
self.call("setWithStd", withStd)
|
|
|
|
return self
|
|
|
|
|
2015-12-22 02:14:12 -05:00
|
|
|
@property
|
|
|
|
@since('2.0.0')
|
|
|
|
def withStd(self):
|
|
|
|
"""
|
|
|
|
Returns if the model scales the data to unit standard deviation.
|
|
|
|
"""
|
|
|
|
return self.call("withStd")
|
|
|
|
|
|
|
|
@property
|
|
|
|
@since('2.0.0')
|
|
|
|
def withMean(self):
|
|
|
|
"""
|
|
|
|
Returns if the model centers the data before scaling.
|
|
|
|
"""
|
|
|
|
return self.call("withMean")
|
|
|
|
|
|
|
|
@property
|
|
|
|
@since('2.0.0')
|
|
|
|
def std(self):
|
|
|
|
"""
|
|
|
|
Return the column standard deviation values.
|
|
|
|
"""
|
|
|
|
return self.call("std")
|
|
|
|
|
|
|
|
@property
|
|
|
|
@since('2.0.0')
|
|
|
|
def mean(self):
|
|
|
|
"""
|
|
|
|
Return the column mean values.
|
|
|
|
"""
|
|
|
|
return self.call("mean")
|
|
|
|
|
2014-10-28 06:50:22 -04:00
|
|
|
|
|
|
|
class StandardScaler(object):
|
|
|
|
"""
|
|
|
|
Standardizes features by removing the mean and scaling to unit
|
|
|
|
variance using column summary statistics on the samples in the
|
|
|
|
training set.
|
2014-10-11 14:51:59 -04:00
|
|
|
|
2015-05-30 19:24:07 -04:00
|
|
|
:param withMean: False by default. Centers the data with mean
|
2016-08-27 03:48:56 -04:00
|
|
|
before scaling. It will build a dense output, so take
|
|
|
|
care when applying to sparse input.
|
2015-05-30 19:24:07 -04:00
|
|
|
:param withStd: True by default. Scales the data to unit
|
|
|
|
standard deviation.
|
|
|
|
|
2014-10-28 06:50:22 -04:00
|
|
|
>>> vs = [Vectors.dense([-2.0, 2.3, 0]), Vectors.dense([3.8, 0.0, 1.9])]
|
|
|
|
>>> dataset = sc.parallelize(vs)
|
|
|
|
>>> standardizer = StandardScaler(True, True)
|
|
|
|
>>> model = standardizer.fit(dataset)
|
|
|
|
>>> result = model.transform(dataset)
|
|
|
|
>>> for r in result.collect(): r
|
|
|
|
DenseVector([-0.7071, 0.7071, -0.7071])
|
|
|
|
DenseVector([0.7071, -0.7071, 0.7071])
|
2015-12-22 02:14:12 -05:00
|
|
|
>>> int(model.std[0])
|
|
|
|
4
|
|
|
|
>>> int(model.mean[0]*10)
|
|
|
|
9
|
|
|
|
>>> model.withStd
|
|
|
|
True
|
|
|
|
>>> model.withMean
|
|
|
|
True
|
2015-09-15 00:58:52 -04:00
|
|
|
|
|
|
|
.. versionadded:: 1.2.0
|
2014-10-28 06:50:22 -04:00
|
|
|
"""
|
|
|
|
def __init__(self, withMean=False, withStd=True):
|
|
|
|
if not (withMean or withStd):
|
|
|
|
warnings.warn("Both withMean and withStd are false. The model does nothing.")
|
|
|
|
self.withMean = withMean
|
|
|
|
self.withStd = withStd
|
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.2.0')
|
2014-10-28 06:50:22 -04:00
|
|
|
def fit(self, dataset):
|
|
|
|
"""
|
2015-02-25 19:13:17 -05:00
|
|
|
Computes the mean and variance and stores as a model to be used
|
|
|
|
for later scaling.
|
2014-10-28 06:50:22 -04:00
|
|
|
|
2015-06-29 21:50:23 -04:00
|
|
|
:param dataset: The data used to compute the mean and variance
|
2015-05-30 19:24:07 -04:00
|
|
|
to build the transformation model.
|
2014-10-28 06:50:22 -04:00
|
|
|
:return: a StandardScalarModel
|
|
|
|
"""
|
2014-11-11 01:26:16 -05:00
|
|
|
dataset = dataset.map(_convert_to_vector)
|
2014-10-31 01:25:18 -04:00
|
|
|
jmodel = callMLlibFunc("fitStandardScaler", self.withMean, self.withStd, dataset)
|
|
|
|
return StandardScalerModel(jmodel)
|
2014-10-28 06:50:22 -04:00
|
|
|
|
|
|
|
|
2015-05-08 18:48:39 -04:00
|
|
|
class ChiSqSelectorModel(JavaVectorTransformer):
|
|
|
|
"""
|
|
|
|
Represents a Chi Squared selector model.
|
2015-09-15 00:58:52 -04:00
|
|
|
|
|
|
|
.. versionadded:: 1.4.0
|
2015-05-08 18:48:39 -04:00
|
|
|
"""
|
2015-09-15 00:58:52 -04:00
|
|
|
|
|
|
|
@since('1.4.0')
|
2015-05-08 18:48:39 -04:00
|
|
|
def transform(self, vector):
|
|
|
|
"""
|
|
|
|
Applies transformation on a vector.
|
|
|
|
|
|
|
|
:param vector: Vector or RDD of Vector to be transformed.
|
|
|
|
:return: transformed vector.
|
|
|
|
"""
|
|
|
|
return JavaVectorTransformer.transform(self, vector)
|
|
|
|
|
|
|
|
|
|
|
|
class ChiSqSelector(object):
|
|
|
|
"""
|
|
|
|
Creates a ChiSquared feature selector.
|
[SPARK-17645][MLLIB][ML] add feature selector method based on: False Discovery Rate (FDR) and Family wise error rate (FWE)
## What changes were proposed in this pull request?
Univariate feature selection works by selecting the best features based on univariate statistical tests.
FDR and FWE are a popular univariate statistical test for feature selection.
In 2005, the Benjamini and Hochberg paper on FDR was identified as one of the 25 most-cited statistical papers. The FDR uses the Benjamini-Hochberg procedure in this PR. https://en.wikipedia.org/wiki/False_discovery_rate.
In statistics, FWE is the probability of making one or more false discoveries, or type I errors, among all the hypotheses when performing multiple hypotheses tests.
https://en.wikipedia.org/wiki/Family-wise_error_rate
We add FDR and FWE methods for ChiSqSelector in this PR, like it is implemented in scikit-learn.
http://scikit-learn.org/stable/modules/feature_selection.html#univariate-feature-selection
## How was this patch tested?
ut will be added soon
(Please explain how this patch was tested. E.g. unit tests, integration tests, manual tests)
(If this patch involves UI changes, please attach a screenshot; otherwise, remove this)
Author: Peng <peng.meng@intel.com>
Author: Peng, Meng <peng.meng@intel.com>
Closes #15212 from mpjlu/fdr_fwe.
2016-12-28 03:49:36 -05:00
|
|
|
The selector supports different selection methods: `numTopFeatures`, `percentile`, `fpr`,
|
|
|
|
`fdr`, `fwe`.
|
|
|
|
|
|
|
|
* `numTopFeatures` chooses a fixed number of top features according to a chi-squared test.
|
|
|
|
|
|
|
|
* `percentile` is similar but chooses a fraction of all features
|
|
|
|
instead of a fixed number.
|
|
|
|
|
2017-01-10 08:09:58 -05:00
|
|
|
* `fpr` chooses all features whose p-values are below a threshold,
|
[SPARK-17645][MLLIB][ML] add feature selector method based on: False Discovery Rate (FDR) and Family wise error rate (FWE)
## What changes were proposed in this pull request?
Univariate feature selection works by selecting the best features based on univariate statistical tests.
FDR and FWE are a popular univariate statistical test for feature selection.
In 2005, the Benjamini and Hochberg paper on FDR was identified as one of the 25 most-cited statistical papers. The FDR uses the Benjamini-Hochberg procedure in this PR. https://en.wikipedia.org/wiki/False_discovery_rate.
In statistics, FWE is the probability of making one or more false discoveries, or type I errors, among all the hypotheses when performing multiple hypotheses tests.
https://en.wikipedia.org/wiki/Family-wise_error_rate
We add FDR and FWE methods for ChiSqSelector in this PR, like it is implemented in scikit-learn.
http://scikit-learn.org/stable/modules/feature_selection.html#univariate-feature-selection
## How was this patch tested?
ut will be added soon
(Please explain how this patch was tested. E.g. unit tests, integration tests, manual tests)
(If this patch involves UI changes, please attach a screenshot; otherwise, remove this)
Author: Peng <peng.meng@intel.com>
Author: Peng, Meng <peng.meng@intel.com>
Closes #15212 from mpjlu/fdr_fwe.
2016-12-28 03:49:36 -05:00
|
|
|
thus controlling the false positive rate of selection.
|
|
|
|
|
|
|
|
* `fdr` uses the `Benjamini-Hochberg procedure <https://en.wikipedia.org/wiki/
|
|
|
|
False_discovery_rate#Benjamini.E2.80.93Hochberg_procedure>`_
|
|
|
|
to choose all features whose false discovery rate is below a threshold.
|
|
|
|
|
2017-01-10 08:09:58 -05:00
|
|
|
* `fwe` chooses all features whose p-values are below a threshold. The threshold is scaled by
|
|
|
|
1/numFeatures, thus controlling the family-wise error rate of selection.
|
[SPARK-17645][MLLIB][ML] add feature selector method based on: False Discovery Rate (FDR) and Family wise error rate (FWE)
## What changes were proposed in this pull request?
Univariate feature selection works by selecting the best features based on univariate statistical tests.
FDR and FWE are a popular univariate statistical test for feature selection.
In 2005, the Benjamini and Hochberg paper on FDR was identified as one of the 25 most-cited statistical papers. The FDR uses the Benjamini-Hochberg procedure in this PR. https://en.wikipedia.org/wiki/False_discovery_rate.
In statistics, FWE is the probability of making one or more false discoveries, or type I errors, among all the hypotheses when performing multiple hypotheses tests.
https://en.wikipedia.org/wiki/Family-wise_error_rate
We add FDR and FWE methods for ChiSqSelector in this PR, like it is implemented in scikit-learn.
http://scikit-learn.org/stable/modules/feature_selection.html#univariate-feature-selection
## How was this patch tested?
ut will be added soon
(Please explain how this patch was tested. E.g. unit tests, integration tests, manual tests)
(If this patch involves UI changes, please attach a screenshot; otherwise, remove this)
Author: Peng <peng.meng@intel.com>
Author: Peng, Meng <peng.meng@intel.com>
Closes #15212 from mpjlu/fdr_fwe.
2016-12-28 03:49:36 -05:00
|
|
|
|
2016-11-01 20:00:00 -04:00
|
|
|
By default, the selection method is `numTopFeatures`, with the default number of top features
|
|
|
|
set to 50.
|
2015-05-30 19:24:07 -04:00
|
|
|
|
2020-08-08 11:51:57 -04:00
|
|
|
>>> from pyspark.mllib.linalg import SparseVector, DenseVector
|
|
|
|
>>> from pyspark.mllib.regression import LabeledPoint
|
2016-11-01 20:00:00 -04:00
|
|
|
>>> data = sc.parallelize([
|
2015-05-08 18:48:39 -04:00
|
|
|
... LabeledPoint(0.0, SparseVector(3, {0: 8.0, 1: 7.0})),
|
|
|
|
... LabeledPoint(1.0, SparseVector(3, {1: 9.0, 2: 6.0})),
|
|
|
|
... LabeledPoint(1.0, [0.0, 9.0, 8.0]),
|
2016-11-01 20:00:00 -04:00
|
|
|
... LabeledPoint(2.0, [7.0, 9.0, 5.0]),
|
|
|
|
... LabeledPoint(2.0, [8.0, 7.0, 3.0])
|
|
|
|
... ])
|
|
|
|
>>> model = ChiSqSelector(numTopFeatures=1).fit(data)
|
2016-09-21 05:17:38 -04:00
|
|
|
>>> model.transform(SparseVector(3, {1: 9.0, 2: 6.0}))
|
2016-10-14 07:48:57 -04:00
|
|
|
SparseVector(1, {})
|
2016-11-01 20:00:00 -04:00
|
|
|
>>> model.transform(DenseVector([7.0, 9.0, 5.0]))
|
|
|
|
DenseVector([7.0])
|
|
|
|
>>> model = ChiSqSelector(selectorType="fpr", fpr=0.2).fit(data)
|
2015-05-08 18:48:39 -04:00
|
|
|
>>> model.transform(SparseVector(3, {1: 9.0, 2: 6.0}))
|
2016-10-14 07:48:57 -04:00
|
|
|
SparseVector(1, {})
|
2016-11-01 20:00:00 -04:00
|
|
|
>>> model.transform(DenseVector([7.0, 9.0, 5.0]))
|
|
|
|
DenseVector([7.0])
|
|
|
|
>>> model = ChiSqSelector(selectorType="percentile", percentile=0.34).fit(data)
|
|
|
|
>>> model.transform(DenseVector([7.0, 9.0, 5.0]))
|
|
|
|
DenseVector([7.0])
|
2015-09-15 00:58:52 -04:00
|
|
|
|
|
|
|
.. versionadded:: 1.4.0
|
2015-05-08 18:48:39 -04:00
|
|
|
"""
|
[SPARK-17645][MLLIB][ML] add feature selector method based on: False Discovery Rate (FDR) and Family wise error rate (FWE)
## What changes were proposed in this pull request?
Univariate feature selection works by selecting the best features based on univariate statistical tests.
FDR and FWE are a popular univariate statistical test for feature selection.
In 2005, the Benjamini and Hochberg paper on FDR was identified as one of the 25 most-cited statistical papers. The FDR uses the Benjamini-Hochberg procedure in this PR. https://en.wikipedia.org/wiki/False_discovery_rate.
In statistics, FWE is the probability of making one or more false discoveries, or type I errors, among all the hypotheses when performing multiple hypotheses tests.
https://en.wikipedia.org/wiki/Family-wise_error_rate
We add FDR and FWE methods for ChiSqSelector in this PR, like it is implemented in scikit-learn.
http://scikit-learn.org/stable/modules/feature_selection.html#univariate-feature-selection
## How was this patch tested?
ut will be added soon
(Please explain how this patch was tested. E.g. unit tests, integration tests, manual tests)
(If this patch involves UI changes, please attach a screenshot; otherwise, remove this)
Author: Peng <peng.meng@intel.com>
Author: Peng, Meng <peng.meng@intel.com>
Closes #15212 from mpjlu/fdr_fwe.
2016-12-28 03:49:36 -05:00
|
|
|
def __init__(self, numTopFeatures=50, selectorType="numTopFeatures", percentile=0.1, fpr=0.05,
|
|
|
|
fdr=0.05, fwe=0.05):
|
2016-09-21 05:17:38 -04:00
|
|
|
self.numTopFeatures = numTopFeatures
|
[SPARK-17017][FOLLOW-UP][ML] Refactor of ChiSqSelector and add ML Python API.
## What changes were proposed in this pull request?
#14597 modified ```ChiSqSelector``` to support ```fpr``` type selector, however, it left some issue need to be addressed:
* We should allow users to set selector type explicitly rather than switching them by using different setting function, since the setting order will involves some unexpected issue. For example, if users both set ```numTopFeatures``` and ```percentile```, it will train ```kbest``` or ```percentile``` model based on the order of setting (the latter setting one will be trained). This make users confused, and we should allow users to set selector type explicitly. We handle similar issues at other place of ML code base such as ```GeneralizedLinearRegression``` and ```LogisticRegression```.
* Meanwhile, if there are more than one parameter except ```alpha``` can be set for ```fpr``` model, we can not handle it elegantly in the existing framework. And similar issues for ```kbest``` and ```percentile``` model. Setting selector type explicitly can solve this issue also.
* If setting selector type explicitly by users is allowed, we should handle param interaction such as if users set ```selectorType = percentile``` and ```alpha = 0.1```, we should notify users the parameter ```alpha``` will take no effect. We should handle complex parameter interaction checks at ```transformSchema```. (FYI #11620)
* We should use lower case of the selector type names to follow MLlib convention.
* Add ML Python API.
## How was this patch tested?
Unit test.
Author: Yanbo Liang <ybliang8@gmail.com>
Closes #15214 from yanboliang/spark-17017.
2016-09-26 04:45:33 -04:00
|
|
|
self.selectorType = selectorType
|
|
|
|
self.percentile = percentile
|
2016-11-01 20:00:00 -04:00
|
|
|
self.fpr = fpr
|
[SPARK-17645][MLLIB][ML] add feature selector method based on: False Discovery Rate (FDR) and Family wise error rate (FWE)
## What changes were proposed in this pull request?
Univariate feature selection works by selecting the best features based on univariate statistical tests.
FDR and FWE are a popular univariate statistical test for feature selection.
In 2005, the Benjamini and Hochberg paper on FDR was identified as one of the 25 most-cited statistical papers. The FDR uses the Benjamini-Hochberg procedure in this PR. https://en.wikipedia.org/wiki/False_discovery_rate.
In statistics, FWE is the probability of making one or more false discoveries, or type I errors, among all the hypotheses when performing multiple hypotheses tests.
https://en.wikipedia.org/wiki/Family-wise_error_rate
We add FDR and FWE methods for ChiSqSelector in this PR, like it is implemented in scikit-learn.
http://scikit-learn.org/stable/modules/feature_selection.html#univariate-feature-selection
## How was this patch tested?
ut will be added soon
(Please explain how this patch was tested. E.g. unit tests, integration tests, manual tests)
(If this patch involves UI changes, please attach a screenshot; otherwise, remove this)
Author: Peng <peng.meng@intel.com>
Author: Peng, Meng <peng.meng@intel.com>
Closes #15212 from mpjlu/fdr_fwe.
2016-12-28 03:49:36 -05:00
|
|
|
self.fdr = fdr
|
|
|
|
self.fwe = fwe
|
2016-09-21 05:17:38 -04:00
|
|
|
|
|
|
|
@since('2.1.0')
|
|
|
|
def setNumTopFeatures(self, numTopFeatures):
|
|
|
|
"""
|
[SPARK-17017][FOLLOW-UP][ML] Refactor of ChiSqSelector and add ML Python API.
## What changes were proposed in this pull request?
#14597 modified ```ChiSqSelector``` to support ```fpr``` type selector, however, it left some issue need to be addressed:
* We should allow users to set selector type explicitly rather than switching them by using different setting function, since the setting order will involves some unexpected issue. For example, if users both set ```numTopFeatures``` and ```percentile```, it will train ```kbest``` or ```percentile``` model based on the order of setting (the latter setting one will be trained). This make users confused, and we should allow users to set selector type explicitly. We handle similar issues at other place of ML code base such as ```GeneralizedLinearRegression``` and ```LogisticRegression```.
* Meanwhile, if there are more than one parameter except ```alpha``` can be set for ```fpr``` model, we can not handle it elegantly in the existing framework. And similar issues for ```kbest``` and ```percentile``` model. Setting selector type explicitly can solve this issue also.
* If setting selector type explicitly by users is allowed, we should handle param interaction such as if users set ```selectorType = percentile``` and ```alpha = 0.1```, we should notify users the parameter ```alpha``` will take no effect. We should handle complex parameter interaction checks at ```transformSchema```. (FYI #11620)
* We should use lower case of the selector type names to follow MLlib convention.
* Add ML Python API.
## How was this patch tested?
Unit test.
Author: Yanbo Liang <ybliang8@gmail.com>
Closes #15214 from yanboliang/spark-17017.
2016-09-26 04:45:33 -04:00
|
|
|
set numTopFeature for feature selection by number of top features.
|
2016-11-01 20:00:00 -04:00
|
|
|
Only applicable when selectorType = "numTopFeatures".
|
2016-09-21 05:17:38 -04:00
|
|
|
"""
|
2015-05-08 18:48:39 -04:00
|
|
|
self.numTopFeatures = int(numTopFeatures)
|
2016-09-21 05:17:38 -04:00
|
|
|
return self
|
|
|
|
|
|
|
|
@since('2.1.0')
|
|
|
|
def setPercentile(self, percentile):
|
|
|
|
"""
|
[SPARK-17017][FOLLOW-UP][ML] Refactor of ChiSqSelector and add ML Python API.
## What changes were proposed in this pull request?
#14597 modified ```ChiSqSelector``` to support ```fpr``` type selector, however, it left some issue need to be addressed:
* We should allow users to set selector type explicitly rather than switching them by using different setting function, since the setting order will involves some unexpected issue. For example, if users both set ```numTopFeatures``` and ```percentile```, it will train ```kbest``` or ```percentile``` model based on the order of setting (the latter setting one will be trained). This make users confused, and we should allow users to set selector type explicitly. We handle similar issues at other place of ML code base such as ```GeneralizedLinearRegression``` and ```LogisticRegression```.
* Meanwhile, if there are more than one parameter except ```alpha``` can be set for ```fpr``` model, we can not handle it elegantly in the existing framework. And similar issues for ```kbest``` and ```percentile``` model. Setting selector type explicitly can solve this issue also.
* If setting selector type explicitly by users is allowed, we should handle param interaction such as if users set ```selectorType = percentile``` and ```alpha = 0.1```, we should notify users the parameter ```alpha``` will take no effect. We should handle complex parameter interaction checks at ```transformSchema```. (FYI #11620)
* We should use lower case of the selector type names to follow MLlib convention.
* Add ML Python API.
## How was this patch tested?
Unit test.
Author: Yanbo Liang <ybliang8@gmail.com>
Closes #15214 from yanboliang/spark-17017.
2016-09-26 04:45:33 -04:00
|
|
|
set percentile [0.0, 1.0] for feature selection by percentile.
|
|
|
|
Only applicable when selectorType = "percentile".
|
2016-09-21 05:17:38 -04:00
|
|
|
"""
|
|
|
|
self.percentile = float(percentile)
|
|
|
|
return self
|
|
|
|
|
|
|
|
@since('2.1.0')
|
2016-11-01 20:00:00 -04:00
|
|
|
def setFpr(self, fpr):
|
2016-09-21 05:17:38 -04:00
|
|
|
"""
|
2016-11-01 20:00:00 -04:00
|
|
|
set FPR [0.0, 1.0] for feature selection by FPR.
|
[SPARK-17017][FOLLOW-UP][ML] Refactor of ChiSqSelector and add ML Python API.
## What changes were proposed in this pull request?
#14597 modified ```ChiSqSelector``` to support ```fpr``` type selector, however, it left some issue need to be addressed:
* We should allow users to set selector type explicitly rather than switching them by using different setting function, since the setting order will involves some unexpected issue. For example, if users both set ```numTopFeatures``` and ```percentile```, it will train ```kbest``` or ```percentile``` model based on the order of setting (the latter setting one will be trained). This make users confused, and we should allow users to set selector type explicitly. We handle similar issues at other place of ML code base such as ```GeneralizedLinearRegression``` and ```LogisticRegression```.
* Meanwhile, if there are more than one parameter except ```alpha``` can be set for ```fpr``` model, we can not handle it elegantly in the existing framework. And similar issues for ```kbest``` and ```percentile``` model. Setting selector type explicitly can solve this issue also.
* If setting selector type explicitly by users is allowed, we should handle param interaction such as if users set ```selectorType = percentile``` and ```alpha = 0.1```, we should notify users the parameter ```alpha``` will take no effect. We should handle complex parameter interaction checks at ```transformSchema```. (FYI #11620)
* We should use lower case of the selector type names to follow MLlib convention.
* Add ML Python API.
## How was this patch tested?
Unit test.
Author: Yanbo Liang <ybliang8@gmail.com>
Closes #15214 from yanboliang/spark-17017.
2016-09-26 04:45:33 -04:00
|
|
|
Only applicable when selectorType = "fpr".
|
2016-09-21 05:17:38 -04:00
|
|
|
"""
|
2016-11-01 20:00:00 -04:00
|
|
|
self.fpr = float(fpr)
|
[SPARK-17017][FOLLOW-UP][ML] Refactor of ChiSqSelector and add ML Python API.
## What changes were proposed in this pull request?
#14597 modified ```ChiSqSelector``` to support ```fpr``` type selector, however, it left some issue need to be addressed:
* We should allow users to set selector type explicitly rather than switching them by using different setting function, since the setting order will involves some unexpected issue. For example, if users both set ```numTopFeatures``` and ```percentile```, it will train ```kbest``` or ```percentile``` model based on the order of setting (the latter setting one will be trained). This make users confused, and we should allow users to set selector type explicitly. We handle similar issues at other place of ML code base such as ```GeneralizedLinearRegression``` and ```LogisticRegression```.
* Meanwhile, if there are more than one parameter except ```alpha``` can be set for ```fpr``` model, we can not handle it elegantly in the existing framework. And similar issues for ```kbest``` and ```percentile``` model. Setting selector type explicitly can solve this issue also.
* If setting selector type explicitly by users is allowed, we should handle param interaction such as if users set ```selectorType = percentile``` and ```alpha = 0.1```, we should notify users the parameter ```alpha``` will take no effect. We should handle complex parameter interaction checks at ```transformSchema```. (FYI #11620)
* We should use lower case of the selector type names to follow MLlib convention.
* Add ML Python API.
## How was this patch tested?
Unit test.
Author: Yanbo Liang <ybliang8@gmail.com>
Closes #15214 from yanboliang/spark-17017.
2016-09-26 04:45:33 -04:00
|
|
|
return self
|
|
|
|
|
[SPARK-17645][MLLIB][ML] add feature selector method based on: False Discovery Rate (FDR) and Family wise error rate (FWE)
## What changes were proposed in this pull request?
Univariate feature selection works by selecting the best features based on univariate statistical tests.
FDR and FWE are a popular univariate statistical test for feature selection.
In 2005, the Benjamini and Hochberg paper on FDR was identified as one of the 25 most-cited statistical papers. The FDR uses the Benjamini-Hochberg procedure in this PR. https://en.wikipedia.org/wiki/False_discovery_rate.
In statistics, FWE is the probability of making one or more false discoveries, or type I errors, among all the hypotheses when performing multiple hypotheses tests.
https://en.wikipedia.org/wiki/Family-wise_error_rate
We add FDR and FWE methods for ChiSqSelector in this PR, like it is implemented in scikit-learn.
http://scikit-learn.org/stable/modules/feature_selection.html#univariate-feature-selection
## How was this patch tested?
ut will be added soon
(Please explain how this patch was tested. E.g. unit tests, integration tests, manual tests)
(If this patch involves UI changes, please attach a screenshot; otherwise, remove this)
Author: Peng <peng.meng@intel.com>
Author: Peng, Meng <peng.meng@intel.com>
Closes #15212 from mpjlu/fdr_fwe.
2016-12-28 03:49:36 -05:00
|
|
|
@since('2.2.0')
|
|
|
|
def setFdr(self, fdr):
|
|
|
|
"""
|
|
|
|
set FDR [0.0, 1.0] for feature selection by FDR.
|
|
|
|
Only applicable when selectorType = "fdr".
|
|
|
|
"""
|
|
|
|
self.fdr = float(fdr)
|
|
|
|
return self
|
|
|
|
|
|
|
|
@since('2.2.0')
|
|
|
|
def setFwe(self, fwe):
|
|
|
|
"""
|
|
|
|
set FWE [0.0, 1.0] for feature selection by FWE.
|
|
|
|
Only applicable when selectorType = "fwe".
|
|
|
|
"""
|
|
|
|
self.fwe = float(fwe)
|
|
|
|
return self
|
|
|
|
|
[SPARK-17017][FOLLOW-UP][ML] Refactor of ChiSqSelector and add ML Python API.
## What changes were proposed in this pull request?
#14597 modified ```ChiSqSelector``` to support ```fpr``` type selector, however, it left some issue need to be addressed:
* We should allow users to set selector type explicitly rather than switching them by using different setting function, since the setting order will involves some unexpected issue. For example, if users both set ```numTopFeatures``` and ```percentile```, it will train ```kbest``` or ```percentile``` model based on the order of setting (the latter setting one will be trained). This make users confused, and we should allow users to set selector type explicitly. We handle similar issues at other place of ML code base such as ```GeneralizedLinearRegression``` and ```LogisticRegression```.
* Meanwhile, if there are more than one parameter except ```alpha``` can be set for ```fpr``` model, we can not handle it elegantly in the existing framework. And similar issues for ```kbest``` and ```percentile``` model. Setting selector type explicitly can solve this issue also.
* If setting selector type explicitly by users is allowed, we should handle param interaction such as if users set ```selectorType = percentile``` and ```alpha = 0.1```, we should notify users the parameter ```alpha``` will take no effect. We should handle complex parameter interaction checks at ```transformSchema```. (FYI #11620)
* We should use lower case of the selector type names to follow MLlib convention.
* Add ML Python API.
## How was this patch tested?
Unit test.
Author: Yanbo Liang <ybliang8@gmail.com>
Closes #15214 from yanboliang/spark-17017.
2016-09-26 04:45:33 -04:00
|
|
|
@since('2.1.0')
|
|
|
|
def setSelectorType(self, selectorType):
|
|
|
|
"""
|
|
|
|
set the selector type of the ChisqSelector.
|
[SPARK-17645][MLLIB][ML] add feature selector method based on: False Discovery Rate (FDR) and Family wise error rate (FWE)
## What changes were proposed in this pull request?
Univariate feature selection works by selecting the best features based on univariate statistical tests.
FDR and FWE are a popular univariate statistical test for feature selection.
In 2005, the Benjamini and Hochberg paper on FDR was identified as one of the 25 most-cited statistical papers. The FDR uses the Benjamini-Hochberg procedure in this PR. https://en.wikipedia.org/wiki/False_discovery_rate.
In statistics, FWE is the probability of making one or more false discoveries, or type I errors, among all the hypotheses when performing multiple hypotheses tests.
https://en.wikipedia.org/wiki/Family-wise_error_rate
We add FDR and FWE methods for ChiSqSelector in this PR, like it is implemented in scikit-learn.
http://scikit-learn.org/stable/modules/feature_selection.html#univariate-feature-selection
## How was this patch tested?
ut will be added soon
(Please explain how this patch was tested. E.g. unit tests, integration tests, manual tests)
(If this patch involves UI changes, please attach a screenshot; otherwise, remove this)
Author: Peng <peng.meng@intel.com>
Author: Peng, Meng <peng.meng@intel.com>
Closes #15212 from mpjlu/fdr_fwe.
2016-12-28 03:49:36 -05:00
|
|
|
Supported options: "numTopFeatures" (default), "percentile", "fpr", "fdr", "fwe".
|
[SPARK-17017][FOLLOW-UP][ML] Refactor of ChiSqSelector and add ML Python API.
## What changes were proposed in this pull request?
#14597 modified ```ChiSqSelector``` to support ```fpr``` type selector, however, it left some issue need to be addressed:
* We should allow users to set selector type explicitly rather than switching them by using different setting function, since the setting order will involves some unexpected issue. For example, if users both set ```numTopFeatures``` and ```percentile```, it will train ```kbest``` or ```percentile``` model based on the order of setting (the latter setting one will be trained). This make users confused, and we should allow users to set selector type explicitly. We handle similar issues at other place of ML code base such as ```GeneralizedLinearRegression``` and ```LogisticRegression```.
* Meanwhile, if there are more than one parameter except ```alpha``` can be set for ```fpr``` model, we can not handle it elegantly in the existing framework. And similar issues for ```kbest``` and ```percentile``` model. Setting selector type explicitly can solve this issue also.
* If setting selector type explicitly by users is allowed, we should handle param interaction such as if users set ```selectorType = percentile``` and ```alpha = 0.1```, we should notify users the parameter ```alpha``` will take no effect. We should handle complex parameter interaction checks at ```transformSchema```. (FYI #11620)
* We should use lower case of the selector type names to follow MLlib convention.
* Add ML Python API.
## How was this patch tested?
Unit test.
Author: Yanbo Liang <ybliang8@gmail.com>
Closes #15214 from yanboliang/spark-17017.
2016-09-26 04:45:33 -04:00
|
|
|
"""
|
|
|
|
self.selectorType = str(selectorType)
|
2016-09-21 05:17:38 -04:00
|
|
|
return self
|
2015-05-08 18:48:39 -04:00
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.4.0')
|
2015-05-08 18:48:39 -04:00
|
|
|
def fit(self, data):
|
|
|
|
"""
|
|
|
|
Returns a ChiSquared feature selector.
|
|
|
|
|
|
|
|
:param data: an `RDD[LabeledPoint]` containing the labeled dataset
|
2015-05-30 19:24:07 -04:00
|
|
|
with categorical features. Real-valued features will be
|
|
|
|
treated as categorical for each distinct value.
|
|
|
|
Apply feature discretizer before using this function.
|
2015-05-08 18:48:39 -04:00
|
|
|
"""
|
[SPARK-17017][FOLLOW-UP][ML] Refactor of ChiSqSelector and add ML Python API.
## What changes were proposed in this pull request?
#14597 modified ```ChiSqSelector``` to support ```fpr``` type selector, however, it left some issue need to be addressed:
* We should allow users to set selector type explicitly rather than switching them by using different setting function, since the setting order will involves some unexpected issue. For example, if users both set ```numTopFeatures``` and ```percentile```, it will train ```kbest``` or ```percentile``` model based on the order of setting (the latter setting one will be trained). This make users confused, and we should allow users to set selector type explicitly. We handle similar issues at other place of ML code base such as ```GeneralizedLinearRegression``` and ```LogisticRegression```.
* Meanwhile, if there are more than one parameter except ```alpha``` can be set for ```fpr``` model, we can not handle it elegantly in the existing framework. And similar issues for ```kbest``` and ```percentile``` model. Setting selector type explicitly can solve this issue also.
* If setting selector type explicitly by users is allowed, we should handle param interaction such as if users set ```selectorType = percentile``` and ```alpha = 0.1```, we should notify users the parameter ```alpha``` will take no effect. We should handle complex parameter interaction checks at ```transformSchema```. (FYI #11620)
* We should use lower case of the selector type names to follow MLlib convention.
* Add ML Python API.
## How was this patch tested?
Unit test.
Author: Yanbo Liang <ybliang8@gmail.com>
Closes #15214 from yanboliang/spark-17017.
2016-09-26 04:45:33 -04:00
|
|
|
jmodel = callMLlibFunc("fitChiSqSelector", self.selectorType, self.numTopFeatures,
|
[SPARK-17645][MLLIB][ML] add feature selector method based on: False Discovery Rate (FDR) and Family wise error rate (FWE)
## What changes were proposed in this pull request?
Univariate feature selection works by selecting the best features based on univariate statistical tests.
FDR and FWE are a popular univariate statistical test for feature selection.
In 2005, the Benjamini and Hochberg paper on FDR was identified as one of the 25 most-cited statistical papers. The FDR uses the Benjamini-Hochberg procedure in this PR. https://en.wikipedia.org/wiki/False_discovery_rate.
In statistics, FWE is the probability of making one or more false discoveries, or type I errors, among all the hypotheses when performing multiple hypotheses tests.
https://en.wikipedia.org/wiki/Family-wise_error_rate
We add FDR and FWE methods for ChiSqSelector in this PR, like it is implemented in scikit-learn.
http://scikit-learn.org/stable/modules/feature_selection.html#univariate-feature-selection
## How was this patch tested?
ut will be added soon
(Please explain how this patch was tested. E.g. unit tests, integration tests, manual tests)
(If this patch involves UI changes, please attach a screenshot; otherwise, remove this)
Author: Peng <peng.meng@intel.com>
Author: Peng, Meng <peng.meng@intel.com>
Closes #15212 from mpjlu/fdr_fwe.
2016-12-28 03:49:36 -05:00
|
|
|
self.percentile, self.fpr, self.fdr, self.fwe, data)
|
2015-05-08 18:48:39 -04:00
|
|
|
return ChiSqSelectorModel(jmodel)
|
|
|
|
|
|
|
|
|
2015-06-21 15:04:20 -04:00
|
|
|
class PCAModel(JavaVectorTransformer):
|
|
|
|
"""
|
|
|
|
Model fitted by [[PCA]] that can project vectors to a low-dimensional space using PCA.
|
2015-09-15 00:58:52 -04:00
|
|
|
|
|
|
|
.. versionadded:: 1.5.0
|
2015-06-21 15:04:20 -04:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
class PCA(object):
|
|
|
|
"""
|
|
|
|
A feature transformer that projects vectors to a low-dimensional space using PCA.
|
|
|
|
|
|
|
|
>>> data = [Vectors.sparse(5, [(1, 1.0), (3, 7.0)]),
|
|
|
|
... Vectors.dense([2.0, 0.0, 3.0, 4.0, 5.0]),
|
|
|
|
... Vectors.dense([4.0, 0.0, 0.0, 6.0, 7.0])]
|
|
|
|
>>> model = PCA(2).fit(sc.parallelize(data))
|
|
|
|
>>> pcArray = model.transform(Vectors.sparse(5, [(1, 1.0), (3, 7.0)])).toArray()
|
|
|
|
>>> pcArray[0]
|
|
|
|
1.648...
|
|
|
|
>>> pcArray[1]
|
|
|
|
-4.013...
|
2015-09-15 00:58:52 -04:00
|
|
|
|
|
|
|
.. versionadded:: 1.5.0
|
2015-06-21 15:04:20 -04:00
|
|
|
"""
|
|
|
|
def __init__(self, k):
|
|
|
|
"""
|
|
|
|
:param k: number of principal components.
|
|
|
|
"""
|
|
|
|
self.k = int(k)
|
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.5.0')
|
2015-06-21 15:04:20 -04:00
|
|
|
def fit(self, data):
|
|
|
|
"""
|
|
|
|
Computes a [[PCAModel]] that contains the principal components of the input vectors.
|
|
|
|
:param data: source vectors
|
|
|
|
"""
|
|
|
|
jmodel = callMLlibFunc("fitPCA", self.k, data)
|
|
|
|
return PCAModel(jmodel)
|
|
|
|
|
|
|
|
|
2014-10-28 06:50:22 -04:00
|
|
|
class HashingTF(object):
|
|
|
|
"""
|
2015-02-25 19:13:17 -05:00
|
|
|
Maps a sequence of terms to their term frequencies using the hashing
|
|
|
|
trick.
|
2014-10-28 06:50:22 -04:00
|
|
|
|
2016-11-22 06:40:18 -05:00
|
|
|
.. note:: The terms must be hashable (can not be dict/set/list...).
|
2014-10-28 06:50:22 -04:00
|
|
|
|
2015-05-30 19:24:07 -04:00
|
|
|
:param numFeatures: number of features (default: 2^20)
|
|
|
|
|
2014-10-28 06:50:22 -04:00
|
|
|
>>> htf = HashingTF(100)
|
|
|
|
>>> doc = "a a b b c d".split(" ")
|
|
|
|
>>> htf.transform(doc)
|
2015-04-16 19:20:57 -04:00
|
|
|
SparseVector(100, {...})
|
2015-09-15 00:58:52 -04:00
|
|
|
|
|
|
|
.. versionadded:: 1.2.0
|
2014-10-28 06:50:22 -04:00
|
|
|
"""
|
|
|
|
def __init__(self, numFeatures=1 << 20):
|
|
|
|
self.numFeatures = numFeatures
|
2016-04-14 15:53:32 -04:00
|
|
|
self.binary = False
|
|
|
|
|
|
|
|
@since("2.0.0")
|
|
|
|
def setBinary(self, value):
|
|
|
|
"""
|
|
|
|
If True, term frequency vector will be binary such that non-zero
|
|
|
|
term counts will be set to 1
|
|
|
|
(default: False)
|
|
|
|
"""
|
|
|
|
self.binary = value
|
|
|
|
return self
|
2014-10-28 06:50:22 -04:00
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.2.0')
|
2014-10-28 06:50:22 -04:00
|
|
|
def indexOf(self, term):
|
|
|
|
""" Returns the index of the input term. """
|
|
|
|
return hash(term) % self.numFeatures
|
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.2.0')
|
2014-10-28 06:50:22 -04:00
|
|
|
def transform(self, document):
|
|
|
|
"""
|
2015-02-25 19:13:17 -05:00
|
|
|
Transforms the input document (list of terms) to term frequency
|
|
|
|
vectors, or transform the RDD of document to RDD of term
|
|
|
|
frequency vectors.
|
2014-10-28 06:50:22 -04:00
|
|
|
"""
|
|
|
|
if isinstance(document, RDD):
|
|
|
|
return document.map(self.transform)
|
|
|
|
|
|
|
|
freq = {}
|
|
|
|
for term in document:
|
|
|
|
i = self.indexOf(term)
|
2016-04-14 15:53:32 -04:00
|
|
|
freq[i] = 1.0 if self.binary else freq.get(i, 0) + 1.0
|
2014-10-28 06:50:22 -04:00
|
|
|
return Vectors.sparse(self.numFeatures, freq.items())
|
|
|
|
|
|
|
|
|
2014-10-31 01:25:18 -04:00
|
|
|
class IDFModel(JavaVectorTransformer):
|
2014-10-28 06:50:22 -04:00
|
|
|
"""
|
|
|
|
Represents an IDF model that can transform term frequency vectors.
|
2015-09-15 00:58:52 -04:00
|
|
|
|
|
|
|
.. versionadded:: 1.2.0
|
2014-10-28 06:50:22 -04:00
|
|
|
"""
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.2.0')
|
2014-12-15 16:44:15 -05:00
|
|
|
def transform(self, x):
|
2014-10-28 06:50:22 -04:00
|
|
|
"""
|
|
|
|
Transforms term frequency (TF) vectors to TF-IDF vectors.
|
|
|
|
|
|
|
|
If `minDocFreq` was set for the IDF calculation,
|
|
|
|
the terms which occur in fewer than `minDocFreq`
|
|
|
|
documents will have an entry of 0.
|
|
|
|
|
2016-11-22 06:40:18 -05:00
|
|
|
.. note:: In Python, transform cannot currently be used within
|
|
|
|
an RDD transformation or action.
|
|
|
|
Call transform directly on the RDD instead.
|
2015-02-25 19:13:17 -05:00
|
|
|
|
|
|
|
:param x: an RDD of term frequency vectors or a term frequency
|
2015-05-30 19:24:07 -04:00
|
|
|
vector
|
2014-12-15 16:44:15 -05:00
|
|
|
:return: an RDD of TF-IDF vectors or a TF-IDF vector
|
2014-10-28 06:50:22 -04:00
|
|
|
"""
|
2014-12-15 16:44:15 -05:00
|
|
|
return JavaVectorTransformer.transform(self, x)
|
2014-10-28 06:50:22 -04:00
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.4.0')
|
2015-03-31 14:25:21 -04:00
|
|
|
def idf(self):
|
|
|
|
"""
|
|
|
|
Returns the current IDF vector.
|
|
|
|
"""
|
|
|
|
return self.call('idf')
|
|
|
|
|
2019-01-22 08:41:54 -05:00
|
|
|
@since('3.0.0')
|
|
|
|
def docFreq(self):
|
|
|
|
"""
|
|
|
|
Returns the document frequency.
|
|
|
|
"""
|
|
|
|
return self.call('docFreq')
|
|
|
|
|
|
|
|
@since('3.0.0')
|
|
|
|
def numDocs(self):
|
|
|
|
"""
|
|
|
|
Returns number of documents evaluated to compute idf
|
|
|
|
"""
|
|
|
|
return self.call('numDocs')
|
|
|
|
|
2014-10-28 06:50:22 -04:00
|
|
|
|
|
|
|
class IDF(object):
|
|
|
|
"""
|
|
|
|
Inverse document frequency (IDF).
|
|
|
|
|
|
|
|
The standard formulation is used: `idf = log((m + 1) / (d(t) + 1))`,
|
|
|
|
where `m` is the total number of documents and `d(t)` is the number
|
|
|
|
of documents that contain term `t`.
|
|
|
|
|
|
|
|
This implementation supports filtering out terms which do not appear
|
2015-02-25 19:13:17 -05:00
|
|
|
in a minimum number of documents (controlled by the variable
|
|
|
|
`minDocFreq`). For terms that are not in at least `minDocFreq`
|
|
|
|
documents, the IDF is found as 0, resulting in TF-IDFs of 0.
|
2014-10-28 06:50:22 -04:00
|
|
|
|
2015-05-30 19:24:07 -04:00
|
|
|
:param minDocFreq: minimum of documents in which a term
|
|
|
|
should appear for filtering
|
|
|
|
|
2014-10-28 06:50:22 -04:00
|
|
|
>>> n = 4
|
|
|
|
>>> freqs = [Vectors.sparse(n, (1, 3), (1.0, 2.0)),
|
|
|
|
... Vectors.dense([0.0, 1.0, 2.0, 3.0]),
|
|
|
|
... Vectors.sparse(n, [1], [1.0])]
|
|
|
|
>>> data = sc.parallelize(freqs)
|
|
|
|
>>> idf = IDF()
|
|
|
|
>>> model = idf.fit(data)
|
|
|
|
>>> tfidf = model.transform(data)
|
|
|
|
>>> for r in tfidf.collect(): r
|
|
|
|
SparseVector(4, {1: 0.0, 3: 0.5754})
|
|
|
|
DenseVector([0.0, 0.0, 1.3863, 0.863])
|
|
|
|
SparseVector(4, {1: 0.0})
|
2014-12-15 16:44:15 -05:00
|
|
|
>>> model.transform(Vectors.dense([0.0, 1.0, 2.0, 3.0]))
|
|
|
|
DenseVector([0.0, 0.0, 1.3863, 0.863])
|
|
|
|
>>> model.transform([0.0, 1.0, 2.0, 3.0])
|
|
|
|
DenseVector([0.0, 0.0, 1.3863, 0.863])
|
|
|
|
>>> model.transform(Vectors.sparse(n, (1, 3), (1.0, 2.0)))
|
|
|
|
SparseVector(4, {1: 0.0, 3: 0.5754})
|
2015-09-15 00:58:52 -04:00
|
|
|
|
|
|
|
.. versionadded:: 1.2.0
|
2014-10-28 06:50:22 -04:00
|
|
|
"""
|
|
|
|
def __init__(self, minDocFreq=0):
|
|
|
|
self.minDocFreq = minDocFreq
|
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.2.0')
|
2014-10-28 06:50:22 -04:00
|
|
|
def fit(self, dataset):
|
|
|
|
"""
|
|
|
|
Computes the inverse document frequency.
|
|
|
|
|
|
|
|
:param dataset: an RDD of term frequency vectors
|
|
|
|
"""
|
2014-11-11 01:26:16 -05:00
|
|
|
if not isinstance(dataset, RDD):
|
|
|
|
raise TypeError("dataset should be an RDD of term frequency vectors")
|
|
|
|
jmodel = callMLlibFunc("fitIDF", self.minDocFreq, dataset.map(_convert_to_vector))
|
2014-10-31 01:25:18 -04:00
|
|
|
return IDFModel(jmodel)
|
2014-10-28 06:50:22 -04:00
|
|
|
|
|
|
|
|
2015-07-02 18:55:16 -04:00
|
|
|
class Word2VecModel(JavaVectorTransformer, JavaSaveable, JavaLoader):
|
2014-10-28 06:50:22 -04:00
|
|
|
"""
|
|
|
|
class for Word2Vec model
|
2015-09-15 00:58:52 -04:00
|
|
|
|
|
|
|
.. versionadded:: 1.2.0
|
2014-10-28 06:50:22 -04:00
|
|
|
"""
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.2.0')
|
2014-10-28 06:50:22 -04:00
|
|
|
def transform(self, word):
|
|
|
|
"""
|
2014-10-07 19:43:34 -04:00
|
|
|
Transforms a word to its vector representation
|
|
|
|
|
2016-11-22 06:40:18 -05:00
|
|
|
.. note:: Local use only
|
2014-10-28 06:50:22 -04:00
|
|
|
|
|
|
|
:param word: a word
|
|
|
|
:return: vector representation of word(s)
|
2014-10-07 19:43:34 -04:00
|
|
|
"""
|
2014-10-28 06:50:22 -04:00
|
|
|
try:
|
2014-10-31 01:25:18 -04:00
|
|
|
return self.call("transform", word)
|
2014-10-28 06:50:22 -04:00
|
|
|
except Py4JJavaError:
|
|
|
|
raise ValueError("%s not found" % word)
|
2014-10-07 19:43:34 -04:00
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.2.0')
|
2014-10-28 06:50:22 -04:00
|
|
|
def findSynonyms(self, word, num):
|
2014-10-07 19:43:34 -04:00
|
|
|
"""
|
2014-10-28 06:50:22 -04:00
|
|
|
Find synonyms of a word
|
|
|
|
|
|
|
|
:param word: a word or a vector representation of word
|
2014-10-07 19:43:34 -04:00
|
|
|
:param num: number of synonyms to find
|
|
|
|
:return: array of (word, cosineSimilarity)
|
2014-10-11 14:51:59 -04:00
|
|
|
|
2016-11-22 06:40:18 -05:00
|
|
|
.. note:: Local use only
|
2014-10-07 19:43:34 -04:00
|
|
|
"""
|
2020-07-13 22:22:44 -04:00
|
|
|
if not isinstance(word, str):
|
2014-11-11 01:26:16 -05:00
|
|
|
word = _convert_to_vector(word)
|
2014-10-31 01:25:18 -04:00
|
|
|
words, similarity = self.call("findSynonyms", word, num)
|
2014-10-07 19:43:34 -04:00
|
|
|
return zip(words, similarity)
|
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.4.0')
|
2015-04-03 12:49:50 -04:00
|
|
|
def getVectors(self):
|
|
|
|
"""
|
|
|
|
Returns a map of words to their vector representations.
|
|
|
|
"""
|
|
|
|
return self.call("getVectors")
|
|
|
|
|
2015-07-02 18:55:16 -04:00
|
|
|
@classmethod
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.5.0')
|
2015-07-02 18:55:16 -04:00
|
|
|
def load(cls, sc, path):
|
2015-09-15 00:58:52 -04:00
|
|
|
"""
|
|
|
|
Load a model from the given path.
|
|
|
|
"""
|
2015-07-02 18:55:16 -04:00
|
|
|
jmodel = sc._jvm.org.apache.spark.mllib.feature \
|
|
|
|
.Word2VecModel.load(sc._jsc.sc(), path)
|
2016-07-05 20:00:24 -04:00
|
|
|
model = sc._jvm.org.apache.spark.mllib.api.python.Word2VecModelWrapper(jmodel)
|
2015-12-14 12:59:42 -05:00
|
|
|
return Word2VecModel(model)
|
2015-07-02 18:55:16 -04:00
|
|
|
|
2014-10-07 19:43:34 -04:00
|
|
|
|
|
|
|
class Word2Vec(object):
|
2016-09-17 07:49:58 -04:00
|
|
|
"""Word2Vec creates vector representation of words in a text corpus.
|
2014-10-07 19:43:34 -04:00
|
|
|
The algorithm first constructs a vocabulary from the corpus
|
|
|
|
and then learns vector representation of words in the vocabulary.
|
|
|
|
The vector representation can be used as features in
|
|
|
|
natural language processing and machine learning algorithms.
|
|
|
|
|
2015-02-25 19:13:17 -05:00
|
|
|
We used skip-gram model in our implementation and hierarchical
|
|
|
|
softmax method to train the model. The variable names in the
|
|
|
|
implementation matches the original C implementation.
|
2014-10-28 06:50:22 -04:00
|
|
|
|
2015-02-25 19:13:17 -05:00
|
|
|
For original C implementation,
|
|
|
|
see https://code.google.com/p/word2vec/
|
2014-10-07 19:43:34 -04:00
|
|
|
For research papers, see
|
|
|
|
Efficient Estimation of Word Representations in Vector Space
|
2015-02-25 19:13:17 -05:00
|
|
|
and Distributed Representations of Words and Phrases and their
|
|
|
|
Compositionality.
|
2014-10-07 19:43:34 -04:00
|
|
|
|
|
|
|
>>> sentence = "a b " * 100 + "a c " * 10
|
|
|
|
>>> localDoc = [sentence, sentence]
|
|
|
|
>>> doc = sc.parallelize(localDoc).map(lambda line: line.split(" "))
|
2015-04-16 19:20:57 -04:00
|
|
|
>>> model = Word2Vec().setVectorSize(10).setSeed(42).fit(doc)
|
2014-10-28 06:50:22 -04:00
|
|
|
|
2016-09-17 07:49:58 -04:00
|
|
|
Querying for synonyms of a word will not return that word:
|
|
|
|
|
2014-10-07 19:43:34 -04:00
|
|
|
>>> syms = model.findSynonyms("a", 2)
|
2014-10-28 06:50:22 -04:00
|
|
|
>>> [s[0] for s in syms]
|
2020-07-13 22:22:44 -04:00
|
|
|
['b', 'c']
|
2016-09-17 07:49:58 -04:00
|
|
|
|
|
|
|
But querying for synonyms of a vector may return the word whose
|
|
|
|
representation is that vector:
|
|
|
|
|
2014-10-07 19:43:34 -04:00
|
|
|
>>> vec = model.transform("a")
|
|
|
|
>>> syms = model.findSynonyms(vec, 2)
|
2014-10-28 06:50:22 -04:00
|
|
|
>>> [s[0] for s in syms]
|
2020-07-13 22:22:44 -04:00
|
|
|
['a', 'b']
|
2015-07-02 18:55:16 -04:00
|
|
|
|
|
|
|
>>> import os, tempfile
|
|
|
|
>>> path = tempfile.mkdtemp()
|
|
|
|
>>> model.save(sc, path)
|
|
|
|
>>> sameModel = Word2VecModel.load(sc, path)
|
|
|
|
>>> model.transform("a") == sameModel.transform("a")
|
|
|
|
True
|
2015-12-14 12:59:42 -05:00
|
|
|
>>> syms = sameModel.findSynonyms("a", 2)
|
|
|
|
>>> [s[0] for s in syms]
|
2020-07-13 22:22:44 -04:00
|
|
|
['b', 'c']
|
2015-07-02 18:55:16 -04:00
|
|
|
>>> from shutil import rmtree
|
|
|
|
>>> try:
|
|
|
|
... rmtree(path)
|
|
|
|
... except OSError:
|
|
|
|
... pass
|
2015-09-15 00:58:52 -04:00
|
|
|
|
|
|
|
.. versionadded:: 1.2.0
|
2016-09-17 07:49:58 -04:00
|
|
|
|
2014-10-07 19:43:34 -04:00
|
|
|
"""
|
|
|
|
def __init__(self):
|
|
|
|
"""
|
|
|
|
Construct Word2Vec instance
|
|
|
|
"""
|
|
|
|
self.vectorSize = 100
|
|
|
|
self.learningRate = 0.025
|
|
|
|
self.numPartitions = 1
|
|
|
|
self.numIterations = 1
|
2016-09-04 07:40:51 -04:00
|
|
|
self.seed = None
|
2015-04-03 12:49:50 -04:00
|
|
|
self.minCount = 5
|
2016-04-18 15:47:14 -04:00
|
|
|
self.windowSize = 5
|
2014-10-07 19:43:34 -04:00
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.2.0')
|
2014-10-07 19:43:34 -04:00
|
|
|
def setVectorSize(self, vectorSize):
|
|
|
|
"""
|
|
|
|
Sets vector size (default: 100).
|
|
|
|
"""
|
|
|
|
self.vectorSize = vectorSize
|
|
|
|
return self
|
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.2.0')
|
2014-10-07 19:43:34 -04:00
|
|
|
def setLearningRate(self, learningRate):
|
|
|
|
"""
|
|
|
|
Sets initial learning rate (default: 0.025).
|
|
|
|
"""
|
|
|
|
self.learningRate = learningRate
|
|
|
|
return self
|
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.2.0')
|
2014-10-07 19:43:34 -04:00
|
|
|
def setNumPartitions(self, numPartitions):
|
|
|
|
"""
|
2015-02-25 19:13:17 -05:00
|
|
|
Sets number of partitions (default: 1). Use a small number for
|
|
|
|
accuracy.
|
2014-10-07 19:43:34 -04:00
|
|
|
"""
|
|
|
|
self.numPartitions = numPartitions
|
|
|
|
return self
|
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.2.0')
|
2014-10-07 19:43:34 -04:00
|
|
|
def setNumIterations(self, numIterations):
|
|
|
|
"""
|
2015-02-25 19:13:17 -05:00
|
|
|
Sets number of iterations (default: 1), which should be smaller
|
|
|
|
than or equal to number of partitions.
|
2014-10-07 19:43:34 -04:00
|
|
|
"""
|
|
|
|
self.numIterations = numIterations
|
|
|
|
return self
|
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.2.0')
|
2014-10-07 19:43:34 -04:00
|
|
|
def setSeed(self, seed):
|
|
|
|
"""
|
|
|
|
Sets random seed.
|
|
|
|
"""
|
|
|
|
self.seed = seed
|
|
|
|
return self
|
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.4.0')
|
2015-04-03 12:49:50 -04:00
|
|
|
def setMinCount(self, minCount):
|
|
|
|
"""
|
|
|
|
Sets minCount, the minimum number of times a token must appear
|
|
|
|
to be included in the word2vec model's vocabulary (default: 5).
|
|
|
|
"""
|
|
|
|
self.minCount = minCount
|
|
|
|
return self
|
|
|
|
|
2016-04-18 15:47:14 -04:00
|
|
|
@since('2.0.0')
|
|
|
|
def setWindowSize(self, windowSize):
|
|
|
|
"""
|
|
|
|
Sets window size (default: 5).
|
|
|
|
"""
|
|
|
|
self.windowSize = windowSize
|
|
|
|
return self
|
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.2.0')
|
2014-10-07 19:43:34 -04:00
|
|
|
def fit(self, data):
|
|
|
|
"""
|
|
|
|
Computes the vector representation of each word in vocabulary.
|
|
|
|
|
2014-11-11 01:26:16 -05:00
|
|
|
:param data: training data. RDD of list of string
|
2014-10-28 06:50:22 -04:00
|
|
|
:return: Word2VecModel instance
|
2014-10-07 19:43:34 -04:00
|
|
|
"""
|
2014-11-11 01:26:16 -05:00
|
|
|
if not isinstance(data, RDD):
|
|
|
|
raise TypeError("data should be an RDD of list of string")
|
2015-06-25 11:13:17 -04:00
|
|
|
jmodel = callMLlibFunc("trainWord2VecModel", data, int(self.vectorSize),
|
2014-10-31 01:25:18 -04:00
|
|
|
float(self.learningRate), int(self.numPartitions),
|
2016-09-04 07:40:51 -04:00
|
|
|
int(self.numIterations), self.seed,
|
2016-04-18 15:47:14 -04:00
|
|
|
int(self.minCount), int(self.windowSize))
|
2014-10-31 01:25:18 -04:00
|
|
|
return Word2VecModel(jmodel)
|
2014-10-07 19:43:34 -04:00
|
|
|
|
|
|
|
|
2015-06-18 01:08:38 -04:00
|
|
|
class ElementwiseProduct(VectorTransformer):
|
|
|
|
"""
|
|
|
|
Scales each column of the vector, with the supplied weight vector.
|
|
|
|
i.e the elementwise product.
|
|
|
|
|
|
|
|
>>> weight = Vectors.dense([1.0, 2.0, 3.0])
|
|
|
|
>>> eprod = ElementwiseProduct(weight)
|
|
|
|
>>> a = Vectors.dense([2.0, 1.0, 3.0])
|
|
|
|
>>> eprod.transform(a)
|
|
|
|
DenseVector([2.0, 2.0, 9.0])
|
|
|
|
>>> b = Vectors.dense([9.0, 3.0, 4.0])
|
|
|
|
>>> rdd = sc.parallelize([a, b])
|
|
|
|
>>> eprod.transform(rdd).collect()
|
|
|
|
[DenseVector([2.0, 2.0, 9.0]), DenseVector([9.0, 6.0, 12.0])]
|
2015-09-15 00:58:52 -04:00
|
|
|
|
|
|
|
.. versionadded:: 1.5.0
|
2015-06-18 01:08:38 -04:00
|
|
|
"""
|
|
|
|
def __init__(self, scalingVector):
|
|
|
|
self.scalingVector = _convert_to_vector(scalingVector)
|
|
|
|
|
2015-09-15 00:58:52 -04:00
|
|
|
@since('1.5.0')
|
2015-06-18 01:08:38 -04:00
|
|
|
def transform(self, vector):
|
|
|
|
"""
|
|
|
|
Computes the Hadamard product of the vector.
|
|
|
|
"""
|
|
|
|
if isinstance(vector, RDD):
|
|
|
|
vector = vector.map(_convert_to_vector)
|
|
|
|
|
|
|
|
else:
|
|
|
|
vector = _convert_to_vector(vector)
|
|
|
|
return callMLlibFunc("elementwiseProductVector", self.scalingVector, vector)
|
|
|
|
|
|
|
|
|
2014-10-07 19:43:34 -04:00
|
|
|
def _test():
|
|
|
|
import doctest
|
2016-05-23 21:14:48 -04:00
|
|
|
from pyspark.sql import SparkSession
|
2014-10-07 19:43:34 -04:00
|
|
|
globs = globals().copy()
|
2016-05-23 21:14:48 -04:00
|
|
|
spark = SparkSession.builder\
|
|
|
|
.master("local[4]")\
|
|
|
|
.appName("mllib.feature tests")\
|
|
|
|
.getOrCreate()
|
|
|
|
globs['sc'] = spark.sparkContext
|
2014-10-07 19:43:34 -04:00
|
|
|
(failure_count, test_count) = doctest.testmod(globs=globs, optionflags=doctest.ELLIPSIS)
|
2016-05-23 21:14:48 -04:00
|
|
|
spark.stop()
|
2014-10-07 19:43:34 -04:00
|
|
|
if failure_count:
|
2018-03-08 06:38:34 -05:00
|
|
|
sys.exit(-1)
|
2014-10-07 19:43:34 -04:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2014-10-28 06:50:22 -04:00
|
|
|
sys.path.pop(0)
|
2014-10-07 19:43:34 -04:00
|
|
|
_test()
|