r""" Generates n_projections samples from the uniform on the unit sphere of dimension :math:`d-1`: :math:`\mathcal{U}(\mathcal{S}^{d-1})` Parameters ---------- d : int dimension of the space n_projections : int number of samples requested seed: int or RandomS
(d, n_projections, seed=None, backend=None, type_as=None)
| 20 | |
| 21 | |
| 22 | def get_random_projections(d, n_projections, seed=None, backend=None, type_as=None): |
| 23 | r""" |
| 24 | Generates n_projections samples from the uniform on the unit sphere of dimension :math:`d-1`: :math:`\mathcal{U}(\mathcal{S}^{d-1})` |
| 25 | |
| 26 | Parameters |
| 27 | ---------- |
| 28 | d : int |
| 29 | dimension of the space |
| 30 | n_projections : int |
| 31 | number of samples requested |
| 32 | seed: int or RandomState, optional |
| 33 | Seed used for numpy random number generator |
| 34 | backend: |
| 35 | Backend to use for random generation |
| 36 | |
| 37 | Returns |
| 38 | ------- |
| 39 | out: ndarray, shape (d, n_projections) |
| 40 | The uniform unit vectors on the sphere |
| 41 | |
| 42 | Examples |
| 43 | -------- |
| 44 | >>> n_projections = 100 |
| 45 | >>> d = 5 |
| 46 | >>> projs = get_random_projections(d, n_projections) |
| 47 | >>> np.allclose(np.sum(np.square(projs), 0), 1.) # doctest: +NORMALIZE_WHITESPACE |
| 48 | True |
| 49 | |
| 50 | """ |
| 51 | |
| 52 | if backend is None: |
| 53 | nx = NumpyBackend() |
| 54 | else: |
| 55 | nx = backend |
| 56 | |
| 57 | if isinstance(seed, np.random.RandomState) and str(nx) == "numpy": |
| 58 | projections = seed.randn(d, n_projections) |
| 59 | else: |
| 60 | if seed is not None: |
| 61 | nx.seed(seed) |
| 62 | projections = nx.randn(d, n_projections, type_as=type_as) |
| 63 | |
| 64 | projections = projections / nx.sqrt(nx.sum(projections**2, 0, keepdims=True)) |
| 65 | return projections |
| 66 | |
| 67 | |
| 68 | def sliced_wasserstein_distance( |