random_projection.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. """Random Projection transformers.
  2. Random Projections are a simple and computationally efficient way to
  3. reduce the dimensionality of the data by trading a controlled amount
  4. of accuracy (as additional variance) for faster processing times and
  5. smaller model sizes.
  6. The dimensions and distribution of Random Projections matrices are
  7. controlled so as to preserve the pairwise distances between any two
  8. samples of the dataset.
  9. The main theoretical result behind the efficiency of random projection is the
  10. `Johnson-Lindenstrauss lemma (quoting Wikipedia)
  11. <https://en.wikipedia.org/wiki/Johnson%E2%80%93Lindenstrauss_lemma>`_:
  12. In mathematics, the Johnson-Lindenstrauss lemma is a result
  13. concerning low-distortion embeddings of points from high-dimensional
  14. into low-dimensional Euclidean space. The lemma states that a small set
  15. of points in a high-dimensional space can be embedded into a space of
  16. much lower dimension in such a way that distances between the points are
  17. nearly preserved. The map used for the embedding is at least Lipschitz,
  18. and can even be taken to be an orthogonal projection.
  19. """
  20. # Authors: Olivier Grisel <olivier.grisel@ensta.org>,
  21. # Arnaud Joly <a.joly@ulg.ac.be>
  22. # License: BSD 3 clause
  23. import warnings
  24. from abc import ABCMeta, abstractmethod
  25. from numbers import Integral, Real
  26. import numpy as np
  27. import scipy.sparse as sp
  28. from scipy import linalg
  29. from .base import (
  30. BaseEstimator,
  31. ClassNamePrefixFeaturesOutMixin,
  32. TransformerMixin,
  33. _fit_context,
  34. )
  35. from .exceptions import DataDimensionalityWarning
  36. from .utils import check_random_state
  37. from .utils._param_validation import Interval, StrOptions, validate_params
  38. from .utils.extmath import safe_sparse_dot
  39. from .utils.random import sample_without_replacement
  40. from .utils.validation import check_array, check_is_fitted
  41. __all__ = [
  42. "SparseRandomProjection",
  43. "GaussianRandomProjection",
  44. "johnson_lindenstrauss_min_dim",
  45. ]
  46. @validate_params(
  47. {
  48. "n_samples": ["array-like", Interval(Real, 1, None, closed="left")],
  49. "eps": ["array-like", Interval(Real, 0, 1, closed="neither")],
  50. },
  51. prefer_skip_nested_validation=True,
  52. )
  53. def johnson_lindenstrauss_min_dim(n_samples, *, eps=0.1):
  54. """Find a 'safe' number of components to randomly project to.
  55. The distortion introduced by a random projection `p` only changes the
  56. distance between two points by a factor (1 +- eps) in a euclidean space
  57. with good probability. The projection `p` is an eps-embedding as defined
  58. by:
  59. (1 - eps) ||u - v||^2 < ||p(u) - p(v)||^2 < (1 + eps) ||u - v||^2
  60. Where u and v are any rows taken from a dataset of shape (n_samples,
  61. n_features), eps is in ]0, 1[ and p is a projection by a random Gaussian
  62. N(0, 1) matrix of shape (n_components, n_features) (or a sparse
  63. Achlioptas matrix).
  64. The minimum number of components to guarantee the eps-embedding is
  65. given by:
  66. n_components >= 4 log(n_samples) / (eps^2 / 2 - eps^3 / 3)
  67. Note that the number of dimensions is independent of the original
  68. number of features but instead depends on the size of the dataset:
  69. the larger the dataset, the higher is the minimal dimensionality of
  70. an eps-embedding.
  71. Read more in the :ref:`User Guide <johnson_lindenstrauss>`.
  72. Parameters
  73. ----------
  74. n_samples : int or array-like of int
  75. Number of samples that should be an integer greater than 0. If an array
  76. is given, it will compute a safe number of components array-wise.
  77. eps : float or array-like of shape (n_components,), dtype=float, \
  78. default=0.1
  79. Maximum distortion rate in the range (0, 1) as defined by the
  80. Johnson-Lindenstrauss lemma. If an array is given, it will compute a
  81. safe number of components array-wise.
  82. Returns
  83. -------
  84. n_components : int or ndarray of int
  85. The minimal number of components to guarantee with good probability
  86. an eps-embedding with n_samples.
  87. References
  88. ----------
  89. .. [1] https://en.wikipedia.org/wiki/Johnson%E2%80%93Lindenstrauss_lemma
  90. .. [2] `Sanjoy Dasgupta and Anupam Gupta, 1999,
  91. "An elementary proof of the Johnson-Lindenstrauss Lemma."
  92. <https://citeseerx.ist.psu.edu/doc_view/pid/95cd464d27c25c9c8690b378b894d337cdf021f9>`_
  93. Examples
  94. --------
  95. >>> from sklearn.random_projection import johnson_lindenstrauss_min_dim
  96. >>> johnson_lindenstrauss_min_dim(1e6, eps=0.5)
  97. 663
  98. >>> johnson_lindenstrauss_min_dim(1e6, eps=[0.5, 0.1, 0.01])
  99. array([ 663, 11841, 1112658])
  100. >>> johnson_lindenstrauss_min_dim([1e4, 1e5, 1e6], eps=0.1)
  101. array([ 7894, 9868, 11841])
  102. """
  103. eps = np.asarray(eps)
  104. n_samples = np.asarray(n_samples)
  105. if np.any(eps <= 0.0) or np.any(eps >= 1):
  106. raise ValueError("The JL bound is defined for eps in ]0, 1[, got %r" % eps)
  107. if np.any(n_samples <= 0):
  108. raise ValueError(
  109. "The JL bound is defined for n_samples greater than zero, got %r"
  110. % n_samples
  111. )
  112. denominator = (eps**2 / 2) - (eps**3 / 3)
  113. return (4 * np.log(n_samples) / denominator).astype(np.int64)
  114. def _check_density(density, n_features):
  115. """Factorize density check according to Li et al."""
  116. if density == "auto":
  117. density = 1 / np.sqrt(n_features)
  118. elif density <= 0 or density > 1:
  119. raise ValueError("Expected density in range ]0, 1], got: %r" % density)
  120. return density
  121. def _check_input_size(n_components, n_features):
  122. """Factorize argument checking for random matrix generation."""
  123. if n_components <= 0:
  124. raise ValueError(
  125. "n_components must be strictly positive, got %d" % n_components
  126. )
  127. if n_features <= 0:
  128. raise ValueError("n_features must be strictly positive, got %d" % n_features)
  129. def _gaussian_random_matrix(n_components, n_features, random_state=None):
  130. """Generate a dense Gaussian random matrix.
  131. The components of the random matrix are drawn from
  132. N(0, 1.0 / n_components).
  133. Read more in the :ref:`User Guide <gaussian_random_matrix>`.
  134. Parameters
  135. ----------
  136. n_components : int,
  137. Dimensionality of the target projection space.
  138. n_features : int,
  139. Dimensionality of the original source space.
  140. random_state : int, RandomState instance or None, default=None
  141. Controls the pseudo random number generator used to generate the matrix
  142. at fit time.
  143. Pass an int for reproducible output across multiple function calls.
  144. See :term:`Glossary <random_state>`.
  145. Returns
  146. -------
  147. components : ndarray of shape (n_components, n_features)
  148. The generated Gaussian random matrix.
  149. See Also
  150. --------
  151. GaussianRandomProjection
  152. """
  153. _check_input_size(n_components, n_features)
  154. rng = check_random_state(random_state)
  155. components = rng.normal(
  156. loc=0.0, scale=1.0 / np.sqrt(n_components), size=(n_components, n_features)
  157. )
  158. return components
  159. def _sparse_random_matrix(n_components, n_features, density="auto", random_state=None):
  160. """Generalized Achlioptas random sparse matrix for random projection.
  161. Setting density to 1 / 3 will yield the original matrix by Dimitris
  162. Achlioptas while setting a lower value will yield the generalization
  163. by Ping Li et al.
  164. If we note :math:`s = 1 / density`, the components of the random matrix are
  165. drawn from:
  166. - -sqrt(s) / sqrt(n_components) with probability 1 / 2s
  167. - 0 with probability 1 - 1 / s
  168. - +sqrt(s) / sqrt(n_components) with probability 1 / 2s
  169. Read more in the :ref:`User Guide <sparse_random_matrix>`.
  170. Parameters
  171. ----------
  172. n_components : int,
  173. Dimensionality of the target projection space.
  174. n_features : int,
  175. Dimensionality of the original source space.
  176. density : float or 'auto', default='auto'
  177. Ratio of non-zero component in the random projection matrix in the
  178. range `(0, 1]`
  179. If density = 'auto', the value is set to the minimum density
  180. as recommended by Ping Li et al.: 1 / sqrt(n_features).
  181. Use density = 1 / 3.0 if you want to reproduce the results from
  182. Achlioptas, 2001.
  183. random_state : int, RandomState instance or None, default=None
  184. Controls the pseudo random number generator used to generate the matrix
  185. at fit time.
  186. Pass an int for reproducible output across multiple function calls.
  187. See :term:`Glossary <random_state>`.
  188. Returns
  189. -------
  190. components : {ndarray, sparse matrix} of shape (n_components, n_features)
  191. The generated Gaussian random matrix. Sparse matrix will be of CSR
  192. format.
  193. See Also
  194. --------
  195. SparseRandomProjection
  196. References
  197. ----------
  198. .. [1] Ping Li, T. Hastie and K. W. Church, 2006,
  199. "Very Sparse Random Projections".
  200. https://web.stanford.edu/~hastie/Papers/Ping/KDD06_rp.pdf
  201. .. [2] D. Achlioptas, 2001, "Database-friendly random projections",
  202. https://cgi.di.uoa.gr/~optas/papers/jl.pdf
  203. """
  204. _check_input_size(n_components, n_features)
  205. density = _check_density(density, n_features)
  206. rng = check_random_state(random_state)
  207. if density == 1:
  208. # skip index generation if totally dense
  209. components = rng.binomial(1, 0.5, (n_components, n_features)) * 2 - 1
  210. return 1 / np.sqrt(n_components) * components
  211. else:
  212. # Generate location of non zero elements
  213. indices = []
  214. offset = 0
  215. indptr = [offset]
  216. for _ in range(n_components):
  217. # find the indices of the non-zero components for row i
  218. n_nonzero_i = rng.binomial(n_features, density)
  219. indices_i = sample_without_replacement(
  220. n_features, n_nonzero_i, random_state=rng
  221. )
  222. indices.append(indices_i)
  223. offset += n_nonzero_i
  224. indptr.append(offset)
  225. indices = np.concatenate(indices)
  226. # Among non zero components the probability of the sign is 50%/50%
  227. data = rng.binomial(1, 0.5, size=np.size(indices)) * 2 - 1
  228. # build the CSR structure by concatenating the rows
  229. components = sp.csr_matrix(
  230. (data, indices, indptr), shape=(n_components, n_features)
  231. )
  232. return np.sqrt(1 / density) / np.sqrt(n_components) * components
  233. class BaseRandomProjection(
  234. TransformerMixin, BaseEstimator, ClassNamePrefixFeaturesOutMixin, metaclass=ABCMeta
  235. ):
  236. """Base class for random projections.
  237. Warning: This class should not be used directly.
  238. Use derived classes instead.
  239. """
  240. _parameter_constraints: dict = {
  241. "n_components": [
  242. Interval(Integral, 1, None, closed="left"),
  243. StrOptions({"auto"}),
  244. ],
  245. "eps": [Interval(Real, 0, None, closed="neither")],
  246. "compute_inverse_components": ["boolean"],
  247. "random_state": ["random_state"],
  248. }
  249. @abstractmethod
  250. def __init__(
  251. self,
  252. n_components="auto",
  253. *,
  254. eps=0.1,
  255. compute_inverse_components=False,
  256. random_state=None,
  257. ):
  258. self.n_components = n_components
  259. self.eps = eps
  260. self.compute_inverse_components = compute_inverse_components
  261. self.random_state = random_state
  262. @abstractmethod
  263. def _make_random_matrix(self, n_components, n_features):
  264. """Generate the random projection matrix.
  265. Parameters
  266. ----------
  267. n_components : int,
  268. Dimensionality of the target projection space.
  269. n_features : int,
  270. Dimensionality of the original source space.
  271. Returns
  272. -------
  273. components : {ndarray, sparse matrix} of shape (n_components, n_features)
  274. The generated random matrix. Sparse matrix will be of CSR format.
  275. """
  276. def _compute_inverse_components(self):
  277. """Compute the pseudo-inverse of the (densified) components."""
  278. components = self.components_
  279. if sp.issparse(components):
  280. components = components.toarray()
  281. return linalg.pinv(components, check_finite=False)
  282. @_fit_context(prefer_skip_nested_validation=True)
  283. def fit(self, X, y=None):
  284. """Generate a sparse random projection matrix.
  285. Parameters
  286. ----------
  287. X : {ndarray, sparse matrix} of shape (n_samples, n_features)
  288. Training set: only the shape is used to find optimal random
  289. matrix dimensions based on the theory referenced in the
  290. afore mentioned papers.
  291. y : Ignored
  292. Not used, present here for API consistency by convention.
  293. Returns
  294. -------
  295. self : object
  296. BaseRandomProjection class instance.
  297. """
  298. X = self._validate_data(
  299. X, accept_sparse=["csr", "csc"], dtype=[np.float64, np.float32]
  300. )
  301. n_samples, n_features = X.shape
  302. if self.n_components == "auto":
  303. self.n_components_ = johnson_lindenstrauss_min_dim(
  304. n_samples=n_samples, eps=self.eps
  305. )
  306. if self.n_components_ <= 0:
  307. raise ValueError(
  308. "eps=%f and n_samples=%d lead to a target dimension of "
  309. "%d which is invalid" % (self.eps, n_samples, self.n_components_)
  310. )
  311. elif self.n_components_ > n_features:
  312. raise ValueError(
  313. "eps=%f and n_samples=%d lead to a target dimension of "
  314. "%d which is larger than the original space with "
  315. "n_features=%d"
  316. % (self.eps, n_samples, self.n_components_, n_features)
  317. )
  318. else:
  319. if self.n_components > n_features:
  320. warnings.warn(
  321. "The number of components is higher than the number of"
  322. " features: n_features < n_components (%s < %s)."
  323. "The dimensionality of the problem will not be reduced."
  324. % (n_features, self.n_components),
  325. DataDimensionalityWarning,
  326. )
  327. self.n_components_ = self.n_components
  328. # Generate a projection matrix of size [n_components, n_features]
  329. self.components_ = self._make_random_matrix(
  330. self.n_components_, n_features
  331. ).astype(X.dtype, copy=False)
  332. if self.compute_inverse_components:
  333. self.inverse_components_ = self._compute_inverse_components()
  334. # Required by ClassNamePrefixFeaturesOutMixin.get_feature_names_out.
  335. self._n_features_out = self.n_components
  336. return self
  337. def inverse_transform(self, X):
  338. """Project data back to its original space.
  339. Returns an array X_original whose transform would be X. Note that even
  340. if X is sparse, X_original is dense: this may use a lot of RAM.
  341. If `compute_inverse_components` is False, the inverse of the components is
  342. computed during each call to `inverse_transform` which can be costly.
  343. Parameters
  344. ----------
  345. X : {array-like, sparse matrix} of shape (n_samples, n_components)
  346. Data to be transformed back.
  347. Returns
  348. -------
  349. X_original : ndarray of shape (n_samples, n_features)
  350. Reconstructed data.
  351. """
  352. check_is_fitted(self)
  353. X = check_array(X, dtype=[np.float64, np.float32], accept_sparse=("csr", "csc"))
  354. if self.compute_inverse_components:
  355. return X @ self.inverse_components_.T
  356. inverse_components = self._compute_inverse_components()
  357. return X @ inverse_components.T
  358. def _more_tags(self):
  359. return {
  360. "preserves_dtype": [np.float64, np.float32],
  361. }
  362. class GaussianRandomProjection(BaseRandomProjection):
  363. """Reduce dimensionality through Gaussian random projection.
  364. The components of the random matrix are drawn from N(0, 1 / n_components).
  365. Read more in the :ref:`User Guide <gaussian_random_matrix>`.
  366. .. versionadded:: 0.13
  367. Parameters
  368. ----------
  369. n_components : int or 'auto', default='auto'
  370. Dimensionality of the target projection space.
  371. n_components can be automatically adjusted according to the
  372. number of samples in the dataset and the bound given by the
  373. Johnson-Lindenstrauss lemma. In that case the quality of the
  374. embedding is controlled by the ``eps`` parameter.
  375. It should be noted that Johnson-Lindenstrauss lemma can yield
  376. very conservative estimated of the required number of components
  377. as it makes no assumption on the structure of the dataset.
  378. eps : float, default=0.1
  379. Parameter to control the quality of the embedding according to
  380. the Johnson-Lindenstrauss lemma when `n_components` is set to
  381. 'auto'. The value should be strictly positive.
  382. Smaller values lead to better embedding and higher number of
  383. dimensions (n_components) in the target projection space.
  384. compute_inverse_components : bool, default=False
  385. Learn the inverse transform by computing the pseudo-inverse of the
  386. components during fit. Note that computing the pseudo-inverse does not
  387. scale well to large matrices.
  388. random_state : int, RandomState instance or None, default=None
  389. Controls the pseudo random number generator used to generate the
  390. projection matrix at fit time.
  391. Pass an int for reproducible output across multiple function calls.
  392. See :term:`Glossary <random_state>`.
  393. Attributes
  394. ----------
  395. n_components_ : int
  396. Concrete number of components computed when n_components="auto".
  397. components_ : ndarray of shape (n_components, n_features)
  398. Random matrix used for the projection.
  399. inverse_components_ : ndarray of shape (n_features, n_components)
  400. Pseudo-inverse of the components, only computed if
  401. `compute_inverse_components` is True.
  402. .. versionadded:: 1.1
  403. n_features_in_ : int
  404. Number of features seen during :term:`fit`.
  405. .. versionadded:: 0.24
  406. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  407. Names of features seen during :term:`fit`. Defined only when `X`
  408. has feature names that are all strings.
  409. .. versionadded:: 1.0
  410. See Also
  411. --------
  412. SparseRandomProjection : Reduce dimensionality through sparse
  413. random projection.
  414. Examples
  415. --------
  416. >>> import numpy as np
  417. >>> from sklearn.random_projection import GaussianRandomProjection
  418. >>> rng = np.random.RandomState(42)
  419. >>> X = rng.rand(25, 3000)
  420. >>> transformer = GaussianRandomProjection(random_state=rng)
  421. >>> X_new = transformer.fit_transform(X)
  422. >>> X_new.shape
  423. (25, 2759)
  424. """
  425. def __init__(
  426. self,
  427. n_components="auto",
  428. *,
  429. eps=0.1,
  430. compute_inverse_components=False,
  431. random_state=None,
  432. ):
  433. super().__init__(
  434. n_components=n_components,
  435. eps=eps,
  436. compute_inverse_components=compute_inverse_components,
  437. random_state=random_state,
  438. )
  439. def _make_random_matrix(self, n_components, n_features):
  440. """Generate the random projection matrix.
  441. Parameters
  442. ----------
  443. n_components : int,
  444. Dimensionality of the target projection space.
  445. n_features : int,
  446. Dimensionality of the original source space.
  447. Returns
  448. -------
  449. components : ndarray of shape (n_components, n_features)
  450. The generated random matrix.
  451. """
  452. random_state = check_random_state(self.random_state)
  453. return _gaussian_random_matrix(
  454. n_components, n_features, random_state=random_state
  455. )
  456. def transform(self, X):
  457. """Project the data by using matrix product with the random matrix.
  458. Parameters
  459. ----------
  460. X : {ndarray, sparse matrix} of shape (n_samples, n_features)
  461. The input data to project into a smaller dimensional space.
  462. Returns
  463. -------
  464. X_new : ndarray of shape (n_samples, n_components)
  465. Projected array.
  466. """
  467. check_is_fitted(self)
  468. X = self._validate_data(
  469. X, accept_sparse=["csr", "csc"], reset=False, dtype=[np.float64, np.float32]
  470. )
  471. return X @ self.components_.T
  472. class SparseRandomProjection(BaseRandomProjection):
  473. """Reduce dimensionality through sparse random projection.
  474. Sparse random matrix is an alternative to dense random
  475. projection matrix that guarantees similar embedding quality while being
  476. much more memory efficient and allowing faster computation of the
  477. projected data.
  478. If we note `s = 1 / density` the components of the random matrix are
  479. drawn from:
  480. - -sqrt(s) / sqrt(n_components) with probability 1 / 2s
  481. - 0 with probability 1 - 1 / s
  482. - +sqrt(s) / sqrt(n_components) with probability 1 / 2s
  483. Read more in the :ref:`User Guide <sparse_random_matrix>`.
  484. .. versionadded:: 0.13
  485. Parameters
  486. ----------
  487. n_components : int or 'auto', default='auto'
  488. Dimensionality of the target projection space.
  489. n_components can be automatically adjusted according to the
  490. number of samples in the dataset and the bound given by the
  491. Johnson-Lindenstrauss lemma. In that case the quality of the
  492. embedding is controlled by the ``eps`` parameter.
  493. It should be noted that Johnson-Lindenstrauss lemma can yield
  494. very conservative estimated of the required number of components
  495. as it makes no assumption on the structure of the dataset.
  496. density : float or 'auto', default='auto'
  497. Ratio in the range (0, 1] of non-zero component in the random
  498. projection matrix.
  499. If density = 'auto', the value is set to the minimum density
  500. as recommended by Ping Li et al.: 1 / sqrt(n_features).
  501. Use density = 1 / 3.0 if you want to reproduce the results from
  502. Achlioptas, 2001.
  503. eps : float, default=0.1
  504. Parameter to control the quality of the embedding according to
  505. the Johnson-Lindenstrauss lemma when n_components is set to
  506. 'auto'. This value should be strictly positive.
  507. Smaller values lead to better embedding and higher number of
  508. dimensions (n_components) in the target projection space.
  509. dense_output : bool, default=False
  510. If True, ensure that the output of the random projection is a
  511. dense numpy array even if the input and random projection matrix
  512. are both sparse. In practice, if the number of components is
  513. small the number of zero components in the projected data will
  514. be very small and it will be more CPU and memory efficient to
  515. use a dense representation.
  516. If False, the projected data uses a sparse representation if
  517. the input is sparse.
  518. compute_inverse_components : bool, default=False
  519. Learn the inverse transform by computing the pseudo-inverse of the
  520. components during fit. Note that the pseudo-inverse is always a dense
  521. array, even if the training data was sparse. This means that it might be
  522. necessary to call `inverse_transform` on a small batch of samples at a
  523. time to avoid exhausting the available memory on the host. Moreover,
  524. computing the pseudo-inverse does not scale well to large matrices.
  525. random_state : int, RandomState instance or None, default=None
  526. Controls the pseudo random number generator used to generate the
  527. projection matrix at fit time.
  528. Pass an int for reproducible output across multiple function calls.
  529. See :term:`Glossary <random_state>`.
  530. Attributes
  531. ----------
  532. n_components_ : int
  533. Concrete number of components computed when n_components="auto".
  534. components_ : sparse matrix of shape (n_components, n_features)
  535. Random matrix used for the projection. Sparse matrix will be of CSR
  536. format.
  537. inverse_components_ : ndarray of shape (n_features, n_components)
  538. Pseudo-inverse of the components, only computed if
  539. `compute_inverse_components` is True.
  540. .. versionadded:: 1.1
  541. density_ : float in range 0.0 - 1.0
  542. Concrete density computed from when density = "auto".
  543. n_features_in_ : int
  544. Number of features seen during :term:`fit`.
  545. .. versionadded:: 0.24
  546. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  547. Names of features seen during :term:`fit`. Defined only when `X`
  548. has feature names that are all strings.
  549. .. versionadded:: 1.0
  550. See Also
  551. --------
  552. GaussianRandomProjection : Reduce dimensionality through Gaussian
  553. random projection.
  554. References
  555. ----------
  556. .. [1] Ping Li, T. Hastie and K. W. Church, 2006,
  557. "Very Sparse Random Projections".
  558. https://web.stanford.edu/~hastie/Papers/Ping/KDD06_rp.pdf
  559. .. [2] D. Achlioptas, 2001, "Database-friendly random projections",
  560. https://cgi.di.uoa.gr/~optas/papers/jl.pdf
  561. Examples
  562. --------
  563. >>> import numpy as np
  564. >>> from sklearn.random_projection import SparseRandomProjection
  565. >>> rng = np.random.RandomState(42)
  566. >>> X = rng.rand(25, 3000)
  567. >>> transformer = SparseRandomProjection(random_state=rng)
  568. >>> X_new = transformer.fit_transform(X)
  569. >>> X_new.shape
  570. (25, 2759)
  571. >>> # very few components are non-zero
  572. >>> np.mean(transformer.components_ != 0)
  573. 0.0182...
  574. """
  575. _parameter_constraints: dict = {
  576. **BaseRandomProjection._parameter_constraints,
  577. "density": [Interval(Real, 0.0, 1.0, closed="right"), StrOptions({"auto"})],
  578. "dense_output": ["boolean"],
  579. }
  580. def __init__(
  581. self,
  582. n_components="auto",
  583. *,
  584. density="auto",
  585. eps=0.1,
  586. dense_output=False,
  587. compute_inverse_components=False,
  588. random_state=None,
  589. ):
  590. super().__init__(
  591. n_components=n_components,
  592. eps=eps,
  593. compute_inverse_components=compute_inverse_components,
  594. random_state=random_state,
  595. )
  596. self.dense_output = dense_output
  597. self.density = density
  598. def _make_random_matrix(self, n_components, n_features):
  599. """Generate the random projection matrix
  600. Parameters
  601. ----------
  602. n_components : int
  603. Dimensionality of the target projection space.
  604. n_features : int
  605. Dimensionality of the original source space.
  606. Returns
  607. -------
  608. components : sparse matrix of shape (n_components, n_features)
  609. The generated random matrix in CSR format.
  610. """
  611. random_state = check_random_state(self.random_state)
  612. self.density_ = _check_density(self.density, n_features)
  613. return _sparse_random_matrix(
  614. n_components, n_features, density=self.density_, random_state=random_state
  615. )
  616. def transform(self, X):
  617. """Project the data by using matrix product with the random matrix.
  618. Parameters
  619. ----------
  620. X : {ndarray, sparse matrix} of shape (n_samples, n_features)
  621. The input data to project into a smaller dimensional space.
  622. Returns
  623. -------
  624. X_new : {ndarray, sparse matrix} of shape (n_samples, n_components)
  625. Projected array. It is a sparse matrix only when the input is sparse and
  626. `dense_output = False`.
  627. """
  628. check_is_fitted(self)
  629. X = self._validate_data(
  630. X, accept_sparse=["csr", "csc"], reset=False, dtype=[np.float64, np.float32]
  631. )
  632. return safe_sparse_dot(X, self.components_.T, dense_output=self.dense_output)