本文整理汇总了Python中numpy.nextafter函数的典型用法代码示例。如果您正苦于以下问题:Python nextafter函数的具体用法?Python nextafter怎么用?Python nextafter使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了nextafter函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: make_strictly_feasible
def make_strictly_feasible(x, lb, ub, rstep=1e-10):
"""Shift a point to the interior of a feasible region.
Each element of the returned vector is at least at a relative distance
`rstep` from the closest bound. If ``rstep=0`` then `np.nextafter` is used.
"""
x_new = x.copy()
active = find_active_constraints(x, lb, ub, rstep)
lower_mask = np.equal(active, -1)
upper_mask = np.equal(active, 1)
if rstep == 0:
x_new[lower_mask] = np.nextafter(lb[lower_mask], ub[lower_mask])
x_new[upper_mask] = np.nextafter(ub[upper_mask], lb[upper_mask])
else:
x_new[lower_mask] = (lb[lower_mask] +
rstep * np.maximum(1, np.abs(lb[lower_mask])))
x_new[upper_mask] = (ub[upper_mask] -
rstep * np.maximum(1, np.abs(ub[upper_mask])))
tight_bounds = (x_new < lb) | (x_new > ub)
x_new[tight_bounds] = 0.5 * (lb[tight_bounds] + ub[tight_bounds])
return x_new
开发者ID:MechCoder,项目名称:scipy,代码行数:25,代码来源:common.py
示例2: make_strictly_feasible
def make_strictly_feasible(x, lb, ub, rstep=0):
"""Shift the point in the slightest possible way to the interior.
If ``rstep=0`` the function uses np.nextafter, otherwise `rstep` is
multiplied by absolute value of the bound.
The utility of this function is questionable to me. Maybe bigger shifts
should be used, or maybe this function is not necessary at all despite
theoretical requirement of our interior point algorithm.
"""
x_new = x.copy()
m = x <= lb
if rstep == 0:
x_new[m] = np.nextafter(lb[m], ub[m])
else:
x_new[m] = lb[m] + rstep * (1 + np.abs(lb[m]))
m = x >= ub
if rstep == 0:
x_new[m] = np.nextafter(ub[m], lb[m])
else:
x_new[m] = ub[m] - rstep * (1 + np.abs(ub[m]))
return x_new
开发者ID:shaoguangleo,项目名称:autoFits,代码行数:25,代码来源:bounds.py
示例3: nextafter
def nextafter(x, direction, dtype, itemsize):
"""Return the next representable neighbor of x in the appropriate
direction."""
assert direction in [-1, 0, +1]
assert dtype.kind == "S" or type(x) in (bool, int, int, float)
if direction == 0:
return x
if dtype.kind == "S":
return string_next_after(x, direction, itemsize)
if dtype.kind in ['b']:
return bool_type_next_after(x, direction, itemsize)
elif dtype.kind in ['i', 'u']:
return int_type_next_after(x, direction, itemsize)
elif dtype.kind == "f":
if direction < 0:
return numpy.nextafter(x, x - 1)
else:
return numpy.nextafter(x, x + 1)
# elif dtype.name == "float32":
# if direction < 0:
# return PyNextAfterF(x,x-1)
# else:
# return PyNextAfterF(x,x + 1)
# elif dtype.name == "float64":
# if direction < 0:
# return PyNextAfter(x,x-1)
# else:
# return PyNextAfter(x,x + 1)
raise TypeError("data type ``%s`` is not supported" % dtype)
开发者ID:alfonsodiecko,项目名称:PYTHON_DIST,代码行数:35,代码来源:idxutils.py
示例4: __init__
def __init__(self, value_1, value_2=None):
# use Decimal as exact value holder (because of arbitrary precision)
from decimal import Decimal
# nextafter(x, y) returns next machine number after x in direction of y
from numpy import nextafter
# creating interval from middle value
if not value_2:
exact = Decimal(value_1)
float_repr = Decimal("{0:0.70f}".format(float(exact)))
if exact == float_repr:
self.lv = float(float_repr)
self.rv = float(float_repr)
elif exact > float_repr:
self.lv = float(float_repr)
self.rv = nextafter(self.lv, float('Inf'))
elif exact < float_repr:
self.rv = float(float_repr)
self.lv = nextafter(self.rv, -float('Inf'))
# creating interval from left and right edge
else:
exact_left = Decimal(value_1)
exact_right = Decimal(value_2)
if exact_left > exact_right:
exact_left, exact_right = exact_right, exact_left
float_repr_left = Decimal(float(exact_left))
float_repr_right = Decimal(float(exact_right))
if exact_left < float_repr_left:
self.lv = nextafter(float(float_repr_left), -float('Inf'))
else:
self.lv = float(float_repr_left)
if exact_right > float_repr_right:
self.rv = nextafter(float(float_repr_right), float('Inf'))
else:
self.rv = float(float_repr_right)
开发者ID:cubsoon,项目名称:intervalarithmetic,代码行数:35,代码来源:__init__.py
示例5: _logpmf
def _logpmf(self, x, mu, alpha, p):
mu_p = mu ** (p - 1.)
a1 = np.maximum(np.nextafter(0, 1), 1 + alpha * mu_p)
a2 = np.maximum(np.nextafter(0, 1), mu + (a1 - 1.) * x)
logpmf_ = np.log(mu) + (x - 1.) * np.log(a2)
logpmf_ -= x * np.log(a1) + gammaln(x + 1.) + a2 / a1
return logpmf_
开发者ID:BranYang,项目名称:statsmodels,代码行数:7,代码来源:discrete.py
示例6: test_half_fpe
def test_half_fpe(self):
oldsettings = np.seterr(all="raise")
try:
sx16 = np.array((1e-4,), dtype=float16)
bx16 = np.array((1e4,), dtype=float16)
sy16 = float16(1e-4)
by16 = float16(1e4)
# Underflow errors
assert_raises_fpe("underflow", lambda a, b: a * b, sx16, sx16)
assert_raises_fpe("underflow", lambda a, b: a * b, sx16, sy16)
assert_raises_fpe("underflow", lambda a, b: a * b, sy16, sx16)
assert_raises_fpe("underflow", lambda a, b: a * b, sy16, sy16)
assert_raises_fpe("underflow", lambda a, b: a / b, sx16, bx16)
assert_raises_fpe("underflow", lambda a, b: a / b, sx16, by16)
assert_raises_fpe("underflow", lambda a, b: a / b, sy16, bx16)
assert_raises_fpe("underflow", lambda a, b: a / b, sy16, by16)
assert_raises_fpe("underflow", lambda a, b: a / b, float16(2.0 ** -14), float16(2 ** 11))
assert_raises_fpe("underflow", lambda a, b: a / b, float16(-2.0 ** -14), float16(2 ** 11))
assert_raises_fpe("underflow", lambda a, b: a / b, float16(2.0 ** -14 + 2 ** -24), float16(2))
assert_raises_fpe("underflow", lambda a, b: a / b, float16(-2.0 ** -14 - 2 ** -24), float16(2))
assert_raises_fpe("underflow", lambda a, b: a / b, float16(2.0 ** -14 + 2 ** -23), float16(4))
# Overflow errors
assert_raises_fpe("overflow", lambda a, b: a * b, bx16, bx16)
assert_raises_fpe("overflow", lambda a, b: a * b, bx16, by16)
assert_raises_fpe("overflow", lambda a, b: a * b, by16, bx16)
assert_raises_fpe("overflow", lambda a, b: a * b, by16, by16)
assert_raises_fpe("overflow", lambda a, b: a / b, bx16, sx16)
assert_raises_fpe("overflow", lambda a, b: a / b, bx16, sy16)
assert_raises_fpe("overflow", lambda a, b: a / b, by16, sx16)
assert_raises_fpe("overflow", lambda a, b: a / b, by16, sy16)
assert_raises_fpe("overflow", lambda a, b: a + b, float16(65504), float16(17))
assert_raises_fpe("overflow", lambda a, b: a - b, float16(-65504), float16(17))
assert_raises_fpe("overflow", np.nextafter, float16(65504), float16(np.inf))
assert_raises_fpe("overflow", np.nextafter, float16(-65504), float16(-np.inf))
assert_raises_fpe("overflow", np.spacing, float16(65504))
# Invalid value errors
assert_raises_fpe("invalid", np.divide, float16(np.inf), float16(np.inf))
assert_raises_fpe("invalid", np.spacing, float16(np.inf))
assert_raises_fpe("invalid", np.spacing, float16(np.nan))
assert_raises_fpe("invalid", np.nextafter, float16(np.inf), float16(0))
assert_raises_fpe("invalid", np.nextafter, float16(-np.inf), float16(0))
assert_raises_fpe("invalid", np.nextafter, float16(0), float16(np.nan))
# These should not raise
float16(65472) + float16(32)
float16(2 ** -13) / float16(2)
float16(2 ** -14) / float16(2 ** 10)
np.spacing(float16(-65504))
np.nextafter(float16(65504), float16(-np.inf))
np.nextafter(float16(-65504), float16(np.inf))
float16(2 ** -14) / float16(2 ** 10)
float16(-2 ** -14) / float16(2 ** 10)
float16(2 ** -14 + 2 ** -23) / float16(2)
float16(-2 ** -14 - 2 ** -23) / float16(2)
finally:
np.seterr(**oldsettings)
开发者ID:MrBago,项目名称:numpy,代码行数:59,代码来源:test_half.py
示例7: forward_cpu
def forward_cpu(self, inputs):
U, points = inputs
batch_size, height, width = U.shape
# Points just on the boundary are slightly (i.e. nextafter in float32)
# moved inward to simplify the implementation
points = points.copy()
on_boundary = (points == 0)
points[on_boundary] = np.nextafter(points[on_boundary], np.float32(1))
x = points[:, 0]
y = points[:, 1]
on_boundary = (x == (width - 1))
x[on_boundary] = np.nextafter(x[on_boundary], np.float32(0))
on_boundary = (y == (height - 1))
y[on_boundary] = np.nextafter(y[on_boundary], np.float32(0))
batch_axis = np.expand_dims(np.arange(batch_size), 1)
points_floor = np.floor(points)
x_l = points_floor[:, 0].astype(np.int32)
y_l = points_floor[:, 1].astype(np.int32)
x_l = np.clip(x_l, 0, width - 1)
y_l = np.clip(y_l, 0, height - 1)
x_h = np.clip(x_l + 1, 0, width - 1)
y_h = np.clip(y_l + 1, 0, height - 1)
weight = 1.0 - (points - points_floor)
weight_x_l = weight[:, 0]
weight_y_l = weight[:, 1]
weight_x_h = 1 - weight_x_l
weight_y_h = 1 - weight_y_l
# remove points outside of the (source) image region
# by setting their weights to 0
x_invalid = np.logical_or(x < 0, (width - 1) < x)
y_invalid = np.logical_or(y < 0, (height - 1) < y)
invalid = np.logical_or(x_invalid, y_invalid)
weight_x_l[invalid] = 0
weight_y_l[invalid] = 0
weight_x_h[invalid] = 0
weight_y_h[invalid] = 0
U_y_l = (weight_x_l * U[batch_axis, y_l, x_l] +
weight_x_h * U[batch_axis, y_l, x_h])
U_y_h = (weight_x_l * U[batch_axis, y_h, x_l] +
weight_x_h * U[batch_axis, y_h, x_h])
V = weight_y_l * U_y_l + weight_y_h * U_y_h
self.x_l = x_l
self.y_l = y_l
self.x_h = x_h
self.y_h = y_h
self.weight_x_l = weight_x_l
self.weight_y_l = weight_y_l
self.weight_x_h = weight_x_h
self.weight_y_h = weight_y_h
return (V,)
开发者ID:ronekko,项目名称:spatial_transformer_network,代码行数:56,代码来源:spatial_transformer_network.py
示例8: _test_nextafter
def _test_nextafter(t):
one = t(1)
two = t(2)
zero = t(0)
eps = np.finfo(t).eps
assert_(np.nextafter(one, two) - one == eps)
assert_(np.nextafter(one, zero) - one < 0)
assert_(np.isnan(np.nextafter(np.nan, one)))
assert_(np.isnan(np.nextafter(one, np.nan)))
assert_(np.nextafter(one, one) == one)
开发者ID:jarrodmillman,项目名称:numpy,代码行数:10,代码来源:test_umath.py
示例9: test_nextafter
def test_nextafter():
for t in [np.float32, np.float64, np.longdouble]:
one = t(1)
two = t(2)
zero = t(0)
eps = np.finfo(t).eps
assert np.nextafter(one, two) - one == eps
assert np.nextafter(one, zero) - one < 0
assert np.isnan(np.nextafter(np.nan, one))
assert np.isnan(np.nextafter(one, np.nan))
assert np.nextafter(one, one) == one
开发者ID:plaes,项目名称:numpy,代码行数:11,代码来源:test_umath.py
示例10: ranges_to_weight_table
def ranges_to_weight_table(ranges):
"""
Create a table of weights from ranges. Include only edge points of ranges.
Include each edge point twice: once as values within the range and zero
value outside the range (with this output the weights can easily be interpolated).
Weights of overlapping intervals are summed.
Assumes 64-bit floats.
:param ranges: list of triples (edge1, edge2, weight)
:return: an Orange.data.Table
"""
values = {}
inf = float("inf")
minf = float("-inf")
def dict_to_numpy(d):
x = []
y = []
for a, b in d.items():
x.append(a)
y.append(b)
return np.array(x), np.array([y])
for l, r, w in ranges:
l, r = min(l, r), max(l, r)
positions = [nextafter(l, minf), l, r, nextafter(r, inf)]
weights = [0., float(w), float(w), 0.]
all_positions = list(set(positions) | set(values)) # new and old positions
# current values on all position
x, y = dict_to_numpy(values)
current = interp1d_with_unknowns_numpy(x, y, all_positions)[0]
current[np.isnan(current)] = 0
# new values on all positions
new = interp1d_with_unknowns_numpy(np.array(positions), np.array([weights]),
all_positions)[0]
new[np.isnan(new)] = 0
# update values
for p, f in zip(all_positions, current + new):
values[p] = f
x, y = dict_to_numpy(values)
dom = Orange.data.Domain([Orange.data.ContinuousVariable(name=str(float(a))) for a in x])
data = Orange.data.Table.from_numpy(dom, y)
return data
开发者ID:stuart-cls,项目名称:orange-infrared,代码行数:52,代码来源:emsc.py
示例11: test_half_conversion_rounding
def test_half_conversion_rounding(self, float_t, shift, offset):
# Assumes that round to even is used during casting.
max_pattern = np.float16(np.finfo(np.float16).max).view(np.uint16)
# Test all (positive) finite numbers, denormals are most interesting
# however:
f16s_patterns = np.arange(0, max_pattern+1, dtype=np.uint16)
f16s_float = f16s_patterns.view(np.float16).astype(float_t)
# Shift the values by half a bit up or a down (or do not shift),
if shift == "up":
f16s_float = 0.5 * (f16s_float[:-1] + f16s_float[1:])[1:]
elif shift == "down":
f16s_float = 0.5 * (f16s_float[:-1] + f16s_float[1:])[:-1]
else:
f16s_float = f16s_float[1:-1]
# Increase the float by a minimal value:
if offset == "up":
f16s_float = np.nextafter(f16s_float, float_t(1e50))
elif offset == "down":
f16s_float = np.nextafter(f16s_float, float_t(-1e50))
# Convert back to float16 and its bit pattern:
res_patterns = f16s_float.astype(np.float16).view(np.uint16)
# The above calculations tries the original values, or the exact
# mid points between the float16 values. It then further offsets them
# by as little as possible. If no offset occurs, "round to even"
# logic will be necessary, an arbitrarily small offset should cause
# normal up/down rounding always.
# Calculate the expecte pattern:
cmp_patterns = f16s_patterns[1:-1].copy()
if shift == "down" and offset != "up":
shift_pattern = -1
elif shift == "up" and offset != "down":
shift_pattern = 1
else:
# There cannot be a shift, either shift is None, so all rounding
# will go back to original, or shift is reduced by offset too much.
shift_pattern = 0
# If rounding occurs, is it normal rounding or round to even?
if offset is None:
# Round to even occurs, modify only non-even, cast to allow + (-1)
cmp_patterns[0::2].view(np.int16)[...] += shift_pattern
else:
cmp_patterns.view(np.int16)[...] += shift_pattern
assert_equal(res_patterns, cmp_patterns)
开发者ID:Horta,项目名称:numpy,代码行数:52,代码来源:test_half.py
示例12: compute_likelihoods
def compute_likelihoods(self, PLCs, FLCs):
K = self.K()
N = self.N()
future_given_state_probs = np.nextafter(self.f_hat_conditional_densities(FLCs, label="PDF_FLCs"), 1.)
state_given_past_probs = np.nextafter(np.vstack([self.PLC_densities(j, PLCs) for j in range(K)]), 1.).T
''' Weight by state likelihood '''
n_hats = self.W.sum(axis=0) / N
state_given_past_probs *= n_hats
state_given_past_probs = np.nextafter(state_given_past_probs, 1.)
''' Normalize '''
state_given_past_probs /= np.expand_dims(np.sum(state_given_past_probs, axis=1), axis=1)
''' Return mixed likelihoods '''
return np.nextafter(np.sum(np.multiply(state_given_past_probs, future_given_state_probs), axis=1), 1.)
开发者ID:george-montanez,项目名称:pyMixedLICORS,代码行数:13,代码来源:MixedLICORS.py
示例13: testBearingToValueOnEquator
def testBearingToValueOnEquator(self):
"""Test if bearingTo() returns the expected value from a point on the equator
"""
lon0 = 90.0
lat0 = 0.0 # These tests only work from the equator.
arcLen = 10.0
trials = [
# Along celestial equator
dict(lon=lon0, lat=lat0, bearing=0.0,
lonEnd=lon0+arcLen, latEnd=lat0),
# Along a meridian
dict(lon=lon0, lat=lat0, bearing=90.0,
lonEnd=lon0, latEnd=lat0+arcLen),
# 180 degree arc (should go to antipodal point)
dict(lon=lon0, lat=lat0, bearing=45.0,
lonEnd=lon0+180.0, latEnd=-lat0),
#
dict(lon=lon0, lat=lat0, bearing=45.0,
lonEnd=lon0+90.0, latEnd=lat0 + 45.0),
dict(lon=lon0, lat=lat0, bearing=225.0,
lonEnd=lon0-90.0, latEnd=lat0 - 45.0),
dict(lon=lon0, lat=np.nextafter(-90.0, inf),
bearing=90.0, lonEnd=lon0, latEnd=0.0),
dict(lon=lon0, lat=np.nextafter(-90.0, inf),
bearing=0.0, lonEnd=lon0 + 90.0, latEnd=0.0),
# Argument at a pole should work
dict(lon=lon0, lat=lat0, bearing=270.0, lonEnd=lon0, latEnd=-90.0),
# Support for non-finite values
dict(lon=lon0, lat=nan, bearing=nan, lonEnd=lon0, latEnd=45.0),
dict(lon=lon0, lat=lat0, bearing=nan, lonEnd=nan, latEnd=90.0),
dict(lon=inf, lat=lat0, bearing=nan, lonEnd=lon0, latEnd=42.0),
dict(lon=lon0, lat=lat0, bearing=nan, lonEnd=-inf, latEnd=42.0),
]
for trial in trials:
origin = SpherePoint(trial['lon']*degrees, trial['lat']*degrees)
end = SpherePoint(trial['lonEnd']*degrees, trial['latEnd']*degrees)
bearing = origin.bearingTo(end)
self.assertIsInstance(bearing, geom.Angle)
if origin.isFinite() and end.isFinite():
self.assertGreaterEqual(bearing.asDegrees(), 0.0)
self.assertLess(bearing.asDegrees(), 360.0)
if origin.separation(end).asDegrees() != 180.0:
if not math.isnan(trial['bearing']):
self.assertAlmostEqual(
trial['bearing'], bearing.asDegrees(), 12)
else:
self.assertTrue(math.isnan(bearing.asRadians()))
开发者ID:HyperSuprime-Cam,项目名称:geom,代码行数:50,代码来源:test_spherePoint.py
示例14: similarity
def similarity(v1, v2):
# v1 and v2 are vectors
eps = np.nextafter(0, 1) # smallest float above zero
dot = np.dot(v1, v2)
dot /= max(npext.norm(v1), eps)
dot /= max(npext.norm(v2), eps)
return dot
开发者ID:tbekolay,项目名称:phd,代码行数:7,代码来源:idmp.py
示例15: _compute_lwork
def _compute_lwork(routine, *args, **kwargs):
"""
Round floating-point lwork returned by lapack to integer.
Several LAPACK routines compute optimal values for LWORK, which
they return in a floating-point variable. However, for large
values of LWORK, single-precision floating point is not sufficient
to hold the exact value --- some LAPACK versions (<= 3.5.0 at
least) truncate the returned integer to single precision and in
some cases this can be smaller than the required value.
"""
wi = routine(*args, **kwargs)
if len(wi) < 2:
raise ValueError("")
info = wi[-1]
if info != 0:
raise ValueError("Internal work array size computation failed: " "%d" % (info,))
lwork = [w.real for w in wi[:-1]]
dtype = getattr(routine, "dtype", None)
if dtype == _np.float32 or dtype == _np.complex64:
# Single-precision routine -- take next fp value to work
# around possible truncation in LAPACK code
lwork = _np.nextafter(lwork, _np.inf, dtype=_np.float32)
lwork = _np.array(lwork, _np.int64)
if _np.any(_np.logical_or(lwork < 0, lwork > _np.iinfo(_np.int32).max)):
raise ValueError(
"Too large work array required -- computation cannot " "be performed with standard 32-bit LAPACK."
)
lwork = lwork.astype(_np.int32)
if lwork.size == 1:
return lwork[0]
return lwork
开发者ID:ionelberdin,项目名称:scipy,代码行数:35,代码来源:lapack.py
示例16: sample_n
def sample_n(self, n, seed=None, name="sample_n"):
"""Sample `n` observations from the Exponential Distributions.
Args:
n: `Scalar`, type int32, the number of observations to sample.
seed: Python integer, the random seed.
name: The name to give this op.
Returns:
samples: `[n, ...]`, a `Tensor` of `n` samples for each
of the distributions determined by the hyperparameters.
"""
broadcast_shape = self._lam.get_shape()
with ops.op_scope([self.lam, n], name, "ExponentialSample"):
n = ops.convert_to_tensor(n, name="n")
shape = array_ops.concat(
0, [array_ops.pack([n]), array_ops.shape(self._lam)])
# Sample uniformly-at-random from the open-interval (0, 1).
sampled = random_ops.random_uniform(
shape, minval=np.nextafter(
self.dtype.as_numpy_dtype(0.), self.dtype.as_numpy_dtype(1.)),
maxval=constant_op.constant(1.0, dtype=self.dtype),
seed=seed,
dtype=self.dtype)
n_val = tensor_util.constant_value(n)
final_shape = tensor_shape.vector(n_val).concatenate(broadcast_shape)
sampled.set_shape(final_shape)
return -math_ops.log(sampled) / self._lam
开发者ID:2020zyc,项目名称:tensorflow,代码行数:30,代码来源:exponential.py
示例17: test_to_corr
def test_to_corr(self):
# Check some corner cases in to_corr
# ajj == 1
m = np.array([[0.1, 0], [0, 1]], dtype=float)
m = random_correlation._to_corr(m)
assert_allclose(m, np.array([[1, 0], [0, 0.1]]))
# Floating point overflow; fails to compute the correct
# rotation, but should still produce some valid rotation
# rather than infs/nans
with np.errstate(over='ignore'):
g = np.array([[0, 1], [-1, 0]])
m0 = np.array([[1e300, 0], [0, np.nextafter(1, 0)]], dtype=float)
m = random_correlation._to_corr(m0.copy())
assert_allclose(m, g.T.dot(m0).dot(g))
m0 = np.array([[0.9, 1e300], [1e300, 1.1]], dtype=float)
m = random_correlation._to_corr(m0.copy())
assert_allclose(m, g.T.dot(m0).dot(g))
# Zero discriminant; should set the first diag entry to 1
m0 = np.array([[2, 1], [1, 2]], dtype=float)
m = random_correlation._to_corr(m0.copy())
assert_allclose(m[0,0], 1)
# Slightly negative discriminant; should be approx correct still
m0 = np.array([[2 + 1e-7, 1], [1, 2]], dtype=float)
m = random_correlation._to_corr(m0.copy())
assert_allclose(m[0,0], 1)
开发者ID:AlgorithmFan,项目名称:scipy,代码行数:31,代码来源:test_multivariate.py
示例18: sample_n
def sample_n(self, n, seed=None, name="sample_n"):
"""Sample `n` observations from the Laplace Distributions.
Args:
n: `Scalar`, type int32, the number of observations to sample.
seed: Python integer, the random seed.
name: The name to give this op.
Returns:
samples: `[n, ...]`, a `Tensor` of `n` samples for each
of the distributions determined by broadcasting the parameters.
"""
with ops.name_scope(self.name):
with ops.name_scope(name, values=[self._loc, self._scale, n]):
n = ops.convert_to_tensor(n)
n_val = tensor_util.constant_value(n)
shape = array_ops.concat(0, ([n], self.batch_shape()))
# Sample uniformly-at-random from the open-interval (-1, 1).
uniform_samples = random_ops.random_uniform(
shape=shape,
minval=np.nextafter(self.dtype.as_numpy_dtype(-1.),
self.dtype.as_numpy_dtype(0.)),
maxval=self.dtype.as_numpy_dtype(1.),
dtype=self.dtype,
seed=seed)
# Provide some hints to shape inference
inferred_shape = tensor_shape.vector(n_val).concatenate(
self.get_batch_shape())
uniform_samples.set_shape(inferred_shape)
return (self._loc - self._scale * math_ops.sign(uniform_samples) *
math_ops.log(1. - math_ops.abs(uniform_samples)))
开发者ID:alephman,项目名称:Tensorflow,代码行数:33,代码来源:laplace.py
示例19: _addMinMaxToStyle
def _addMinMaxToStyle(theStyle):
"""Add a min and max to each style class in a style dictionary.
When InaSAFE provides style classes they are specific values, not ranges.
However QGIS wants to work in ranges, so this helper will address that by
updating the dictionary to include a min max value for each class.
It is assumed that we will start for 0 as the min for the first class
and the quantity of each class shall constitute the max. For all other
classes , min shall constitute the smalles increment to a float that can
meaningfully be made by python (as determined by numpy.nextafter()).
Args:
style: list - A list of dictionaries of the form as in the example
below.
Returns:
dict: A new dictionary list with min max attributes added to each
entry.
Example input:
style_classes = [dict(colour='#38A800', quantity=2, transparency=0),
dict(colour='#38A800', quantity=5, transparency=50),
dict(colour='#79C900', quantity=10, transparency=50),
dict(colour='#CEED00', quantity=20, transparency=50),
dict(colour='#FFCC00', quantity=50, transparency=34),
dict(colour='#FF6600', quantity=100, transparency=77),
dict(colour='#FF0000', quantity=200, transparency=24),
dict(colour='#7A0000', quantity=300, transparency=22)]
Example output:
style_classes = [dict(colour='#38A800', quantity=2, transparency=0,
min=0, max=2),
dict(colour='#38A800', quantity=5, transparency=50,
min=2.0000000000002, max=5),
),
dict(colour='#79C900', quantity=10, transparency=50,
min=5.0000000000002, max=10),),
dict(colour='#CEED00', quantity=20, transparency=50,
min=5.0000000000002, max=20),),
dict(colour='#FFCC00', quantity=50, transparency=34,
min=20.0000000000002, max=50),),
dict(colour='#FF6600', quantity=100, transparency=77,
min=50.0000000000002, max=100),),
dict(colour='#FF0000', quantity=200, transparency=24,
min=100.0000000000002, max=200),),
dict(colour='#7A0000', quantity=300, transparency=22,
min=200.0000000000002, max=300),)]
"""
myNewStyles = []
myLastMax = 0.0
for myClass in theStyle:
myQuantity = float(myClass['quantity'])
myClass['min'] = myLastMax
myClass['max'] = myQuantity
myLastMax = numpy.nextafter(myQuantity, sys.float_info.max)
myNewStyles.append(myClass)
return myNewStyles
开发者ID:imadedikyadehermawan,项目名称:inasafe,代码行数:60,代码来源:utilities.py
示例20: _sample_n
def _sample_n(self, n, seed=None):
shape = array_ops.concat(0, ([n], array_ops.shape(self.mean())))
np_dtype = self.dtype.as_numpy_dtype()
minval = np.nextafter(np_dtype(0), np_dtype(1))
uniform = random_ops.random_uniform(shape=shape, minval=minval, maxval=1, dtype=self.dtype, seed=seed)
sampled = -math_ops.log(-math_ops.log(uniform))
return sampled * self.scale + self.loc
开发者ID:ppwwyyxx,项目名称:tensorflow,代码行数:7,代码来源:gumbel.py
注:本文中的numpy.nextafter函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论