Python scipy.stats.uniform() Examples

The following are 30 code examples of scipy.stats.uniform(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module scipy.stats , or try the search function .
Example #1
Source File: uniform_test.py    From deep_image_model with Apache License 2.0 6 votes vote down vote up
def testUniformCDF(self):
    with self.test_session():
      batch_size = 6
      a = tf.constant([1.0] * batch_size)
      b = tf.constant([11.0] * batch_size)
      a_v = 1.0
      b_v = 11.0
      x = np.array([-2.5, 2.5, 4.0, 0.0, 10.99, 12.0], dtype=np.float32)

      uniform = tf.contrib.distributions.Uniform(a=a, b=b)

      def _expected_cdf():
        cdf = (x - a_v) / (b_v - a_v)
        cdf[x >= b_v] = 1
        cdf[x < a_v] = 0
        return cdf

      cdf = uniform.cdf(x)
      self.assertAllClose(_expected_cdf(), cdf.eval())

      log_cdf = uniform.log_cdf(x)
      self.assertAllClose(np.log(_expected_cdf()), log_cdf.eval()) 
Example #2
Source File: test_multivariate.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_pairwise_distances(self):
        # Test that the distribution of pairwise distances is close to correct.
        np.random.seed(514)

        def random_ortho(dim):
            u, _s, v = np.linalg.svd(np.random.normal(size=(dim, dim)))
            return np.dot(u, v)

        for dim in range(2, 6):
            def generate_test_statistics(rvs, N=1000, eps=1e-10):
                stats = np.array([
                    np.sum((rvs(dim=dim) - rvs(dim=dim))**2)
                    for _ in range(N)
                ])
                # Add a bit of noise to account for numeric accuracy.
                stats += np.random.uniform(-eps, eps, size=stats.shape)
                return stats

            expected = generate_test_statistics(random_ortho)
            actual = generate_test_statistics(scipy.stats.ortho_group.rvs)

            _D, p = scipy.stats.ks_2samp(expected, actual)

            assert_array_less(.05, p) 
Example #3
Source File: uniform.py    From Effective-Quadratures with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self, lower, upper):
        self.lower = lower
        self.upper = upper
        self.bounds = np.array([-1.0, 1.0])
        if (self.lower is None) or (self.upper is None):
            print('One or more bounds not specified. Assuming [0, 1].')
            self.lower = 0.0
            self.upper = 1.0
        self.mean = 0.5 * (self.upper + self.lower)
        self.variance = 1.0/12.0 * (self.upper - self.lower)**2
        self.x_range_for_pdf = np.linspace(self.lower, self.upper, RECURRENCE_PDF_SAMPLES)
        self.parent = uniform(loc=(self.lower), scale=(self.upper-self.lower))

        self.skewness = 0.0
        self.shape_parameter_A = 0.
        self.shape_parameter_B = 0. 
Example #4
Source File: test_multivariate.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_frozen_dirichlet(self):
        np.random.seed(2846)

        n = np.random.randint(1, 32)
        alpha = np.random.uniform(10e-10, 100, n)

        d = dirichlet(alpha)

        assert_equal(d.var(), dirichlet.var(alpha))
        assert_equal(d.mean(), dirichlet.mean(alpha))
        assert_equal(d.entropy(), dirichlet.entropy(alpha))
        num_tests = 10
        for i in range(num_tests):
            x = np.random.uniform(10e-10, 100, n)
            x /= np.sum(x)
            assert_equal(d.pdf(x[:-1]), dirichlet.pdf(x[:-1], alpha))
            assert_equal(d.logpdf(x[:-1]), dirichlet.logpdf(x[:-1], alpha)) 
Example #5
Source File: test_multivariate.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_haar(self):
        # Test that the eigenvalues, which lie on the unit circle in
        # the complex plane, are uncorrelated.

        # Generate samples
        dim = 5
        samples = 1000  # Not too many, or the test takes too long
        np.random.seed(514)  # Note that the test is sensitive to seed too
        xs = unitary_group.rvs(dim, size=samples)

        # The angles "x" of the eigenvalues should be uniformly distributed
        # Overall this seems to be a necessary but weak test of the distribution.
        eigs = np.vstack(scipy.linalg.eigvals(x) for x in xs)
        x = np.arctan2(eigs.imag, eigs.real)
        res = kstest(x.ravel(), uniform(-np.pi, 2*np.pi).cdf)
        assert_(res.pvalue > 0.05) 
