Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit aefa925

Browse files
committed
ENH speed up RBFSampler by ~10%
Applied the same to SkewedChi2Sampler, without measuring. I was actually aiming for reduced memory usage, but unfortunately that didn't matter much.
1 parent 91c9fab commit aefa925

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

sklearn/kernel_approximation.py

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,10 @@ class RBFSampler(BaseEstimator, TransformerMixin):
2828
Parameters
2929
----------
3030
gamma: float
31-
parameter of RBF kernel: exp(-gamma * x**2)
31+
Parameter of RBF kernel: exp(-γ × x²)
3232
3333
n_components: int
34-
number of Monte Carlo samples per original feature.
34+
Number of Monte Carlo samples per original feature.
3535
Equals the dimensionality of the computed feature space.
3636
3737
random_state : {int, RandomState}, optional
@@ -44,7 +44,7 @@ class RBFSampler(BaseEstimator, TransformerMixin):
4444
Benjamin Recht.
4545
"""
4646

47-
def __init__(self, gamma=1., n_components=100., random_state=None):
47+
def __init__(self, gamma=1., n_components=100, random_state=None):
4848
self.gamma = gamma
4949
self.n_components = n_components
5050
self.random_state = random_state
@@ -94,8 +94,10 @@ def transform(self, X, y=None):
9494
"""
9595
X = atleast2d_or_csr(X)
9696
projection = safe_sparse_dot(X, self.random_weights_)
97-
return (np.sqrt(2.) / np.sqrt(self.n_components)
98-
* np.cos(projection + self.random_offset_))
97+
projection += self.random_offset_
98+
np.cos(projection, projection)
99+
projection *= np.sqrt(2.) / np.sqrt(self.n_components)
100+
return projection
99101

100102

101103
class SkewedChi2Sampler(BaseEstimator, TransformerMixin):
@@ -176,15 +178,17 @@ def transform(self, X, y=None):
176178
-------
177179
X_new: array-like, shape (n_samples, n_components)
178180
"""
179-
X = array2d(X)
181+
X = array2d(X, copy=True)
180182
if (X < 0).any():
181183
raise ValueError("X may not contain entries smaller than zero.")
182184

183-
projection = safe_sparse_dot(np.log(X + self.skewedness),
184-
self.random_weights_)
185-
186-
return (np.sqrt(2.) / np.sqrt(self.n_components)
187-
* np.cos(projection + self.random_offset_))
185+
X += self.skewedness
186+
np.log(X, X)
187+
projection = safe_sparse_dot(X, self.random_weights_)
188+
projection += self.random_offset_
189+
np.cos(projection, projection)
190+
projection *= np.sqrt(2.) / np.sqrt(self.n_components)
191+
return projection
188192

189193

190194
class AdditiveChi2Sampler(BaseEstimator, TransformerMixin):

0 commit comments

Comments
 (0)