_sketches.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. """ Sketching-based Matrix Computations """
  2. # Author: Jordi Montes <jomsdev@gmail.com>
  3. # August 28, 2017
  4. import numpy as np
  5. from scipy._lib._util import (check_random_state, rng_integers,
  6. _transition_to_rng, _apply_over_batch)
  7. __all__ = ['clarkson_woodruff_transform']
  8. def cwt_matrix(n_rows, n_columns, rng=None):
  9. r"""
  10. Generate a matrix S which represents a Clarkson-Woodruff transform.
  11. Given the desired size of matrix, the method returns a matrix S of size
  12. (n_rows, n_columns) where each column has all the entries set to 0
  13. except for one position which has been randomly set to +1 or -1 with
  14. equal probability.
  15. Parameters
  16. ----------
  17. n_rows : int
  18. Number of rows of S
  19. n_columns : int
  20. Number of columns of S
  21. rng : `numpy.random.Generator`, optional
  22. Pseudorandom number generator state. When `rng` is None, a new
  23. `numpy.random.Generator` is created using entropy from the
  24. operating system. Types other than `numpy.random.Generator` are
  25. passed to `numpy.random.default_rng` to instantiate a ``Generator``.
  26. Returns
  27. -------
  28. S : (n_rows, n_columns) csc_matrix
  29. The returned matrix has ``n_columns`` nonzero entries.
  30. Notes
  31. -----
  32. Given a matrix A, with probability at least 9/10,
  33. .. math:: \|SA\| = (1 \pm \epsilon)\|A\|
  34. Where the error epsilon is related to the size of S.
  35. """
  36. # lazy import to prevent to prevent sparse dependency for whole module (gh-23420)
  37. from scipy.sparse import csc_matrix
  38. rng = check_random_state(rng)
  39. rows = rng_integers(rng, 0, n_rows, n_columns)
  40. cols = np.arange(n_columns+1)
  41. signs = rng.choice([1, -1], n_columns)
  42. S = csc_matrix((signs, rows, cols), shape=(n_rows, n_columns))
  43. return S
  44. @_transition_to_rng("seed", position_num=2)
  45. def clarkson_woodruff_transform(input_matrix, sketch_size, rng=None):
  46. r"""
  47. Applies a Clarkson-Woodruff Transform/sketch to the input matrix.
  48. Given an input_matrix ``A`` of size ``(n, d)``, compute a matrix ``A'`` of
  49. size (sketch_size, d) so that
  50. .. math:: \|Ax\| \approx \|A'x\|
  51. with high probability via the Clarkson-Woodruff Transform, otherwise
  52. known as the CountSketch matrix.
  53. The documentation is written assuming array arguments are of specified
  54. "core" shapes. However, array argument(s) of this function may have additional
  55. "batch" dimensions prepended to the core shape. In this case, the array is treated
  56. as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
  57. Parameters
  58. ----------
  59. input_matrix : array_like, shape (..., n, d)
  60. Input matrix.
  61. sketch_size : int
  62. Number of rows for the sketch.
  63. rng : `numpy.random.Generator`, optional
  64. Pseudorandom number generator state. When `rng` is None, a new
  65. `numpy.random.Generator` is created using entropy from the
  66. operating system. Types other than `numpy.random.Generator` are
  67. passed to `numpy.random.default_rng` to instantiate a ``Generator``.
  68. Returns
  69. -------
  70. A' : array_like
  71. Sketch of the input matrix ``A``, of size ``(sketch_size, d)``.
  72. Notes
  73. -----
  74. To make the statement
  75. .. math:: \|Ax\| \approx \|A'x\|
  76. precise, observe the following result which is adapted from the
  77. proof of Theorem 14 of [2]_ via Markov's Inequality. If we have
  78. a sketch size ``sketch_size=k`` which is at least
  79. .. math:: k \geq \frac{2}{\epsilon^2\delta}
  80. Then for any fixed vector ``x``,
  81. .. math:: \|Ax\| = (1\pm\epsilon)\|A'x\|
  82. with probability at least one minus delta.
  83. This implementation takes advantage of sparsity: computing
  84. a sketch takes time proportional to ``A.nnz``. Data ``A`` which
  85. is in ``scipy.sparse.csc_matrix`` format gives the quickest
  86. computation time for sparse input.
  87. >>> import numpy as np
  88. >>> from scipy import linalg
  89. >>> from scipy import sparse
  90. >>> rng = np.random.default_rng()
  91. >>> n_rows, n_columns, density, sketch_n_rows = 15000, 100, 0.01, 200
  92. >>> A = sparse.rand(n_rows, n_columns, density=density, format='csc')
  93. >>> B = sparse.rand(n_rows, n_columns, density=density, format='csr')
  94. >>> C = sparse.rand(n_rows, n_columns, density=density, format='coo')
  95. >>> D = rng.standard_normal((n_rows, n_columns))
  96. >>> SA = linalg.clarkson_woodruff_transform(A, sketch_n_rows) # fastest
  97. >>> SB = linalg.clarkson_woodruff_transform(B, sketch_n_rows) # fast
  98. >>> SC = linalg.clarkson_woodruff_transform(C, sketch_n_rows) # slower
  99. >>> SD = linalg.clarkson_woodruff_transform(D, sketch_n_rows) # slowest
  100. That said, this method does perform well on dense inputs, just slower
  101. on a relative scale.
  102. References
  103. ----------
  104. .. [1] Kenneth L. Clarkson and David P. Woodruff. Low rank approximation
  105. and regression in input sparsity time. In STOC, 2013.
  106. .. [2] David P. Woodruff. Sketching as a tool for numerical linear algebra.
  107. In Foundations and Trends in Theoretical Computer Science, 2014.
  108. Examples
  109. --------
  110. Create a big dense matrix ``A`` for the example:
  111. >>> import numpy as np
  112. >>> from scipy import linalg
  113. >>> n_rows, n_columns = 15000, 100
  114. >>> rng = np.random.default_rng()
  115. >>> A = rng.standard_normal((n_rows, n_columns))
  116. Apply the transform to create a new matrix with 200 rows:
  117. >>> sketch_n_rows = 200
  118. >>> sketch = linalg.clarkson_woodruff_transform(A, sketch_n_rows, seed=rng)
  119. >>> sketch.shape
  120. (200, 100)
  121. Now with high probability, the true norm is close to the sketched norm
  122. in absolute value.
  123. >>> linalg.norm(A)
  124. 1224.2812927123198
  125. >>> linalg.norm(sketch)
  126. 1226.518328407333
  127. Similarly, applying our sketch preserves the solution to a linear
  128. regression of :math:`\min \|Ax - b\|`.
  129. >>> b = rng.standard_normal(n_rows)
  130. >>> x = linalg.lstsq(A, b)[0]
  131. >>> Ab = np.hstack((A, b.reshape(-1, 1)))
  132. >>> SAb = linalg.clarkson_woodruff_transform(Ab, sketch_n_rows, seed=rng)
  133. >>> SA, Sb = SAb[:, :-1], SAb[:, -1]
  134. >>> x_sketched = linalg.lstsq(SA, Sb)[0]
  135. As with the matrix norm example, ``linalg.norm(A @ x - b)`` is close
  136. to ``linalg.norm(A @ x_sketched - b)`` with high probability.
  137. >>> linalg.norm(A @ x - b)
  138. 122.83242365433877
  139. >>> linalg.norm(A @ x_sketched - b)
  140. 166.58473879945151
  141. """
  142. # lazy import to prevent to prevent sparse dependency for whole module (gh-23420)
  143. from scipy.sparse import issparse
  144. if issparse(input_matrix) and input_matrix.ndim > 2:
  145. message = "Batch support for sparse arrays is not available."
  146. raise NotImplementedError(message)
  147. S = cwt_matrix(sketch_size, input_matrix.shape[-2], rng=rng)
  148. # Despite argument order (required by decorator), this is S @ input_matrix
  149. # Can avoid _batch_dot when gh-22153 is resolved.
  150. return S @ input_matrix if input_matrix.ndim <= 2 else _batch_dot(input_matrix, S)
  151. @_apply_over_batch(('input_matrix', 2))
  152. def _batch_dot(input_matrix, S):
  153. return S @ input_matrix