Example #6
Source File: convolutional_sccs.py    From tick with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _construct_generator_obj(self, C_tv_range, C_group_l1_range,
                                 logspace=True):
        generators = []
        if len(C_tv_range) == 2:
            if logspace:
                generators.append(Log10UniformGenerator(*C_tv_range))
            else:
                generators.append(uniform(C_tv_range))
        else:
            generators.append(null_generator)

        if len(C_group_l1_range) == 2:
            if logspace:
                generators.append(Log10UniformGenerator(*C_group_l1_range))
            else:
                generators.append(uniform(C_group_l1_range))
        else:
            generators.append(null_generator)

        return generators

    # Properties # 
Example #7
Source File: test_uniform.py    From chainer with MIT License 6 votes vote down vote up
def setUp_configure(self):
        from scipy import stats
        self.dist = distributions.Uniform
        self.scipy_dist = stats.uniform

        self.test_targets = set([
            'batch_shape', 'cdf', 'entropy', 'event_shape', 'icdf', 'log_prob',
            'mean', 'sample', 'stddev', 'support', 'variance'])

        if self.use_loc_scale:
            loc = numpy.random.uniform(
                -10, 0, self.shape).astype(numpy.float32)
            scale = numpy.random.uniform(
                0, 10, self.shape).astype(numpy.float32)
            self.params = {'loc': loc, 'scale': scale}
            self.scipy_params = {'loc': loc, 'scale': scale}
        else:
            low = numpy.random.uniform(
                -10, 0, self.shape).astype(numpy.float32)
            high = numpy.random.uniform(
                low, low + 10, self.shape).astype(numpy.float32)
            self.params = {'low': low, 'high': high}
            self.scipy_params = {'loc': low, 'scale': high-low}

        self.support = '[low, high]' 
Example #8
Source File: uniform.py    From Effective-Quadratures with GNU Lesser General Public License v2.1 6 votes vote down vote up
def get_cdf(self, points=None):
        """
        A uniform cumulative density function.
        :param points:
                Matrix of points which have to be evaluated
        :param double lower:
            Lower bound of the support of the uniform distribution.
        :param double upper:
            Upper bound of the support of the uniform distribution.
        :return:
            An array of N equidistant values over the support of the distribution.
        :return:
            Cumulative density values along the support of the uniform distribution.
        """
        if points is not None:
            return self.parent.cdf(points)
        else:
            raise ValueError( 'Please digit an input for getCDF method') 
Example #9
Source File: uniform.py    From Effective-Quadratures with GNU Lesser General Public License v2.1 6 votes vote down vote up
def get_pdf(self, points=None):
        """
        A uniform probability distribution.
        :param points:
            Matrix of points which have to be evaluated
        :param double lower:
            Lower bound of the support of the uniform distribution.
        :param double upper:
            Upper bound of the support of the uniform distribution.
        :return:
            An array of N equidistant values over the support of the distribution.
        :return:
            Probability density values along the support of the uniform distribution.
        """
        if points is not None:
            return self.parent.pdf(points)
        else:
            raise ValueError( 'Please digit an input for get_pdf method') 
Example #10
Source File: test_search.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def test_param_sampler():
    # test basic properties of param sampler
    param_distributions = {"kernel": ["rbf", "linear"],
                           "C": uniform(0, 1)}
    sampler = ParameterSampler(param_distributions=param_distributions,
                               n_iter=10, random_state=0)
    samples = [x for x in sampler]
    assert_equal(len(samples), 10)
    for sample in samples:
        assert sample["kernel"] in ["rbf", "linear"]
        assert 0 <= sample["C"] <= 1

    # test that repeated calls yield identical parameters
    param_distributions = {"C": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}
    sampler = ParameterSampler(param_distributions=param_distributions,
                               n_iter=3, random_state=0)
    assert_equal([x for x in sampler], [x for x in sampler])

    if sp_version >= (0, 16):
        param_distributions = {"C": uniform(0, 1)}
        sampler = ParameterSampler(param_distributions=param_distributions,
                                   n_iter=10, random_state=0)
        assert_equal([x for x in sampler], [x for x in sampler]) 
