2011-12-19 23:31:50 +08:00
|
|
|
"""
|
|
|
|
|
The :mod:`sklearn.kernel_approximation` module implements several
|
|
|
|
|
approximate kernel feature maps base on Fourier transforms.
|
|
|
|
|
"""
|
2011-11-14 19:15:58 +08:00
|
|
|
|
2011-12-19 23:31:50 +08:00
|
|
|
# Author: Andreas Mueller <amueller@ais.uni-bonn.de>
|
|
|
|
|
#
|
2013-04-30 14:23:46 +08:00
|
|
|
# License: BSD 3 clause
|
2011-11-14 19:15:58 +08:00
|
|
|
|
2012-11-27 06:39:43 +08:00
|
|
|
import warnings
|
|
|
|
|
|
2011-12-19 23:31:50 +08:00
|
|
|
import numpy as np
|
2012-06-22 23:12:51 +08:00
|
|
|
import scipy.sparse as sp
|
2012-11-26 04:48:41 +08:00
|
|
|
from scipy.linalg import svd
|
2012-06-22 23:12:51 +08:00
|
|
|
|
2011-12-19 23:31:50 +08:00
|
|
|
from .base import BaseEstimator
|
|
|
|
|
from .base import TransformerMixin
|
2014-07-20 19:31:45 +08:00
|
|
|
from .utils import check_array, check_random_state, as_float_array
|
2011-12-20 03:11:43 +08:00
|
|
|
from .utils.extmath import safe_sparse_dot
|
2014-12-29 21:56:02 +08:00
|
|
|
from .utils.validation import check_is_fitted
|
2017-07-01 00:16:10 +08:00
|
|
|
from .metrics.pairwise import pairwise_kernels, KERNEL_PARAMS
|
2011-11-12 01:58:24 +08:00
|
|
|
|
|
|
|
|
|
2011-12-19 23:31:50 +08:00
|
|
|
class RBFSampler(BaseEstimator, TransformerMixin):
|
2011-11-14 19:15:58 +08:00
|
|
|
"""Approximates feature map of an RBF kernel by Monte Carlo approximation
|
|
|
|
|
of its Fourier transform.
|
2015-06-03 12:24:04 +08:00
|
|
|
|
2015-03-02 13:46:03 +08:00
|
|
|
It implements a variant of Random Kitchen Sinks.[1]
|
2011-11-14 19:15:58 +08:00
|
|
|
|
2015-06-03 12:24:04 +08:00
|
|
|
Read more in the :ref:`User Guide <rbf_kernel_approx>`.
|
|
|
|
|
|
2011-11-14 19:15:58 +08:00
|
|
|
Parameters
|
|
|
|
|
----------
|
2013-07-10 04:49:19 +08:00
|
|
|
gamma : float
|
2013-08-29 00:22:57 +08:00
|
|
|
Parameter of RBF kernel: exp(-gamma * x^2)
|
2011-12-21 16:49:06 +08:00
|
|
|
|
2013-07-10 04:49:19 +08:00
|
|
|
n_components : int
|
2013-02-19 00:21:58 +08:00
|
|
|
Number of Monte Carlo samples per original feature.
|
2011-11-14 19:15:58 +08:00
|
|
|
Equals the dimensionality of the computed feature space.
|
|
|
|
|
|
2017-04-06 08:43:21 +08:00
|
|
|
random_state : int, RandomState instance or None, optional (default=None)
|
2011-12-21 16:49:06 +08:00
|
|
|
If int, random_state is the seed used by the random number generator;
|
2017-04-06 08:43:21 +08:00
|
|
|
If RandomState instance, random_state is the random number generator;
|
|
|
|
|
If None, the random number generator is the RandomState instance used
|
|
|
|
|
by `np.random`.
|
2011-12-21 16:49:06 +08:00
|
|
|
|
2018-07-13 03:25:59 +08:00
|
|
|
Examples
|
|
|
|
|
--------
|
|
|
|
|
>>> from sklearn.kernel_approximation import RBFSampler
|
|
|
|
|
>>> from sklearn.linear_model import SGDClassifier
|
|
|
|
|
>>> X = [[0, 0], [1, 1], [1, 0], [0, 1]]
|
|
|
|
|
>>> y = [0, 0, 1, 1]
|
|
|
|
|
>>> rbf_feature = RBFSampler(gamma=1, random_state=1)
|
|
|
|
|
>>> X_features = rbf_feature.fit_transform(X)
|
2018-10-24 23:00:43 +08:00
|
|
|
>>> clf = SGDClassifier(max_iter=5, tol=1e-3)
|
2018-07-13 03:25:59 +08:00
|
|
|
>>> clf.fit(X_features, y)
|
|
|
|
|
... # doctest: +NORMALIZE_WHITESPACE
|
|
|
|
|
SGDClassifier(alpha=0.0001, average=False, class_weight=None,
|
|
|
|
|
early_stopping=False, epsilon=0.1, eta0=0.0, fit_intercept=True,
|
|
|
|
|
l1_ratio=0.15, learning_rate='optimal', loss='hinge', max_iter=5,
|
2018-08-03 18:34:25 +08:00
|
|
|
n_iter=None, n_iter_no_change=5, n_jobs=None, penalty='l2',
|
2018-10-24 23:00:43 +08:00
|
|
|
power_t=0.5, random_state=None, shuffle=True, tol=0.001,
|
2018-07-13 03:25:59 +08:00
|
|
|
validation_fraction=0.1, verbose=0, warm_start=False)
|
|
|
|
|
>>> clf.score(X_features, y)
|
|
|
|
|
1.0
|
|
|
|
|
|
2011-12-21 17:15:00 +08:00
|
|
|
Notes
|
|
|
|
|
-----
|
2011-12-24 17:38:58 +08:00
|
|
|
See "Random Features for Large-Scale Kernel Machines" by A. Rahimi and
|
2011-12-21 17:15:00 +08:00
|
|
|
Benjamin Recht.
|
2015-03-02 13:46:03 +08:00
|
|
|
|
|
|
|
|
[1] "Weighted Sums of Random Kitchen Sinks: Replacing
|
|
|
|
|
minimization with randomization in learning" by A. Rahimi and
|
|
|
|
|
Benjamin Recht.
|
2018-10-06 00:50:31 +08:00
|
|
|
(https://people.eecs.berkeley.edu/~brecht/papers/08.rah.rec.nips.pdf)
|
2011-12-21 16:49:06 +08:00
|
|
|
"""
|
2011-11-14 19:15:58 +08:00
|
|
|
|
2013-02-19 00:21:58 +08:00
|
|
|
def __init__(self, gamma=1., n_components=100, random_state=None):
|
2011-11-12 01:58:24 +08:00
|
|
|
self.gamma = gamma
|
2011-11-14 21:45:48 +08:00
|
|
|
self.n_components = n_components
|
2011-12-19 23:31:50 +08:00
|
|
|
self.random_state = random_state
|
2011-11-12 01:58:24 +08:00
|
|
|
|
|
|
|
|
def fit(self, X, y=None):
|
2011-11-14 19:15:58 +08:00
|
|
|
"""Fit the model with X.
|
2011-12-21 16:49:06 +08:00
|
|
|
|
|
|
|
|
Samples random projection according to n_features.
|
2011-11-14 19:15:58 +08:00
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
2013-07-10 04:49:19 +08:00
|
|
|
X : {array-like, sparse matrix}, shape (n_samples, n_features)
|
2011-11-14 19:15:58 +08:00
|
|
|
Training data, where n_samples in the number of samples
|
|
|
|
|
and n_features is the number of features.
|
2011-12-21 16:49:06 +08:00
|
|
|
|
2011-11-14 19:15:58 +08:00
|
|
|
Returns
|
|
|
|
|
-------
|
|
|
|
|
self : object
|
2011-12-21 16:49:06 +08:00
|
|
|
Returns the transformer.
|
2011-11-14 19:15:58 +08:00
|
|
|
"""
|
|
|
|
|
|
2014-07-20 21:31:28 +08:00
|
|
|
X = check_array(X, accept_sparse='csr')
|
2013-02-10 22:39:23 +08:00
|
|
|
random_state = check_random_state(self.random_state)
|
2011-11-12 01:58:24 +08:00
|
|
|
n_features = X.shape[1]
|
2011-12-19 23:31:50 +08:00
|
|
|
|
2014-09-11 14:59:09 +08:00
|
|
|
self.random_weights_ = (np.sqrt(2 * self.gamma) * random_state.normal(
|
2013-02-10 22:39:23 +08:00
|
|
|
size=(n_features, self.n_components)))
|
2012-11-27 05:58:59 +08:00
|
|
|
|
2013-02-10 22:39:23 +08:00
|
|
|
self.random_offset_ = random_state.uniform(0, 2 * np.pi,
|
|
|
|
|
size=self.n_components)
|
2011-11-12 01:58:24 +08:00
|
|
|
return self
|
|
|
|
|
|
2017-06-23 05:24:12 +08:00
|
|
|
def transform(self, X):
|
2011-11-14 19:15:58 +08:00
|
|
|
"""Apply the approximate feature map to X.
|
|
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
2013-07-10 04:49:19 +08:00
|
|
|
X : {array-like, sparse matrix}, shape (n_samples, n_features)
|
2011-11-14 19:15:58 +08:00
|
|
|
New data, where n_samples in the number of samples
|
|
|
|
|
and n_features is the number of features.
|
|
|
|
|
|
|
|
|
|
Returns
|
|
|
|
|
-------
|
2013-07-10 04:49:19 +08:00
|
|
|
X_new : array-like, shape (n_samples, n_components)
|
2011-11-14 19:15:58 +08:00
|
|
|
"""
|
2014-12-29 21:56:02 +08:00
|
|
|
check_is_fitted(self, 'random_weights_')
|
|
|
|
|
|
2014-07-20 21:31:28 +08:00
|
|
|
X = check_array(X, accept_sparse='csr')
|
2011-12-20 01:12:43 +08:00
|
|
|
projection = safe_sparse_dot(X, self.random_weights_)
|
2013-02-19 00:21:58 +08:00
|
|
|
projection += self.random_offset_
|
|
|
|
|
np.cos(projection, projection)
|
|
|
|
|
projection *= np.sqrt(2.) / np.sqrt(self.n_components)
|
|
|
|
|
return projection
|
2011-11-12 01:58:24 +08:00
|
|
|
|
|
|
|
|
|
2011-12-19 23:31:50 +08:00
|
|
|
class SkewedChi2Sampler(BaseEstimator, TransformerMixin):
|
2011-11-14 19:29:50 +08:00
|
|
|
"""Approximates feature map of the "skewed chi-squared" kernel by Monte
|
|
|
|
|
Carlo approximation of its Fourier transform.
|
2011-11-14 19:15:58 +08:00
|
|
|
|
2015-06-03 12:24:04 +08:00
|
|
|
Read more in the :ref:`User Guide <skewed_chi_kernel_approx>`.
|
|
|
|
|
|
2011-11-14 19:15:58 +08:00
|
|
|
Parameters
|
|
|
|
|
----------
|
2012-11-26 05:27:24 +08:00
|
|
|
skewedness : float
|
2011-11-14 19:15:58 +08:00
|
|
|
"skewedness" parameter of the kernel. Needs to be cross-validated.
|
2011-12-21 16:49:06 +08:00
|
|
|
|
2012-11-26 05:27:24 +08:00
|
|
|
n_components : int
|
2011-11-14 19:15:58 +08:00
|
|
|
number of Monte Carlo samples per original feature.
|
|
|
|
|
Equals the dimensionality of the computed feature space.
|
|
|
|
|
|
2017-04-06 08:43:21 +08:00
|
|
|
random_state : int, RandomState instance or None, optional (default=None)
|
2011-12-21 16:49:06 +08:00
|
|
|
If int, random_state is the seed used by the random number generator;
|
2017-04-06 08:43:21 +08:00
|
|
|
If RandomState instance, random_state is the random number generator;
|
|
|
|
|
If None, the random number generator is the RandomState instance used
|
|
|
|
|
by `np.random`.
|
2011-12-21 16:49:06 +08:00
|
|
|
|
2018-07-13 03:27:08 +08:00
|
|
|
Examples
|
|
|
|
|
--------
|
|
|
|
|
>>> from sklearn.kernel_approximation import SkewedChi2Sampler
|
|
|
|
|
>>> from sklearn.linear_model import SGDClassifier
|
|
|
|
|
>>> X = [[0, 0], [1, 1], [1, 0], [0, 1]]
|
|
|
|
|
>>> y = [0, 0, 1, 1]
|
|
|
|
|
>>> chi2_feature = SkewedChi2Sampler(skewedness=.01,
|
|
|
|
|
... n_components=10,
|
|
|
|
|
... random_state=0)
|
|
|
|
|
>>> X_features = chi2_feature.fit_transform(X, y)
|
2018-10-24 23:00:43 +08:00
|
|
|
>>> clf = SGDClassifier(max_iter=10, tol=1e-3)
|
2018-12-20 12:48:21 +08:00
|
|
|
>>> clf.fit(X_features, y) # doctest: +NORMALIZE_WHITESPACE
|
2018-07-13 03:27:08 +08:00
|
|
|
SGDClassifier(alpha=0.0001, average=False, class_weight=None,
|
|
|
|
|
early_stopping=False, epsilon=0.1, eta0=0.0, fit_intercept=True,
|
|
|
|
|
l1_ratio=0.15, learning_rate='optimal', loss='hinge', max_iter=10,
|
2018-08-03 18:34:25 +08:00
|
|
|
n_iter=None, n_iter_no_change=5, n_jobs=None, penalty='l2',
|
2018-10-24 23:00:43 +08:00
|
|
|
power_t=0.5, random_state=None, shuffle=True, tol=0.001,
|
2018-07-13 03:27:08 +08:00
|
|
|
validation_fraction=0.1, verbose=0, warm_start=False)
|
|
|
|
|
>>> clf.score(X_features, y)
|
|
|
|
|
1.0
|
|
|
|
|
|
2012-11-26 02:19:04 +08:00
|
|
|
References
|
|
|
|
|
----------
|
2011-12-21 17:15:00 +08:00
|
|
|
See "Random Fourier Approximations for Skewed Multiplicative Histogram
|
|
|
|
|
Kernels" by Fuxin Li, Catalin Ionescu and Cristian Sminchisescu.
|
2012-11-26 02:19:04 +08:00
|
|
|
|
|
|
|
|
See also
|
|
|
|
|
--------
|
|
|
|
|
AdditiveChi2Sampler : A different approach for approximating an additive
|
|
|
|
|
variant of the chi squared kernel.
|
|
|
|
|
|
2014-07-29 12:49:36 +08:00
|
|
|
sklearn.metrics.pairwise.chi2_kernel : The exact chi squared kernel.
|
2011-11-12 01:58:24 +08:00
|
|
|
"""
|
|
|
|
|
|
2011-12-19 23:31:50 +08:00
|
|
|
def __init__(self, skewedness=1., n_components=100, random_state=None):
|
|
|
|
|
self.skewedness = skewedness
|
2011-11-14 21:45:48 +08:00
|
|
|
self.n_components = n_components
|
2011-12-19 23:31:50 +08:00
|
|
|
self.random_state = random_state
|
2011-11-12 01:58:24 +08:00
|
|
|
|
2011-11-13 18:58:03 +08:00
|
|
|
def fit(self, X, y=None):
|
2011-11-14 19:15:58 +08:00
|
|
|
"""Fit the model with X.
|
2011-12-21 16:49:06 +08:00
|
|
|
|
|
|
|
|
Samples random projection according to n_features.
|
2011-11-14 19:15:58 +08:00
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
2013-07-10 04:49:19 +08:00
|
|
|
X : array-like, shape (n_samples, n_features)
|
2011-11-14 19:15:58 +08:00
|
|
|
Training data, where n_samples in the number of samples
|
|
|
|
|
and n_features is the number of features.
|
2011-12-21 16:49:06 +08:00
|
|
|
|
2011-11-14 19:15:58 +08:00
|
|
|
Returns
|
|
|
|
|
-------
|
|
|
|
|
self : object
|
2011-12-21 16:49:06 +08:00
|
|
|
Returns the transformer.
|
2011-11-14 19:15:58 +08:00
|
|
|
"""
|
2011-12-03 01:53:24 +08:00
|
|
|
|
2014-07-20 19:31:45 +08:00
|
|
|
X = check_array(X)
|
2013-02-10 22:39:23 +08:00
|
|
|
random_state = check_random_state(self.random_state)
|
2011-11-12 01:58:24 +08:00
|
|
|
n_features = X.shape[1]
|
2013-02-10 22:39:23 +08:00
|
|
|
uniform = random_state.uniform(size=(n_features, self.n_components))
|
2011-11-12 01:58:24 +08:00
|
|
|
# transform by inverse CDF of sech
|
2011-12-19 23:31:50 +08:00
|
|
|
self.random_weights_ = (1. / np.pi
|
2012-11-27 05:58:59 +08:00
|
|
|
* np.log(np.tan(np.pi / 2. * uniform)))
|
2013-02-10 22:39:23 +08:00
|
|
|
self.random_offset_ = random_state.uniform(0, 2 * np.pi,
|
|
|
|
|
size=self.n_components)
|
2011-11-12 01:58:24 +08:00
|
|
|
return self
|
|
|
|
|
|
2017-06-23 05:24:12 +08:00
|
|
|
def transform(self, X):
|
2011-11-14 19:15:58 +08:00
|
|
|
"""Apply the approximate feature map to X.
|
|
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
2013-07-10 04:49:19 +08:00
|
|
|
X : array-like, shape (n_samples, n_features)
|
2011-11-14 19:15:58 +08:00
|
|
|
New data, where n_samples in the number of samples
|
2017-05-19 02:17:10 +08:00
|
|
|
and n_features is the number of features. All values of X must be
|
|
|
|
|
strictly greater than "-skewedness".
|
2011-11-14 19:15:58 +08:00
|
|
|
|
|
|
|
|
Returns
|
|
|
|
|
-------
|
2013-07-10 04:49:19 +08:00
|
|
|
X_new : array-like, shape (n_samples, n_components)
|
2011-11-14 19:15:58 +08:00
|
|
|
"""
|
2014-12-29 21:56:02 +08:00
|
|
|
check_is_fitted(self, 'random_weights_')
|
|
|
|
|
|
2013-04-14 16:27:06 +08:00
|
|
|
X = as_float_array(X, copy=True)
|
2014-07-20 19:31:45 +08:00
|
|
|
X = check_array(X, copy=False)
|
2017-05-19 02:17:10 +08:00
|
|
|
if (X <= -self.skewedness).any():
|
|
|
|
|
raise ValueError("X may not contain entries smaller than"
|
|
|
|
|
" -skewedness.")
|
2011-12-03 01:53:24 +08:00
|
|
|
|
2013-02-19 00:21:58 +08:00
|
|
|
X += self.skewedness
|
|
|
|
|
np.log(X, X)
|
|
|
|
|
projection = safe_sparse_dot(X, self.random_weights_)
|
|
|
|
|
projection += self.random_offset_
|
|
|
|
|
np.cos(projection, projection)
|
|
|
|
|
projection *= np.sqrt(2.) / np.sqrt(self.n_components)
|
|
|
|
|
return projection
|
2011-11-21 02:53:01 +08:00
|
|
|
|
2011-11-21 02:55:30 +08:00
|
|
|
|
2011-12-19 23:31:50 +08:00
|
|
|
class AdditiveChi2Sampler(BaseEstimator, TransformerMixin):
|
2013-08-29 00:22:57 +08:00
|
|
|
"""Approximate feature map for additive chi2 kernel.
|
2011-12-21 16:49:06 +08:00
|
|
|
|
|
|
|
|
Uses sampling the fourier transform of the kernel characteristic
|
2011-12-21 16:57:24 +08:00
|
|
|
at regular intervals.
|
2011-11-21 02:53:01 +08:00
|
|
|
|
2011-12-21 16:49:06 +08:00
|
|
|
Since the kernel that is to be approximated is additive, the components of
|
|
|
|
|
the input vectors can be treated separately. Each entry in the original
|
2013-08-29 00:22:57 +08:00
|
|
|
space is transformed into 2*sample_steps+1 features, where sample_steps is
|
2012-06-23 18:34:45 +08:00
|
|
|
a parameter of the method. Typical values of sample_steps include 1, 2 and
|
|
|
|
|
3.
|
2011-11-21 02:53:01 +08:00
|
|
|
|
2011-12-21 16:57:24 +08:00
|
|
|
Optimal choices for the sampling interval for certain data ranges can be
|
2011-12-21 16:49:06 +08:00
|
|
|
computed (see the reference). The default values should be reasonable.
|
2011-11-21 02:53:01 +08:00
|
|
|
|
2015-06-03 12:24:04 +08:00
|
|
|
Read more in the :ref:`User Guide <additive_chi_kernel_approx>`.
|
|
|
|
|
|
2011-11-21 02:53:01 +08:00
|
|
|
Parameters
|
|
|
|
|
----------
|
2012-11-26 05:27:24 +08:00
|
|
|
sample_steps : int, optional
|
2011-12-21 16:49:06 +08:00
|
|
|
Gives the number of (complex) sampling points.
|
2012-11-26 05:27:24 +08:00
|
|
|
sample_interval : float, optional
|
2011-12-21 16:49:06 +08:00
|
|
|
Sampling interval. Must be specified when sample_steps not in {1,2,3}.
|
|
|
|
|
|
2018-07-31 21:43:35 +08:00
|
|
|
Examples
|
|
|
|
|
--------
|
|
|
|
|
>>> from sklearn.datasets import load_digits
|
|
|
|
|
>>> from sklearn.linear_model import SGDClassifier
|
|
|
|
|
>>> from sklearn.kernel_approximation import AdditiveChi2Sampler
|
|
|
|
|
>>> X, y = load_digits(return_X_y=True)
|
|
|
|
|
>>> chi2sampler = AdditiveChi2Sampler(sample_steps=2)
|
|
|
|
|
>>> X_transformed = chi2sampler.fit_transform(X, y)
|
2018-10-24 23:00:43 +08:00
|
|
|
>>> clf = SGDClassifier(max_iter=5, random_state=0, tol=1e-3)
|
2018-12-20 12:48:21 +08:00
|
|
|
>>> clf.fit(X_transformed, y) # doctest: +NORMALIZE_WHITESPACE
|
2018-07-31 21:43:35 +08:00
|
|
|
SGDClassifier(alpha=0.0001, average=False, class_weight=None,
|
|
|
|
|
early_stopping=False, epsilon=0.1, eta0=0.0, fit_intercept=True,
|
|
|
|
|
l1_ratio=0.15, learning_rate='optimal', loss='hinge', max_iter=5,
|
2018-08-03 18:34:25 +08:00
|
|
|
n_iter=None, n_iter_no_change=5, n_jobs=None, penalty='l2',
|
2018-10-24 23:00:43 +08:00
|
|
|
power_t=0.5, random_state=0, shuffle=True, tol=0.001,
|
2018-07-31 21:43:35 +08:00
|
|
|
validation_fraction=0.1, verbose=0, warm_start=False)
|
|
|
|
|
>>> clf.score(X_transformed, y) # doctest: +ELLIPSIS
|
|
|
|
|
0.9543...
|
|
|
|
|
|
2011-12-21 17:15:00 +08:00
|
|
|
Notes
|
|
|
|
|
-----
|
2012-11-26 02:19:04 +08:00
|
|
|
This estimator approximates a slightly different version of the additive
|
|
|
|
|
chi squared kernel then ``metric.additive_chi2`` computes.
|
|
|
|
|
|
|
|
|
|
See also
|
|
|
|
|
--------
|
|
|
|
|
SkewedChi2Sampler : A Fourier-approximation to a non-additive variant of
|
|
|
|
|
the chi squared kernel.
|
|
|
|
|
|
2014-07-29 12:49:36 +08:00
|
|
|
sklearn.metrics.pairwise.chi2_kernel : The exact chi squared kernel.
|
2012-11-26 02:19:04 +08:00
|
|
|
|
2014-07-29 12:49:36 +08:00
|
|
|
sklearn.metrics.pairwise.additive_chi2_kernel : The exact additive chi
|
|
|
|
|
squared kernel.
|
2012-11-26 02:19:04 +08:00
|
|
|
|
|
|
|
|
References
|
|
|
|
|
----------
|
2011-12-21 17:15:00 +08:00
|
|
|
See `"Efficient additive kernels via explicit feature maps"
|
2015-06-15 02:44:02 +08:00
|
|
|
<http://www.robots.ox.ac.uk/~vedaldi/assets/pubs/vedaldi11efficient.pdf>`_
|
|
|
|
|
A. Vedaldi and A. Zisserman, Pattern Analysis and Machine Intelligence,
|
|
|
|
|
2011
|
2011-12-19 23:31:50 +08:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
def __init__(self, sample_steps=2, sample_interval=None):
|
|
|
|
|
self.sample_steps = sample_steps
|
|
|
|
|
self.sample_interval = sample_interval
|
|
|
|
|
|
|
|
|
|
def fit(self, X, y=None):
|
2018-07-20 06:24:39 +08:00
|
|
|
"""Set the parameters
|
|
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
|
|
|
|
X : array-like, shape (n_samples, n_features)
|
|
|
|
|
Training data, where n_samples in the number of samples
|
|
|
|
|
and n_features is the number of features.
|
|
|
|
|
|
|
|
|
|
Returns
|
|
|
|
|
-------
|
|
|
|
|
self : object
|
|
|
|
|
Returns the transformer.
|
|
|
|
|
"""
|
2018-10-22 09:48:40 +08:00
|
|
|
check_array(X, accept_sparse='csr')
|
2012-11-27 05:58:59 +08:00
|
|
|
if self.sample_interval is None:
|
2011-11-21 02:53:01 +08:00
|
|
|
# See reference, figure 2 c)
|
2011-12-19 23:31:50 +08:00
|
|
|
if self.sample_steps == 1:
|
2013-02-10 22:39:23 +08:00
|
|
|
self.sample_interval_ = 0.8
|
2011-12-19 23:31:50 +08:00
|
|
|
elif self.sample_steps == 2:
|
2013-02-10 22:39:23 +08:00
|
|
|
self.sample_interval_ = 0.5
|
2011-12-19 23:31:50 +08:00
|
|
|
elif self.sample_steps == 3:
|
2013-02-10 22:39:23 +08:00
|
|
|
self.sample_interval_ = 0.4
|
2011-11-21 02:53:01 +08:00
|
|
|
else:
|
2011-12-24 17:38:58 +08:00
|
|
|
raise ValueError("If sample_steps is not in [1, 2, 3],"
|
2012-11-27 05:58:59 +08:00
|
|
|
" you need to provide sample_interval")
|
2013-02-10 22:39:23 +08:00
|
|
|
else:
|
2014-04-15 21:51:53 +08:00
|
|
|
self.sample_interval_ = self.sample_interval
|
2011-12-03 01:52:36 +08:00
|
|
|
return self
|
2011-11-21 02:53:01 +08:00
|
|
|
|
2017-06-23 05:24:12 +08:00
|
|
|
def transform(self, X):
|
2011-11-21 02:53:01 +08:00
|
|
|
"""Apply approximate feature map to X.
|
|
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
2013-07-10 04:49:19 +08:00
|
|
|
X : {array-like, sparse matrix}, shape = (n_samples, n_features)
|
2011-11-21 02:53:01 +08:00
|
|
|
|
|
|
|
|
Returns
|
|
|
|
|
-------
|
2013-07-10 04:49:19 +08:00
|
|
|
X_new : {array, sparse matrix}, \
|
2013-08-29 00:22:57 +08:00
|
|
|
shape = (n_samples, n_features * (2*sample_steps + 1))
|
2012-06-24 07:53:29 +08:00
|
|
|
Whether the return value is an array of sparse matrix depends on
|
|
|
|
|
the type of the input X.
|
2011-11-21 02:53:01 +08:00
|
|
|
"""
|
2014-12-29 21:56:02 +08:00
|
|
|
msg = ("%(name)s is not fitted. Call fit to set the parameters before"
|
|
|
|
|
" calling transform")
|
|
|
|
|
check_is_fitted(self, "sample_interval_", msg=msg)
|
2011-12-03 01:53:24 +08:00
|
|
|
|
2014-07-20 21:31:28 +08:00
|
|
|
X = check_array(X, accept_sparse='csr')
|
2012-06-22 23:12:51 +08:00
|
|
|
sparse = sp.issparse(X)
|
|
|
|
|
|
2012-06-21 19:33:10 +08:00
|
|
|
# check if X has negative values. Doesn't play well with np.log.
|
2012-06-22 23:12:51 +08:00
|
|
|
if ((X.data if sparse else X) < 0).any():
|
2012-06-22 23:16:42 +08:00
|
|
|
raise ValueError("Entries of X must be non-negative.")
|
2011-11-21 02:53:01 +08:00
|
|
|
# zeroth component
|
|
|
|
|
# 1/cosh = sech
|
2012-06-21 19:33:10 +08:00
|
|
|
# cosh(0) = 1.0
|
|
|
|
|
|
2012-06-22 23:12:51 +08:00
|
|
|
transf = self._transform_sparse if sparse else self._transform_dense
|
|
|
|
|
return transf(X)
|
|
|
|
|
|
|
|
|
|
def _transform_dense(self, X):
|
2012-06-21 19:33:10 +08:00
|
|
|
non_zero = (X != 0.0)
|
|
|
|
|
X_nz = X[non_zero]
|
|
|
|
|
|
|
|
|
|
X_step = np.zeros_like(X)
|
2013-02-10 22:39:23 +08:00
|
|
|
X_step[non_zero] = np.sqrt(X_nz * self.sample_interval_)
|
2012-06-22 23:17:52 +08:00
|
|
|
|
2012-06-23 18:34:45 +08:00
|
|
|
X_new = [X_step]
|
2012-06-21 19:33:10 +08:00
|
|
|
|
2013-02-10 22:39:23 +08:00
|
|
|
log_step_nz = self.sample_interval_ * np.log(X_nz)
|
|
|
|
|
step_nz = 2 * X_nz * self.sample_interval_
|
2011-11-21 02:53:01 +08:00
|
|
|
|
2012-03-16 04:35:42 +08:00
|
|
|
for j in range(1, self.sample_steps):
|
2012-06-21 21:47:45 +08:00
|
|
|
factor_nz = np.sqrt(step_nz /
|
2013-02-10 22:39:23 +08:00
|
|
|
np.cosh(np.pi * j * self.sample_interval_))
|
2012-06-22 23:17:52 +08:00
|
|
|
|
2012-06-22 23:16:42 +08:00
|
|
|
X_step = np.zeros_like(X)
|
2012-06-21 19:33:10 +08:00
|
|
|
X_step[non_zero] = factor_nz * np.cos(j * log_step_nz)
|
2012-06-22 23:16:42 +08:00
|
|
|
X_new.append(X_step)
|
|
|
|
|
|
|
|
|
|
X_step = np.zeros_like(X)
|
2012-06-21 19:33:10 +08:00
|
|
|
X_step[non_zero] = factor_nz * np.sin(j * log_step_nz)
|
2012-06-22 23:16:42 +08:00
|
|
|
X_new.append(X_step)
|
|
|
|
|
|
2011-11-21 02:53:01 +08:00
|
|
|
return np.hstack(X_new)
|
2012-06-22 23:12:51 +08:00
|
|
|
|
|
|
|
|
def _transform_sparse(self, X):
|
|
|
|
|
indices = X.indices.copy()
|
|
|
|
|
indptr = X.indptr.copy()
|
|
|
|
|
|
2013-02-10 22:39:23 +08:00
|
|
|
data_step = np.sqrt(X.data * self.sample_interval_)
|
2012-06-22 23:12:51 +08:00
|
|
|
X_step = sp.csr_matrix((data_step, indices, indptr),
|
|
|
|
|
shape=X.shape, dtype=X.dtype, copy=False)
|
|
|
|
|
X_new = [X_step]
|
|
|
|
|
|
2013-02-10 22:39:23 +08:00
|
|
|
log_step_nz = self.sample_interval_ * np.log(X.data)
|
|
|
|
|
step_nz = 2 * X.data * self.sample_interval_
|
2012-06-22 23:12:51 +08:00
|
|
|
|
2013-02-14 09:05:35 +08:00
|
|
|
for j in range(1, self.sample_steps):
|
2012-06-22 23:12:51 +08:00
|
|
|
factor_nz = np.sqrt(step_nz /
|
2013-02-10 22:39:23 +08:00
|
|
|
np.cosh(np.pi * j * self.sample_interval_))
|
2012-06-22 23:12:51 +08:00
|
|
|
|
|
|
|
|
data_step = factor_nz * np.cos(j * log_step_nz)
|
|
|
|
|
X_step = sp.csr_matrix((data_step, indices, indptr),
|
|
|
|
|
shape=X.shape, dtype=X.dtype, copy=False)
|
|
|
|
|
X_new.append(X_step)
|
|
|
|
|
|
|
|
|
|
data_step = factor_nz * np.sin(j * log_step_nz)
|
|
|
|
|
X_step = sp.csr_matrix((data_step, indices, indptr),
|
|
|
|
|
shape=X.shape, dtype=X.dtype, copy=False)
|
|
|
|
|
X_new.append(X_step)
|
|
|
|
|
|
|
|
|
|
return sp.hstack(X_new)
|
2012-11-26 04:48:41 +08:00
|
|
|
|
|
|
|
|
|
2012-11-26 05:00:11 +08:00
|
|
|
class Nystroem(BaseEstimator, TransformerMixin):
|
2012-11-26 05:27:24 +08:00
|
|
|
"""Approximate a kernel map using a subset of the training data.
|
|
|
|
|
|
2012-11-27 05:58:59 +08:00
|
|
|
Constructs an approximate feature map for an arbitrary kernel
|
2012-11-26 05:27:24 +08:00
|
|
|
using a subset of the data as basis.
|
|
|
|
|
|
2015-06-03 12:24:04 +08:00
|
|
|
Read more in the :ref:`User Guide <nystroem_kernel_approx>`.
|
|
|
|
|
|
2012-11-26 05:27:24 +08:00
|
|
|
Parameters
|
|
|
|
|
----------
|
|
|
|
|
kernel : string or callable, default="rbf"
|
2013-03-18 19:50:19 +08:00
|
|
|
Kernel map to be approximated. A callable should accept two arguments
|
|
|
|
|
and the keyword arguments passed to this object as kernel_params, and
|
|
|
|
|
should return a floating point number.
|
2012-11-26 05:27:24 +08:00
|
|
|
|
2013-03-18 19:50:19 +08:00
|
|
|
gamma : float, default=None
|
2017-04-22 21:45:08 +08:00
|
|
|
Gamma parameter for the RBF, laplacian, polynomial, exponential chi2
|
|
|
|
|
and sigmoid kernels. Interpretation of the default value is left to
|
2013-03-18 19:50:19 +08:00
|
|
|
the kernel; see the documentation for sklearn.metrics.pairwise.
|
|
|
|
|
Ignored by other kernels.
|
|
|
|
|
|
2017-07-01 00:16:10 +08:00
|
|
|
coef0 : float, default=None
|
2013-03-18 19:50:19 +08:00
|
|
|
Zero coefficient for polynomial and sigmoid kernels.
|
|
|
|
|
Ignored by other kernels.
|
|
|
|
|
|
2018-07-20 06:24:39 +08:00
|
|
|
degree : float, default=None
|
|
|
|
|
Degree of the polynomial kernel. Ignored by other kernels.
|
|
|
|
|
|
2013-03-18 19:50:19 +08:00
|
|
|
kernel_params : mapping of string to any, optional
|
|
|
|
|
Additional parameters (keyword arguments) for kernel function passed
|
|
|
|
|
as callable object.
|
2012-11-26 05:27:24 +08:00
|
|
|
|
2018-07-20 06:24:39 +08:00
|
|
|
n_components : int
|
|
|
|
|
Number of features to construct.
|
|
|
|
|
How many data points will be used to construct the mapping.
|
|
|
|
|
|
2017-04-06 08:43:21 +08:00
|
|
|
random_state : int, RandomState instance or None, optional (default=None)
|
2012-11-26 05:27:24 +08:00
|
|
|
If int, random_state is the seed used by the random number generator;
|
2017-04-06 08:43:21 +08:00
|
|
|
If RandomState instance, random_state is the random number generator;
|
|
|
|
|
If None, the random number generator is the RandomState instance used
|
|
|
|
|
by `np.random`.
|
2012-11-26 05:27:24 +08:00
|
|
|
|
|
|
|
|
Attributes
|
|
|
|
|
----------
|
2014-07-28 17:04:59 +08:00
|
|
|
components_ : array, shape (n_components, n_features)
|
2012-11-26 05:27:24 +08:00
|
|
|
Subset of training points used to construct the feature map.
|
|
|
|
|
|
2014-07-28 17:04:59 +08:00
|
|
|
component_indices_ : array, shape (n_components)
|
2012-11-27 05:58:59 +08:00
|
|
|
Indices of ``components_`` in the training set.
|
2012-11-26 05:27:24 +08:00
|
|
|
|
2014-07-28 17:04:59 +08:00
|
|
|
normalization_ : array, shape (n_components, n_components)
|
2012-11-26 05:27:24 +08:00
|
|
|
Normalization matrix needed for embedding.
|
2012-11-27 05:58:59 +08:00
|
|
|
Square root of the kernel matrix on ``components_``.
|
2012-11-26 05:27:24 +08:00
|
|
|
|
2018-07-16 09:17:30 +08:00
|
|
|
Examples
|
|
|
|
|
--------
|
|
|
|
|
>>> from sklearn import datasets, svm
|
|
|
|
|
>>> from sklearn.kernel_approximation import Nystroem
|
|
|
|
|
>>> digits = datasets.load_digits(n_class=9)
|
|
|
|
|
>>> data = digits.data / 16.
|
|
|
|
|
>>> clf = svm.LinearSVC()
|
|
|
|
|
>>> feature_map_nystroem = Nystroem(gamma=.2,
|
|
|
|
|
... random_state=1,
|
|
|
|
|
... n_components=300)
|
|
|
|
|
>>> data_transformed = feature_map_nystroem.fit_transform(data)
|
|
|
|
|
>>> clf.fit(data_transformed, digits.target)
|
|
|
|
|
... # doctest: +NORMALIZE_WHITESPACE
|
|
|
|
|
LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True,
|
|
|
|
|
intercept_scaling=1, loss='squared_hinge', max_iter=1000,
|
|
|
|
|
multi_class='ovr', penalty='l2', random_state=None, tol=0.0001,
|
|
|
|
|
verbose=0)
|
|
|
|
|
>>> clf.score(data_transformed, digits.target) # doctest: +ELLIPSIS
|
|
|
|
|
0.9987...
|
2012-11-27 06:39:43 +08:00
|
|
|
|
2012-11-26 05:27:24 +08:00
|
|
|
References
|
|
|
|
|
----------
|
|
|
|
|
* Williams, C.K.I. and Seeger, M.
|
2013-08-29 00:22:57 +08:00
|
|
|
"Using the Nystroem method to speed up kernel machines",
|
2012-11-26 05:27:24 +08:00
|
|
|
Advances in neural information processing systems 2001
|
|
|
|
|
|
|
|
|
|
* T. Yang, Y. Li, M. Mahdavi, R. Jin and Z. Zhou
|
|
|
|
|
"Nystroem Method vs Random Fourier Features: A Theoretical and Empirical
|
|
|
|
|
Comparison",
|
|
|
|
|
Advances in Neural Information Processing Systems 2012
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
See also
|
|
|
|
|
--------
|
|
|
|
|
RBFSampler : An approximation to the RBF kernel using random Fourier
|
|
|
|
|
features.
|
|
|
|
|
|
2014-07-29 12:49:36 +08:00
|
|
|
sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels.
|
2012-11-26 05:27:24 +08:00
|
|
|
"""
|
2017-07-01 00:16:10 +08:00
|
|
|
def __init__(self, kernel="rbf", gamma=None, coef0=None, degree=None,
|
2013-03-18 19:50:19 +08:00
|
|
|
kernel_params=None, n_components=100, random_state=None):
|
2012-11-26 04:48:41 +08:00
|
|
|
self.kernel = kernel
|
|
|
|
|
self.gamma = gamma
|
2012-11-27 05:58:59 +08:00
|
|
|
self.coef0 = coef0
|
|
|
|
|
self.degree = degree
|
2013-03-18 19:50:19 +08:00
|
|
|
self.kernel_params = kernel_params
|
2012-11-26 04:48:41 +08:00
|
|
|
self.n_components = n_components
|
|
|
|
|
self.random_state = random_state
|
|
|
|
|
|
|
|
|
|
def fit(self, X, y=None):
|
2012-11-26 05:27:24 +08:00
|
|
|
"""Fit estimator to data.
|
|
|
|
|
|
|
|
|
|
Samples a subset of training points, computes kernel
|
|
|
|
|
on these and computes normalization matrix.
|
|
|
|
|
|
2013-01-17 05:51:24 +08:00
|
|
|
Parameters
|
|
|
|
|
----------
|
2012-11-26 05:27:24 +08:00
|
|
|
X : array-like, shape=(n_samples, n_feature)
|
|
|
|
|
Training data.
|
|
|
|
|
"""
|
2015-02-07 01:30:40 +08:00
|
|
|
X = check_array(X, accept_sparse='csr')
|
2012-11-26 04:48:41 +08:00
|
|
|
rnd = check_random_state(self.random_state)
|
|
|
|
|
n_samples = X.shape[0]
|
|
|
|
|
|
|
|
|
|
# get basis vectors
|
2012-11-27 06:39:43 +08:00
|
|
|
if self.n_components > n_samples:
|
|
|
|
|
# XXX should we just bail?
|
|
|
|
|
n_components = n_samples
|
|
|
|
|
warnings.warn("n_components > n_samples. This is not possible.\n"
|
|
|
|
|
"n_components was set to n_samples, which results"
|
|
|
|
|
" in inefficient evaluation of the full kernel.")
|
|
|
|
|
|
|
|
|
|
else:
|
|
|
|
|
n_components = self.n_components
|
|
|
|
|
n_components = min(n_samples, n_components)
|
2012-11-26 04:48:41 +08:00
|
|
|
inds = rnd.permutation(n_samples)
|
2012-11-27 06:39:43 +08:00
|
|
|
basis_inds = inds[:n_components]
|
2012-11-26 05:27:24 +08:00
|
|
|
basis = X[basis_inds]
|
2012-11-26 04:48:41 +08:00
|
|
|
|
2013-11-16 21:53:01 +08:00
|
|
|
basis_kernel = pairwise_kernels(basis, metric=self.kernel,
|
|
|
|
|
filter_params=True,
|
|
|
|
|
**self._get_kernel_params())
|
2012-11-26 04:48:41 +08:00
|
|
|
|
2012-11-26 05:27:24 +08:00
|
|
|
# sqrt of kernel matrix on basis vectors
|
2012-11-26 04:48:41 +08:00
|
|
|
U, S, V = svd(basis_kernel)
|
2015-01-30 01:11:52 +08:00
|
|
|
S = np.maximum(S, 1e-12)
|
2017-06-06 22:13:42 +08:00
|
|
|
self.normalization_ = np.dot(U / np.sqrt(S), V)
|
2012-11-27 05:58:59 +08:00
|
|
|
self.components_ = basis
|
|
|
|
|
self.component_indices_ = inds
|
2012-11-26 04:48:41 +08:00
|
|
|
return self
|
|
|
|
|
|
|
|
|
|
def transform(self, X):
|
2012-11-26 05:27:24 +08:00
|
|
|
"""Apply feature map to X.
|
|
|
|
|
|
|
|
|
|
Computes an approximate feature map using the kernel
|
|
|
|
|
between some training points and X.
|
|
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
|
|
|
|
X : array-like, shape=(n_samples, n_features)
|
|
|
|
|
Data to transform.
|
|
|
|
|
|
|
|
|
|
Returns
|
|
|
|
|
-------
|
|
|
|
|
X_transformed : array, shape=(n_samples, n_components)
|
|
|
|
|
Transformed data.
|
|
|
|
|
"""
|
2014-12-29 21:56:02 +08:00
|
|
|
check_is_fitted(self, 'components_')
|
2015-02-07 01:30:40 +08:00
|
|
|
X = check_array(X, accept_sparse='csr')
|
2012-11-26 05:27:24 +08:00
|
|
|
|
2014-12-29 21:56:02 +08:00
|
|
|
kernel_params = self._get_kernel_params()
|
2013-11-16 21:53:01 +08:00
|
|
|
embedded = pairwise_kernels(X, self.components_,
|
|
|
|
|
metric=self.kernel,
|
|
|
|
|
filter_params=True,
|
2014-12-29 21:56:02 +08:00
|
|
|
**kernel_params)
|
2012-11-26 05:27:24 +08:00
|
|
|
return np.dot(embedded, self.normalization_.T)
|
2013-03-18 19:50:19 +08:00
|
|
|
|
|
|
|
|
def _get_kernel_params(self):
|
|
|
|
|
params = self.kernel_params
|
|
|
|
|
if params is None:
|
|
|
|
|
params = {}
|
|
|
|
|
if not callable(self.kernel):
|
2017-07-01 00:16:10 +08:00
|
|
|
for param in (KERNEL_PARAMS[self.kernel]):
|
|
|
|
|
if getattr(self, param) is not None:
|
|
|
|
|
params[param] = getattr(self, param)
|
|
|
|
|
else:
|
|
|
|
|
if (self.gamma is not None or
|
|
|
|
|
self.coef0 is not None or
|
|
|
|
|
self.degree is not None):
|
2018-10-12 02:56:37 +08:00
|
|
|
raise ValueError("Don't pass gamma, coef0 or degree to "
|
|
|
|
|
"Nystroem if using a callable kernel.")
|
2013-03-18 19:50:19 +08:00
|
|
|
|
|
|
|
|
return params
|