Python scipy.stats.norm.pdf() Examples
The following are 30
code examples of scipy.stats.norm.pdf().
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.norm
, or try the search function
.
Example #1
Source File: test_multivariate.py From GraphicDesignPatternByPython with MIT License | 7 votes |
def test_marginalization(self): # Integrating out one of the variables of a 2D Gaussian should # yield a 1D Gaussian mean = np.array([2.5, 3.5]) cov = np.array([[.5, 0.2], [0.2, .6]]) n = 2 ** 8 + 1 # Number of samples delta = 6 / (n - 1) # Grid spacing v = np.linspace(0, 6, n) xv, yv = np.meshgrid(v, v) pos = np.empty((n, n, 2)) pos[:, :, 0] = xv pos[:, :, 1] = yv pdf = multivariate_normal.pdf(pos, mean, cov) # Marginalize over x and y axis margin_x = romb(pdf, delta, axis=0) margin_y = romb(pdf, delta, axis=1) # Compare with standard normal distribution gauss_x = norm.pdf(v, loc=mean[0], scale=cov[0, 0] ** 0.5) gauss_y = norm.pdf(v, loc=mean[1], scale=cov[1, 1] ** 0.5) assert_allclose(margin_x, gauss_x, rtol=1e-2, atol=1e-2) assert_allclose(margin_y, gauss_y, rtol=1e-2, atol=1e-2)
Example #2
Source File: acquisition.py From pyGPGO with MIT License | 6 votes |
def ExpectedImprovement(self, tau, mean, std): """ Expected Improvement acquisition function. Parameters ---------- tau: float Best observed function evaluation. mean: float Point mean of the posterior process. std: float Point std of the posterior process. Returns ------- float Expected improvement. """ z = (mean - tau - self.eps) / (std + self.eps) return (mean - tau) * norm.cdf(z) + std * norm.pdf(z)[0]
Example #3
Source File: acquisition_functions.py From CatLearn with GNU General Public License v3.0 | 6 votes |
def EI(y_best, predictions, uncertainty, objective='max'): """Return expected improvement acq. function. Parameters ---------- y_best : float Condition predictions : list Predicted means. uncertainty : list Uncertainties associated with the predictions. """ if objective == 'max': z = (predictions - y_best) / (uncertainty) return (predictions - y_best) * norm.cdf(z) + \ uncertainty * norm.pdf( z) if objective == 'min': z = (-predictions + y_best) / (uncertainty) return -((predictions - y_best) * norm.cdf(z) - uncertainty * norm.pdf(z))
Example #4
Source File: particleFilter.py From Mask-RCNN-Pedestrian-Detection with MIT License | 6 votes |
def sensorModel(particles, numParticles, boxX, boxY): totalW = 0 for i in range(numParticles): x = particles[i].x y = particles[i].y dx = abs(boxX - x) dy = abs(boxY - y) dist = math.sqrt(dx**2 + dy**2) if dist == 0: dist = 0.1 bias = 1/dist particles[i].weight = norm.pdf(bias) totalW += particles[i].weight for i in range(numParticles): particles[i].weight = particles[i].weight/totalW return particles
Example #5
Source File: DistanceTransform.py From MOTSFusion with MIT License | 6 votes |
def encode_extreme_points(mask, use_gaussian): nz = mask.nonzero() assert nz[0].size > 0, "mask cannot be empty" ymin_idx = nz[0].argmin() ymax_idx = nz[0].argmax() xmin_idx = nz[1].argmin() xmax_idx = nz[1].argmax() ymin = (nz[0][ymin_idx], nz[1][ymin_idx]) ymax = (nz[0][ymax_idx], nz[1][ymax_idx]) xmin = (nz[0][xmin_idx], nz[1][xmin_idx]) xmax = (nz[0][xmax_idx], nz[1][xmax_idx]) pts = (ymin, ymax, xmin, xmax) distance_transform_extreme_pts = get_distance_transform(pts, mask) distance_transform_extreme_pts[distance_transform_extreme_pts > 20] = 20 if use_gaussian: distance_transform_extreme_pts = norm.pdf(distance_transform_extreme_pts, loc=0, scale=10) * 25 else: distance_transform_extreme_pts /= 20.0 return distance_transform_extreme_pts.astype(np.float32)
Example #6
Source File: env_priors.py From RoBO with BSD 3-Clause "New" or "Revised" License | 6 votes |
def lnprob(self, theta): lp = 0 # Covariance amplitude lp += self.ln_prior.lnprob(theta[0]) # Lengthscales lp += self.tophat.lnprob(theta[1:self.n_ls + 1]) # Prior for the Bayesian regression kernel pos = (self.n_ls + 1) end = (self.n_ls + self.n_lr + 1) lp += -np.sum((theta[pos:end]) ** 2 / 10.) # alpha lp += norm.pdf(theta[end], loc=-7, scale=1) # beta lp += norm.pdf(theta[end + 1], loc=0.5, scale=1) # Noise lp += self.horseshoe.lnprob(theta[-1]) return lp
Example #7
Source File: acquisition.py From pyGPGO with MIT License | 6 votes |
def tExpectedImprovement(self, tau, mean, std, nu=3.0): """ Expected Improvement acquisition function. Only to be used with `tStudentProcess` surrogate. Parameters ---------- tau: float Best observed function evaluation. mean: float Point mean of the posterior process. std: float Point std of the posterior process. Returns ------- float Expected improvement. """ gamma = (mean - tau - self.eps) / (std + self.eps) return gamma * std * t.cdf(gamma, df=nu) + std * (1 + (gamma ** 2 - 1)/(nu - 1)) * t.pdf(gamma, df=nu)
Example #8
Source File: test_multivariate.py From GraphicDesignPatternByPython with MIT License | 6 votes |
def test_frozen_matrix_normal(self): for i in range(1,5): for j in range(1,5): M = 0.3 * np.ones((i,j)) U = 0.5 * np.identity(i) + 0.5 * np.ones((i,i)) V = 0.7 * np.identity(j) + 0.3 * np.ones((j,j)) frozen = matrix_normal(mean=M, rowcov=U, colcov=V) rvs1 = frozen.rvs(random_state=1234) rvs2 = matrix_normal.rvs(mean=M, rowcov=U, colcov=V, random_state=1234) assert_equal(rvs1, rvs2) X = frozen.rvs(random_state=1234) pdf1 = frozen.pdf(X) pdf2 = matrix_normal.pdf(X, mean=M, rowcov=U, colcov=V) assert_equal(pdf1, pdf2) logpdf1 = frozen.logpdf(X) logpdf2 = matrix_normal.logpdf(X, mean=M, rowcov=U, colcov=V) assert_equal(logpdf1, logpdf2)
Example #9
Source File: test_multivariate.py From GraphicDesignPatternByPython with MIT License | 6 votes |
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 #10
Source File: mcmc.py From LearningApacheSpark with MIT License | 5 votes |
def dnorm(x,mean,sd, log=False): """ same functions as dnorm in r dnorm(x, mean=0, sd=1, log=FALSE) pdf(x, loc=0, scale=1) """ if log: return np.log(norm.pdf(x=x,loc=mean,scale=sd)) else: return norm.pdf(x=x,loc=mean,scale=sd)
Example #11
Source File: pyglmnet.py From pyglmnet with MIT License | 5 votes |
def _grad_mu(distr, z, eta): """Derivative of the non-linearity.""" if distr in ['softplus', 'gamma']: grad_mu = expit(z) elif distr == 'poisson': grad_mu = z.copy() grad_mu[z > eta] = np.ones_like(z)[z > eta] * np.exp(eta) grad_mu[z <= eta] = np.exp(z[z <= eta]) elif distr == 'gaussian': grad_mu = np.ones_like(z) elif distr == 'binomial': grad_mu = expit(z) * (1 - expit(z)) elif distr in 'probit': grad_mu = norm.pdf(z) return grad_mu
Example #12
Source File: test_multivariate.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_data_vector_too_long(self): alpha = np.array([1.0, 2.0, 3.0, 4.0]) x = np.ones((5, 7)) / 5 assert_raises(ValueError, dirichlet.pdf, x, alpha) assert_raises(ValueError, dirichlet.logpdf, x, alpha)
Example #13
Source File: stable.py From copulae with MIT License | 5 votes |
def logpdf(cls, x: Numeric, alpha: float, beta: float, gamma=1., delta=0., pm=0): """ Returns log of density for stable DF Parameters ---------- x: {array_like, scalar} Numeric vector of quantiles. alpha: float Value of the index parameter alpha in the interval = (0, 2] beta: float Skewness parameter in the range [-1, 1] gamma: float Scale parameter delta: float Location (or ‘shift’) parameter delta. pm: {0, 1, 2} Type of parameterization, an integer in {0, 1, 2}. Defaults to 0, 'S0' parameterization. Returns ------- {array_like, scalar} Numeric vectors of density """ return cls.pdf(x, alpha, beta, gamma, delta, pm, log=True)
Example #14
Source File: human_pose_nn.py From gait-recognition with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _get_gauss_filter(size = 15, std = 1.0, kernel_sum = 1.0): samples = norm.pdf(np.linspace(-2, 2, size), 0, std) samples /= np.sum(samples) samples *= kernel_sum ** 0.5 samples = np.expand_dims(samples, 0) weights = np.zeros(shape = (1, size, 16, 1), dtype = np.float32) for i in range(16): weights[:, :, i, 0] = samples return weights
Example #15
Source File: visualizer.py From PyAutoLens with MIT License | 5 votes |
def visualize_stochastic_histogram( self, log_evidences, max_log_evidence, during_analysis ): if log_evidences is None: return plotter = self.plotter.plotter_with_new_output( path=self.plotter.output.path + "other/" ) if self.plot_stochastic_histogram and not during_analysis: bins = conf.instance.general.get( "inversion", "stochastic_histogram_bins", int ) (mu, sigma) = norm.fit(log_evidences) n, bins, patches = plt.hist(x=log_evidences, bins=bins, density=1) y = norm.pdf(bins, mu, sigma) plt.plot(bins, y, "--") plt.xlabel("log evidence") plt.title("Stochastic Log Evidence Histogram") plt.axvline(max_log_evidence, color="r") plt.savefig( f"{plotter.output.path}stochastic_histogram.png", bbox_inches="tight" )
Example #16
Source File: utils.py From pyldpc with BSD 3-Clause "New" or "Revised" License | 5 votes |
def f1(y, sigma): """Compute normal density N(1,sigma).""" f = norm.pdf(y, loc=1, scale=sigma) return f
Example #17
Source File: test_multivariate.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_frozen(self): # Test that the frozen and non-frozen Wishart gives the same answers # Construct an arbitrary positive definite scale matrix dim = 4 scale = np.diag(np.arange(dim)+1) scale[np.tril_indices(dim, k=-1)] = np.arange(dim * (dim-1) // 2) scale = np.dot(scale.T, scale) # Construct a collection of positive definite matrices to test the PDF X = [] for i in range(5): x = np.diag(np.arange(dim)+(i+1)**2) x[np.tril_indices(dim, k=-1)] = np.arange(dim * (dim-1) // 2) x = np.dot(x.T, x) X.append(x) X = np.array(X).T # Construct a 1D and 2D set of parameters parameters = [ (10, 1, np.linspace(0.1, 10, 5)), # 1D case (10, scale, X) ] for (df, scale, x) in parameters: w = wishart(df, scale) assert_equal(w.var(), wishart.var(df, scale)) assert_equal(w.mean(), wishart.mean(df, scale)) assert_equal(w.mode(), wishart.mode(df, scale)) assert_equal(w.entropy(), wishart.entropy(df, scale)) assert_equal(w.pdf(x), wishart.pdf(x, df, scale))
Example #18
Source File: test_multivariate.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_multiple_entry_calls(self): # Test that calls with multiple x vectors as matrix work np.random.seed(2846) n = np.random.randint(1, 32) alpha = np.random.uniform(10e-10, 100, n) d = dirichlet(alpha) num_tests = 10 num_multiple = 5 xm = None for i in range(num_tests): for m in range(num_multiple): x = np.random.uniform(10e-10, 100, n) x /= np.sum(x) if xm is not None: xm = np.vstack((xm, x)) else: xm = x rm = d.pdf(xm.T) rs = None for xs in xm: r = d.pdf(xs) if rs is not None: rs = np.append(rs, r) else: rs = r assert_array_almost_equal(rm, rs)
Example #19
Source File: pyglmnet.py From pyglmnet with MIT License | 5 votes |
def _logL(distr, y, y_hat, z=None): """The log likelihood.""" if distr in ['softplus', 'poisson']: eps = np.spacing(1) logL = np.sum(y * np.log(y_hat + eps) - y_hat) elif distr == 'gaussian': logL = -0.5 * np.sum((y - y_hat)**2) elif distr == 'binomial': # prevents underflow if z is not None: logL = np.sum(y * z - np.log(1 + np.exp(z))) # for scoring else: logL = np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat)) elif distr == 'probit': if z is not None: pdfz, cdfz = norm.pdf(z), norm.cdf(z) logL = np.sum(y * _probit_g1(z, pdfz, cdfz) + (1 - y) * _probit_g2(z, pdfz, cdfz)) else: logL = np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat)) elif distr == 'gamma': # see # https://www.statistics.ma.tum.de/fileadmin/w00bdb/www/czado/lec8.pdf nu = 1. # shape parameter, exponential for now logL = np.sum(nu * (-y / y_hat - np.log(y_hat))) return logL
Example #20
Source File: test_multivariate.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_K_and_K_minus_1_calls_equal(self): # Test that calls with K and K-1 entries yield the same results. np.random.seed(2846) n = np.random.randint(1, 32) alpha = np.random.uniform(10e-10, 100, n) d = dirichlet(alpha) num_tests = 10 for i in range(num_tests): x = np.random.uniform(10e-10, 100, n) x /= np.sum(x) assert_almost_equal(d.pdf(x[:-1]), d.pdf(x))
Example #21
Source File: test_multivariate.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_scalar_values(self): alpha = np.array([0.2]) d = dirichlet(alpha) # For alpha of length 1, mean and var should be scalar instead of array assert_equal(d.mean().ndim, 0) assert_equal(d.var().ndim, 0) assert_equal(d.pdf([1.]).ndim, 0) assert_equal(d.logpdf([1.]).ndim, 0)
Example #22
Source File: test_multivariate.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_frozen(self): # Test that the frozen and non-frozen inverse Wishart gives the same # answers # Construct an arbitrary positive definite scale matrix dim = 4 scale = np.diag(np.arange(dim)+1) scale[np.tril_indices(dim, k=-1)] = np.arange(dim*(dim-1)/2) scale = np.dot(scale.T, scale) # Construct a collection of positive definite matrices to test the PDF X = [] for i in range(5): x = np.diag(np.arange(dim)+(i+1)**2) x[np.tril_indices(dim, k=-1)] = np.arange(dim*(dim-1)/2) x = np.dot(x.T, x) X.append(x) X = np.array(X).T # Construct a 1D and 2D set of parameters parameters = [ (10, 1, np.linspace(0.1, 10, 5)), # 1D case (10, scale, X) ] for (df, scale, x) in parameters: iw = invwishart(df, scale) assert_equal(iw.var(), invwishart.var(df, scale)) assert_equal(iw.mean(), invwishart.mean(df, scale)) assert_equal(iw.mode(), invwishart.mode(df, scale)) assert_allclose(iw.pdf(x), invwishart.pdf(x, df, scale))
Example #23
Source File: test_multivariate.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_data_vector_too_short(self): alpha = np.array([1.0, 2.0, 3.0, 4.0]) x = np.ones((2, 7)) / 2 assert_raises(ValueError, dirichlet.pdf, x, alpha) assert_raises(ValueError, dirichlet.logpdf, x, alpha)
Example #24
Source File: test_multivariate.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_alpha_correct_depth(self): alpha = np.array([1.0, 2.0, 3.0]) x = np.ones((3, 7)) / 3 dirichlet.pdf(x, alpha) dirichlet.logpdf(x, alpha)
Example #25
Source File: test_multivariate.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_alpha_too_deep(self): alpha = np.array([[1.0, 2.0], [3.0, 4.0]]) x = np.ones((2, 2, 7)) / 4 assert_raises(ValueError, dirichlet.pdf, x, alpha) assert_raises(ValueError, dirichlet.logpdf, x, alpha)
Example #26
Source File: test_multivariate.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_data_too_deep_c(self): alpha = np.array([1.0, 2.0, 3.0]) x = np.ones((2, 7, 7)) / 14 assert_raises(ValueError, dirichlet.pdf, x, alpha) assert_raises(ValueError, dirichlet.logpdf, x, alpha)
Example #27
Source File: test_multivariate.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_data_with_too_large_entries(self): alpha = np.array([1.0, 2.0, 3.0, 4.0]) x = np.array([0.1, 1.1, 0.3, 0.7]) assert_raises(ValueError, dirichlet.pdf, x, alpha) assert_raises(ValueError, dirichlet.logpdf, x, alpha)
Example #28
Source File: test_multivariate.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_data_with_negative_entries(self): alpha = np.array([1.0, 2.0, 3.0, 4.0]) x = np.array([0.1, -0.1, 0.3, 0.7]) assert_raises(ValueError, dirichlet.pdf, x, alpha) assert_raises(ValueError, dirichlet.logpdf, x, alpha)
Example #29
Source File: test_multivariate.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_data_with_zeros(self): alpha = np.array([1.0, 2.0, 3.0, 4.0]) x = np.array([0.1, 0.0, 0.2, 0.7]) dirichlet.pdf(x, alpha) dirichlet.logpdf(x, alpha) alpha = np.array([1.0, 1.0, 1.0, 1.0]) assert_almost_equal(dirichlet.pdf(x, alpha), 6) assert_almost_equal(dirichlet.logpdf(x, alpha), np.log(6))
Example #30
Source File: test_multivariate.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_alpha_with_negative_entries(self): np.random.seed(2846) alpha = [1.0, -2.0, 3.0] # don't pass invalid alpha to np.random.dirichlet x = np.random.dirichlet(np.maximum(1e-9, alpha), size=7).T assert_raises(ValueError, dirichlet.pdf, x, alpha) assert_raises(ValueError, dirichlet.logpdf, x, alpha)