Example #11
Source File: test_search.py    From Surprise with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_randomizedsearchcv_best_estimator(u1_ml100k):
    """Ensure that the best estimator is the one that gives the best score (by
    re-running it)"""

    param_distributions = {'n_epochs': [5], 'lr_all': uniform(0.002, 0.003),
                           'reg_all': uniform(0.04, 0.02), 'n_factors': [1],
                           'init_std_dev': [0]}
    rs = RandomizedSearchCV(SVD, param_distributions, measures=['mae'],
                            cv=PredefinedKFold(), joblib_verbose=100)
    rs.fit(u1_ml100k)
    best_estimator = rs.best_estimator['mae']

    # recompute MAE of best_estimator
    mae = cross_validate(best_estimator, u1_ml100k, measures=['MAE'],
                         cv=PredefinedKFold())['test_mae']

    assert mae == rs.best_score['mae'] 
Example #12
Source File: example_sample_robertson_nopysb_with_dream.py    From PyDREAM with GNU General Public License v3.0 6 votes vote down vote up
def likelihood(parameter_vector):

    parameter_vector = 10**np.array(parameter_vector)

    #Solve ODE system given parameter vector
    yout = odeint(odefunc, y0, tspan, args=(parameter_vector,))

    cout = yout[:, 2]

    #Calculate log probability contribution given simulated experimental values.
    
    logp_ctotal = np.sum(like_ctot.logpdf(cout))
    
    #If simulation failed due to integrator errors, return a log probability of -inf.
    if np.isnan(logp_ctotal):
        logp_ctotal = -np.inf
      
    return logp_ctotal


# Add vector of rate parameters to be sampled as unobserved random variables in DREAM with uniform priors. 
Example #13
Source File: uniform_test.py    From deep_image_model with Apache License 2.0 6 votes vote down vote up
def testUniformSampleWithShape(self):
    with self.test_session():
      a = 10.0
      b = [11.0, 20.0]
      uniform = tf.contrib.distributions.Uniform(a, b)

      pdf = uniform.pdf(uniform.sample((2, 3)))
      # pylint: disable=bad-continuation
      expected_pdf = [
        [[1.0, 0.1],
         [1.0, 0.1],
         [1.0, 0.1]],
        [[1.0, 0.1],
         [1.0, 0.1],
         [1.0, 0.1]],
      ]
      # pylint: enable=bad-continuation
      self.assertAllClose(expected_pdf, pdf.eval())

      pdf = uniform.pdf(uniform.sample())
      expected_pdf = [1.0, 0.1]
      self.assertAllClose(expected_pdf, pdf.eval()) 
Example #14
Source File: uniform_test.py    From deep_image_model with Apache License 2.0 6 votes vote down vote up
def testUniformPDF(self):
    with self.test_session():
      a = tf.constant([-3.0] * 5 + [15.0])
      b = tf.constant([11.0] * 5 + [20.0])
      uniform = tf.contrib.distributions.Uniform(a=a, b=b)

      a_v = -3.0
      b_v = 11.0
      x = np.array([-10.5, 4.0, 0.0, 10.99, 11.3, 17.0], dtype=np.float32)

      def _expected_pdf():
        pdf = np.zeros_like(x) + 1.0 / (b_v - a_v)
        pdf[x > b_v] = 0.0
        pdf[x < a_v] = 0.0
        pdf[5] = 1.0 / (20.0 - 15.0)
        return pdf

      expected_pdf = _expected_pdf()

      pdf = uniform.pdf(x)
      self.assertAllClose(expected_pdf, pdf.eval())

      log_pdf = uniform.log_pdf(x)
      self.assertAllClose(np.log(expected_pdf), log_pdf.eval()) 
