MCPcopy Create free account
hub / github.com/ddbourgin/numpy-ml / truncated_normal

Function truncated_normal

numpy_ml/neural_nets/utils/utils.py:998–1030  ·  view source on GitHub ↗

Generate draws from a truncated normal distribution via rejection sampling. Notes ----- The rejection sampling regimen draws samples from a normal distribution with mean `mean` and standard deviation `std`, and resamples any values more than two standard deviations from `me

(mean, std, out_shape)

Source from the content-addressed store, hash-verified

996
997
998def truncated_normal(mean, std, out_shape):
999 """
1000 Generate draws from a truncated normal distribution via rejection sampling.
1001
1002 Notes
1003 -----
1004 The rejection sampling regimen draws samples from a normal distribution
1005 with mean `mean` and standard deviation `std`, and resamples any values
1006 more than two standard deviations from `mean`.
1007
1008 Parameters
1009 ----------
1010 mean : float or array_like of floats
1011 The mean/center of the distribution
1012 std : float or array_like of floats
1013 Standard deviation (spread or "width") of the distribution.
1014 out_shape : int or tuple of ints
1015 Output shape. If the given shape is, e.g., ``(m, n, k)``, then
1016 ``m * n * k`` samples are drawn.
1017
1018 Returns
1019 -------
1020 samples : :py:class:`ndarray <numpy.ndarray>` of shape `out_shape`
1021 Samples from the truncated normal distribution parameterized by `mean`
1022 and `std`.
1023 """
1024 samples = np.random.normal(loc=mean, scale=std, size=out_shape)
1025 reject = np.logical_or(samples >= mean + 2 * std, samples <= mean - 2 * std)
1026 while any(reject.flatten()):
1027 resamples = np.random.normal(loc=mean, scale=std, size=reject.sum())
1028 samples[reject] = resamples
1029 reject = np.logical_or(samples >= mean + 2 * std, samples <= mean - 2 * std)
1030 return samples

Callers 2

he_normalFunction · 0.85
glorot_normalFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected