Ejemplo n.º 1
0
def _get_distribution_over_matrix(dims, cfg):
    """Get the distribution over a matrix given a config.

  Args:
    dims: int dimensions of the matrix.
    cfg: Config generated from `get_distribution_over_matrix` or
      `sample_matrix_noise_dist`.

  Returns:
    The corresponding tfp.distribution.Distribution for the matrix.
  """
    name, params = cfg
    if name == "linspace_eigen":
        # Generates a random matrix whose spectrum is sampled uniformly from the
        # range (min, max).
        spectrum = np.linspace(params["min"], params["max"],
                               dims).astype(np.float32)
        return quadratic_helper.FixedEigenSpectrumMatrixDistribution(spectrum)
    elif name == "logspace_eigen":
        # Generates a random matrix whose spectrum is sampled logrithmically from
        # the range (min, max).
        spectrum = np.logspace(np.log10(params["min"]),
                               np.log10(params["max"]),
                               dims).astype(np.float32)
        return quadratic_helper.FixedEigenSpectrumMatrixDistribution(spectrum)
    elif name == "normal":
        # Generates a random matrix whose values are randomly sampled from a normal
        # with mean and std.
        return tfp.distributions.Normal(
            tf.ones([dims, dims]) * params["mean"],
            tf.ones([dims, dims]) * params["std"])
    elif name == "uniform":
        # Generates a random matrix whose values are randomly sampled from a uniform
        # with mean and std.
        return tfp.distributions.Uniform(
            tf.ones([dims, dims]) * params["min"],
            tf.ones([dims, dims]) * params["max"])
    else:
        raise ValueError("Name of matrix distribution [%s] not supported." %
                         name)
Ejemplo n.º 2
0
    def test_eigen_spectrum_matrix_distribution(self):
        """Ensures that the sampled matrix has the correct eigen spectrum."""
        dims = 5

        specturm = np.linspace(1.0, 2.0, dims).astype(np.float32)
        A_dist = quadratic_helper.FixedEigenSpectrumMatrixDistribution(
            specturm)
        s = A_dist.sample()

        with self.test_session() as sess:
            mat = sess.run(s)
            # Ensure the matrix is not simply a diagonal.
            sum_square_not_diag = np.sum(np.square(mat - np.eye(dims) * mat))
            self.assertGreater(sum_square_not_diag, 1e-3)

            eig_value, _ = np.linalg.eig(mat)
            np.testing.assert_allclose(np.linspace(1, 2, 5),
                                       sorted(eig_value),
                                       rtol=1e-5)