Example #15
Source File: uniform_test.py    From deep_image_model with Apache License 2.0 6 votes vote down vote up
def testUniformSample(self):
    with self.test_session():
      a = tf.constant([3.0, 4.0])
      b = tf.constant(13.0)
      a1_v = 3.0
      a2_v = 4.0
      b_v = 13.0
      n = tf.constant(100000)
      uniform = tf.contrib.distributions.Uniform(a=a, b=b)

      samples = uniform.sample(n, seed=137)
      sample_values = samples.eval()
      self.assertEqual(sample_values.shape, (100000, 2))
      self.assertAllClose(sample_values[::, 0].mean(), (b_v + a1_v) / 2,
                          atol=1e-2)
      self.assertAllClose(sample_values[::, 1].mean(), (b_v + a2_v) / 2,
                          atol=1e-2)
      self.assertFalse(np.any(sample_values[::, 0] < a1_v) or np.any(
          sample_values >= b_v))
      self.assertFalse(np.any(sample_values[::, 1] < a2_v) or np.any(
          sample_values >= b_v)) 
Example #16
Source File: uniform_test.py    From deep_image_model with Apache License 2.0 6 votes vote down vote up
def testUniformNans(self):
    with self.test_session():
      a = 10.0
      b = [11.0, 100.0]
      uniform = tf.contrib.distributions.Uniform(a=a, b=b)

      no_nans = tf.constant(1.0)
      nans = tf.constant(0.0) / tf.constant(0.0)
      self.assertTrue(tf.is_nan(nans).eval())
      with_nans = tf.stack([no_nans, nans])

      pdf = uniform.pdf(with_nans)

      is_nan = tf.is_nan(pdf).eval()
      self.assertFalse(is_nan[0])
      self.assertTrue(is_nan[1]) 
Example #17
Source File: uniform_test.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def testUniformSamplePdf(self):
    with self.test_session():
      a = 10.0
      b = [11.0, 100.0]
      uniform = tf.contrib.distributions.Uniform(a, b)
      self.assertTrue(tf.reduce_all(uniform.pdf(uniform.sample(10)) > 0).eval(
      )) 
Example #18
Source File: uniform_test.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def testUniformBroadcasting(self):
    with self.test_session():
      a = 10.0
      b = [11.0, 20.0]
      uniform = tf.contrib.distributions.Uniform(a, b)

      pdf = uniform.pdf([[10.5, 11.5], [9.0, 19.0], [10.5, 21.0]])
      expected_pdf = np.array([[1.0, 0.1], [0.0, 0.1], [1.0, 0.0]])
      self.assertAllClose(expected_pdf, pdf.eval()) 
Example #19
Source File: uniform_test.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def testUniformVariance(self):
    with self.test_session():
      a = 10.0
      b = 100.0
      uniform = tf.contrib.distributions.Uniform(a=a, b=b)
      s_uniform = stats.uniform(loc=a, scale=b-a)
      self.assertAllClose(uniform.variance().eval(), s_uniform.var()) 
Example #20
Source File: uniform_test.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def testUniformMean(self):
    with self.test_session():
      a = 10.0
      b = 100.0
      uniform = tf.contrib.distributions.Uniform(a=a, b=b)
      s_uniform = stats.uniform(loc=a, scale=b-a)
      self.assertAllClose(uniform.mean().eval(), s_uniform.mean()) 
Example #21
Source File: uniform_test.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def _testUniformSampleMultiDimensional(self):
    # DISABLED: Please enable this test once b/issues/30149644 is resolved.
    with self.test_session():
      batch_size = 2
      a_v = [3.0, 22.0]
      b_v = [13.0, 35.0]
      a = tf.constant([a_v] * batch_size)
      b = tf.constant([b_v] * batch_size)

      uniform = tf.contrib.distributions.Uniform(a=a, b=b)

      n_v = 100000
      n = tf.constant(n_v)
      samples = uniform.sample(n)
      self.assertEqual(samples.get_shape(), (n_v, batch_size, 2))

      sample_values = samples.eval()

      self.assertFalse(np.any(sample_values[:, 0, 0] < a_v[0]) or np.any(
          sample_values[:, 0, 0] >= b_v[0]))
      self.assertFalse(np.any(sample_values[:, 0, 1] < a_v[1]) or np.any(
          sample_values[:, 0, 1] >= b_v[1]))

      self.assertAllClose(sample_values[:, 0, 0].mean(), (a_v[0] + b_v[0]) / 2,
                          atol=1e-2)
      self.assertAllClose(sample_values[:, 0, 1].mean(), (a_v[1] + b_v[1]) / 2,
                          atol=1e-2) 
