本文整理汇总了Python中scipy.stats.truncnorm.rvs方法的典型用法代码示例。如果您正苦于以下问题:Python truncnorm.rvs方法的具体用法?Python truncnorm.rvs怎么用?Python truncnorm.rvs使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.stats.truncnorm
的用法示例。
在下文中一共展示了truncnorm.rvs方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: rvs
# 需要导入模块: from scipy.stats import truncnorm [as 别名]
# 或者: from scipy.stats.truncnorm import rvs [as 别名]
def rvs(self) -> float:
"""
Will return a float value in the specified range as specified at creation.
:return: a float.
"""
if self.hard_clip_min is None and self.hard_clip_max is None:
result = float(np.random.normal(self._mean, self._std))
else:
a = -np.inf
b = np.inf
if self.hard_clip_min is not None:
a = (self.hard_clip_min - self._mean) / self._std
if self.hard_clip_max is not None:
b = (self.hard_clip_max - self._mean) / self._std
result = truncnorm.rvs(a=a, b=b, loc=self._mean, scale=self._std)
if not math.isfinite(result):
return self.rvs()
return float(result)
示例2: __init__
# 需要导入模块: from scipy.stats import truncnorm [as 别名]
# 或者: from scipy.stats.truncnorm import rvs [as 别名]
def __init__(self, log2_space_mean: float, log2_space_std: float,
hard_clip_min: float = None, hard_clip_max: float = None, null_default_value=None):
"""
Create a LogNormal distribution.
:param log2_space_mean: the most common value to pop, but before taking 2**value.
:param log2_space_std: the standard deviation of the most common value to pop, but before taking 2**value.
:param hard_clip_min: if not none, rvs will return max(result, hard_clip_min). This value is not checked in logspace (so it is checked after the exp).
:param hard_clip_max: if not none, rvs will return min(result, hard_clip_min). This value is not checked in logspace (so it is checked after the exp).
:param null_default_value: null default value for distribution. if None, take the hard_clip_min
:type null_default_value: int
"""
if null_default_value is None:
HyperparameterDistribution.__init__(self, hard_clip_min)
else:
HyperparameterDistribution.__init__(self, null_default_value)
self.log2_space_mean = log2_space_mean
self.log2_space_std = log2_space_std
self.hard_clip_min = hard_clip_min
self.hard_clip_max = hard_clip_max
示例3: trunc_norm_trendify
# 需要导入模块: from scipy.stats import truncnorm [as 别名]
# 或者: from scipy.stats.truncnorm import rvs [as 别名]
def trunc_norm_trendify(self, loc, var_scale=0.1):
"""
This function is used to draw a sample from a bounded linear trend with
some noise.
Y = (min - max)* loc + min + noise
The user can control the expectation and variance of the values
provided by this function. Note the upper and lower bounds come from the
data_gen object.
Args:
loc (float): This controls the expectation of the produced variate.
This should specify the percentage of the way between the
[min, max] range to center values.
var_scale (float): This controls the variance of teh produced
variate. This should b
"""
loc = min(max(loc, 0.0), 1.0)
var_scale = min(max(var_scale, 0.0), 1.0)
lower_bound = self.data_gen.min_float
upper_bound = self.data_gen.max_float
mu = loc * (upper_bound - lower_bound) + lower_bound
sigma = var_scale * (upper_bound - lower_bound)
a, b = (lower_bound - mu) / sigma, (upper_bound - mu) / sigma
return truncnorm.rvs(a, b, mu, sigma)
示例4: truncated_z_sample
# 需要导入模块: from scipy.stats import truncnorm [as 别名]
# 或者: from scipy.stats.truncnorm import rvs [as 别名]
def truncated_z_sample(batch_size, truncation=1., seed=None):
state = None if seed is None else np.random.RandomState(seed)
values = truncnorm.rvs(-2, 2, size=(batch_size, dim_z), random_state=state)
return truncation * values
示例5: fit
# 需要导入模块: from scipy.stats import truncnorm [as 别名]
# 或者: from scipy.stats.truncnorm import rvs [as 别名]
def fit(self, X):
"""
Fit a model given data.
:param X: array-like, shape = (n_samples, n_features)
:return:
"""
# Initialize RBM parameters
self.n_visible_units = X.shape[1]
if self.activation_function == 'sigmoid':
self.W = np.random.randn(self.n_hidden_units, self.n_visible_units) / np.sqrt(self.n_visible_units)
self.c = np.random.randn(self.n_hidden_units) / np.sqrt(self.n_visible_units)
self.b = np.random.randn(self.n_visible_units) / np.sqrt(self.n_visible_units)
self._activation_function_class = SigmoidActivationFunction
elif self.activation_function == 'relu':
self.W = truncnorm.rvs(-0.2, 0.2, size=[self.n_hidden_units, self.n_visible_units]) / np.sqrt(
self.n_visible_units)
self.c = np.full(self.n_hidden_units, 0.1) / np.sqrt(self.n_visible_units)
self.b = np.full(self.n_visible_units, 0.1) / np.sqrt(self.n_visible_units)
self._activation_function_class = ReLUActivationFunction
else:
raise ValueError("Invalid activation function.")
if self.optimization_algorithm == 'sgd':
self._stochastic_gradient_descent(X)
else:
raise ValueError("Invalid optimization algorithm.")
return self
示例6: sample_tgmm
# 需要导入模块: from scipy.stats import truncnorm [as 别名]
# 或者: from scipy.stats.truncnorm import rvs [as 别名]
def sample_tgmm(center, scale, n, xmin, xmax):
'''
Sample from a truncated Gaussian mixture model (TGMM).
Returns the samples and their importance weight.
Args:
center: center of TGMM.
scale: scale of TGMM.
n: number of samples.
xmin: smallest values of the truncated interval.
xmax: largest values of the truncated interval.
'''
dx = len(xmin)
slen = len(center)
rd_centers = np.random.choice(slen, (n))
ta = (xmin - center[rd_centers]) / scale
tb = (xmax - center[rd_centers]) / scale
x_samples_gmm = truncnorm.rvs(ta, tb, loc=center[rd_centers], scale=scale)
ta = (xmin - center) / scale
tb = (xmax - center) / scale
def truncpdf(j,i):
return truncnorm.pdf(x_samples_gmm[:,j], ta[i][j], tb[i][j], center[i][j], scale[j])
prob = [np.prod(map(partial(truncpdf, i=i), range(dx)), axis=0) for i in range(slen)]
prob = np.sum(prob, axis=0) / slen
np.clip(prob, EPS, 1/EPS)
return x_samples_gmm, 1./prob
示例7: truncated_z_sample
# 需要导入模块: from scipy.stats import truncnorm [as 别名]
# 或者: from scipy.stats.truncnorm import rvs [as 别名]
def truncated_z_sample(batch_size, z_dim, truncation=0.5, seed=None):
state = None if seed is None else np.random.RandomState(seed)
values = truncnorm.rvs(-2, 2, size=(batch_size, z_dim), random_state=state)
return truncation * values
示例8: init_weights
# 需要导入模块: from scipy.stats import truncnorm [as 别名]
# 或者: from scipy.stats.truncnorm import rvs [as 别名]
def init_weights(size):
# we truncate the normal distribution at two times the standard deviation (which is 2)
# to account for a smaller variance (but the same mean), we multiply the resulting matrix with he desired std
return np.float32(truncnorm.rvs(-2, 2, size=size)*1.0/math.sqrt(float(size[0])))
开发者ID:SAP-samples,项目名称:machine-learning-diff-private-federated-learning,代码行数:6,代码来源:mnist_inference.py
示例9: rotate_pts
# 需要导入模块: from scipy.stats import truncnorm [as 别名]
# 或者: from scipy.stats.truncnorm import rvs [as 别名]
def rotate_pts(pts, max_angle,sample_type='rvs'):
if sample_type=='rvs':
angle=truncnorm.rvs(-2,2,loc=0,scale=max_angle/2)
elif sample_type=='uniform':
angle=np.random.uniform(-max_angle,max_angle)
else: raise NotImplementedError
rot_m = np.asarray([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]],np.float32)
center=np.mean(pts,0,keepdims=True)
return np.matmul(pts-center,rot_m.transpose())+center
示例10: perspective_pts
# 需要导入模块: from scipy.stats import truncnorm [as 别名]
# 或者: from scipy.stats.truncnorm import rvs [as 别名]
def perspective_pts(pts, h, w, perspective_amplitude=0.2, direction='lr', perspective_short_amplitude=0.2):
displacement = np.random.uniform(-perspective_amplitude,perspective_amplitude) # truncnorm.rvs(-1, 1, loc=0, scale=perspective_amplitude)
ds = np.random.uniform(-perspective_short_amplitude, 0)
if direction=='lr':
displacement*=h
ds*=w
pts += np.asarray([[ds, displacement],[ds, -displacement],[-ds, displacement],[-ds, -displacement]], np.float32)
elif direction=='ud':
displacement*=w
ds*=h
pts += np.asarray([[displacement, ds],[-displacement, -ds],[displacement, -ds], [-displacement, ds]], np.float32)
else: raise NotImplementedError
return pts
示例11: var
# 需要导入模块: from scipy.stats import truncnorm [as 别名]
# 或者: from scipy.stats.truncnorm import rvs [as 别名]
def var(self):
"""
Calculate variance value of the random variable.
:return: variance value of the random variable.
"""
return 0
# TODO: Mixin this or something:
# class DelayedAdditionOf(MalleableDistribution):
# """A HyperparameterDistribution (MalleableDistribution mixin) that """
#
# def __init__(self, *dists):
# self.dists = dists
#
# def rvs(self):
# rvss = [d.rvs if hasattr(d, 'rvs') else d for d in self.dists]
# return sum(rvss)
#
#
# class MalleableDistribution(metaclass=ABCMeta):
# """An hyperparameter distribution to which it's possible to do additional math using defaut python operators."""
#
# def __add__(self, other):
# return DelayedAdditionOf(self, other)
#
# max min + - / * % ** // == != < > <= >=
#
示例12: _sample_from_gmm
# 需要导入模块: from scipy.stats import truncnorm [as 别名]
# 或者: from scipy.stats.truncnorm import rvs [as 别名]
def _sample_from_gmm(
self,
parzen_estimator, # type: _ParzenEstimator
low, # type: float
high, # type: float
q=None, # type: Optional[float]
size=(), # type: Tuple
):
# type: (...) -> np.ndarray
weights = parzen_estimator.weights
mus = parzen_estimator.mus
sigmas = parzen_estimator.sigmas
weights, mus, sigmas = map(np.asarray, (weights, mus, sigmas))
if low >= high:
raise ValueError(
"The 'low' should be lower than the 'high'. "
"But (low, high) = ({}, {}).".format(low, high)
)
active = np.argmax(self._rng.multinomial(1, weights, size=size), axis=-1)
trunc_low = (low - mus[active]) / sigmas[active]
trunc_high = (high - mus[active]) / sigmas[active]
while True:
samples = truncnorm.rvs(
trunc_low,
trunc_high,
size=size,
loc=mus[active],
scale=sigmas[active],
random_state=self._rng,
)
if (samples < high).all():
break
if q is None:
return samples
else:
return np.round(samples / q) * q
示例13: act
# 需要导入模块: from scipy.stats import truncnorm [as 别名]
# 或者: from scipy.stats.truncnorm import rvs [as 别名]
def act(self, qvals):
eps = truncnorm.rvs((0 - self.eps_mean) / self.eps_std, (1 - self.eps_mean) / self.eps_std)
if random.random() > eps:
return np.argmax(qvals)
return random.randrange(len(qvals))
# Continuous action-space policies (noise generators) ==================================================================
示例14: truncated_normal_
# 需要导入模块: from scipy.stats import truncnorm [as 别名]
# 或者: from scipy.stats.truncnorm import rvs [as 别名]
def truncated_normal_(tensor, mean=0.0, std=1.0):
# PT doesn't have truncated normal.
# https://discuss.pytorch.org/t/implementing-truncated-normal-initializer/4778/18
values = truncnorm.rvs(-2, 2, size=tensor.shape)
values = mean + std * values
tensor.copy_(torch.from_numpy(values))
return tensor
示例15: create_scenario
# 需要导入模块: from scipy.stats import truncnorm [as 别名]
# 或者: from scipy.stats.truncnorm import rvs [as 别名]
def create_scenario(self):
scenario = {'meal': {'time': [],
'amount': []}}
# Probability of taking each meal
# [breakfast, snack1, lunch, snack2, dinner, snack3]
prob = [0.95, 0.3, 0.95, 0.3, 0.95, 0.3]
time_lb = np.array([5, 9, 10, 14, 16, 20]) * 60
time_ub = np.array([9, 10, 14, 16, 20, 23]) * 60
time_mu = np.array([7, 9.5, 12, 15, 18, 21.5]) * 60
time_sigma = np.array([60, 30, 60, 30, 60, 30])
amount_mu = [45, 10, 70, 10, 80, 10]
amount_sigma = [10, 5, 10, 5, 10, 5]
for p, tlb, tub, tbar, tsd, mbar, msd in zip(
prob, time_lb, time_ub, time_mu, time_sigma,
amount_mu, amount_sigma):
if self.random_gen.rand() < p:
tmeal = np.round(truncnorm.rvs(a=(tlb - tbar) / tsd,
b=(tub - tbar) / tsd,
loc=tbar,
scale=tsd,
random_state=self.random_gen))
scenario['meal']['time'].append(tmeal)
scenario['meal']['amount'].append(
max(round(self.random_gen.normal(mbar, msd)), 0))
return scenario