Example #22
Source File: tuning.py    From RIDDLE with Apache License 2.0 5 votes vote down vote up
def rvs(self, random_state=None):
        """Draw a value from this random variable."""
        if self.mass_on_zero > 0.0 and np.random.uniform() < self.mass_on_zero:
            return 0.0
        return uniform(loc=self.lo, scale=self.scale).rvs(
            random_state=random_state) 
Example #23
Source File: tuning.py    From RIDDLE with Apache License 2.0 5 votes vote down vote up
def __init__(self, lo=0, hi=1, mass_on_zero=0.0):
        """Initialize random uniform floating number generator.

        Arguments:
            lo: float
                lowest number in range
            hi: float
                highest number in range
            mass_on_zero: float
                probability that zero be returned
        """
        self.lo = lo
        self.scale = hi - lo
        self.mass_on_zero = mass_on_zero 
Example #24
Source File: uniform_test.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def testUniformAssertMaxGtMin(self):
    with self.test_session():
      a_v = np.array([1.0, 1.0, 1.0], dtype=np.float32)
      b_v = np.array([1.0, 2.0, 3.0], dtype=np.float32)
      uniform = tf.contrib.distributions.Uniform(
          a=a_v, b=b_v, validate_args=True)

      with self.assertRaisesWithPredicateMatch(tf.errors.InvalidArgumentError,
                                               "x < y"):
        uniform.a.eval() 
Example #25
Source File: uniform.py    From Effective-Quadratures with GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_description(self):
        """
        A description of the Gaussian.

        :param Gaussian self:
            An instance of the Gaussian class.
        :return:
            A string describing the Gaussian.
        """
        text = "is a uniform distribution over the support "+str(self.lower)+" to "+str(self.upper)+"."
        return text 
Example #26
Source File: dgp_examples.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, nobs=200, x=None, distr_x=None, distr_noise=None):
        if x is None and distr_x is None:
            from scipy import stats
            distr_x = stats.uniform(-2, 4)
        else:
            nobs = x.shape[0]
        self.s_noise = 2.
        self.func = func1
        super(UnivariateFunc1, self).__init__(nobs=nobs, x=x,
                                             distr_x=distr_x,
                                             distr_noise=distr_noise) 
Example #27
Source File: test_sklearn.py    From scikit-neuralnetwork with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_RandomGlobalParams(self):
        clf = RandomizedSearchCV(
                    self.__estimator__(layers=[L("Sigmoid")], n_iter=1),
                    param_distributions={'learning_rate': uniform(0.001, 0.01)},
                    n_iter=2)
        clf.fit(self.a_in, self.a_out) 
Example #28
Source File: test_sklearn.py    From scikit-neuralnetwork with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.a_in = numpy.random.uniform(0.0, 1.0, (64,16))
        self.a_out = numpy.zeros((64,1)) 
Example #29
Source File: test_sklearn.py    From scikit-neuralnetwork with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.a_in = numpy.random.uniform(0.0, 1.0, (64,16))
        self.a_out = numpy.random.randint(0, 4, (64,)) 
Example #30
Source File: dgp_examples.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, nobs=50, x=None, distr_x=None, distr_noise=None):
        if distr_x is None:
            from scipy import stats
            distr_x = stats.uniform
        self.s_noise = 0.15
        self.func = fg1eu
        super(self.__class__, self).__init__(nobs=nobs, x=x,
                                             distr_x=distr_x,
                                             distr_noise=distr_noise)