本文整理汇总了Python中numpy.logaddexp方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.logaddexp方法的具体用法?Python numpy.logaddexp怎么用?Python numpy.logaddexp使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.logaddexp方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_NotImplemented_not_returned
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import logaddexp [as 别名]
def test_NotImplemented_not_returned(self):
# See gh-5964 and gh-2091. Some of these functions are not operator
# related and were fixed for other reasons in the past.
binary_funcs = [
np.power, np.add, np.subtract, np.multiply, np.divide,
np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
np.logical_and, np.logical_or, np.logical_xor, np.maximum,
np.minimum, np.mod,
np.greater, np.greater_equal, np.less, np.less_equal,
np.equal, np.not_equal]
a = np.array('1')
b = 1
c = np.array([1., 2.])
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
assert_raises(TypeError, f, c, a)
示例2: test_NotImplemented_not_returned
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import logaddexp [as 别名]
def test_NotImplemented_not_returned(self):
# See gh-5964 and gh-2091. Some of these functions are not operator
# related and were fixed for other reasons in the past.
binary_funcs = [
np.power, np.add, np.subtract, np.multiply, np.divide,
np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
np.logical_and, np.logical_or, np.logical_xor, np.maximum,
np.minimum, np.mod
]
# These functions still return NotImplemented. Will be fixed in
# future.
# bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]
a = np.array('1')
b = 1
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
示例3: _parallel_predict_log_proba
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import logaddexp [as 别名]
def _parallel_predict_log_proba(estimators, estimators_features, X, n_classes):
"""Private function used to compute log probabilities within a job."""
n_samples = X.shape[0]
log_proba = np.empty((n_samples, n_classes))
log_proba.fill(-np.inf)
all_classes = np.arange(n_classes, dtype=np.int)
for estimator, features in zip(estimators, estimators_features):
log_proba_estimator = estimator.predict_log_proba(X[:, features])
if n_classes == len(estimator.classes_):
log_proba = np.logaddexp(log_proba, log_proba_estimator)
else:
log_proba[:, estimator.classes_] = np.logaddexp(
log_proba[:, estimator.classes_],
log_proba_estimator[:, range(len(estimator.classes_))])
missing = np.setdiff1d(all_classes, estimator.classes_)
log_proba[:, missing] = np.logaddexp(log_proba[:, missing],
-np.inf)
return log_proba
示例4: __call__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import logaddexp [as 别名]
def __call__(self, y, raw_predictions, sample_weight=None):
"""Compute the deviance (= 2 * negative log-likelihood).
Parameters
----------
y : 1d array, shape (n_samples,)
True labels.
raw_predictions : 2d array, shape (n_samples, K)
The raw predictions (i.e. values from the tree leaves) of the
tree ensemble.
sample_weight : 1d array , shape (n_samples,), optional
Sample weights.
"""
# logaddexp(0, v) == log(1.0 + exp(v))
raw_predictions = raw_predictions.ravel()
if sample_weight is None:
return -2 * np.mean((y * raw_predictions) -
np.logaddexp(0, raw_predictions))
else:
return (-2 / sample_weight.sum() * np.sum(
sample_weight * ((y * raw_predictions) -
np.logaddexp(0, raw_predictions))))
示例5: __call__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import logaddexp [as 别名]
def __call__(self, y, pred, sample_weight=None):
"""Compute the deviance (= 2 * negative log-likelihood).
Parameters
----------
y : array, shape (n_samples,)
True labels
pred : array, shape (n_samples,)
Predicted labels
sample_weight : array-like, shape (n_samples,), optional
Sample weights.
"""
# logaddexp(0, v) == log(1.0 + exp(v))
pred = pred.ravel()
if sample_weight is None:
return -2.0 * np.mean((y * pred) - np.logaddexp(0.0, pred))
else:
return (-2.0 / sample_weight.sum() *
np.sum(sample_weight * ((y * pred) - np.logaddexp(0.0, pred))))
示例6: get_collision_force
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import logaddexp [as 别名]
def get_collision_force(self, entity_a, entity_b):
if (not entity_a.collide) or (not entity_b.collide):
return [None, None] # not a collider
if (entity_a is entity_b):
return [None, None] # don't collide against itself
# compute actual distance between entities
delta_pos = entity_a.state.p_pos - entity_b.state.p_pos
dist = np.sqrt(np.sum(np.square(delta_pos)))
# minimum allowable distance
dist_min = entity_a.size + entity_b.size
# softmax penetration
k = self.contact_margin
penetration = np.logaddexp(0, -(dist - dist_min)/k)*k
force = self.contact_force * delta_pos / dist * penetration
force_a = +force if entity_a.movable else None
force_b = -force if entity_b.movable else None
return [force_a, force_b]
示例7: expected_forward_without_reduce
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import logaddexp [as 别名]
def expected_forward_without_reduce(self, x_data, t_data, class_weight):
x = numpy.rollaxis(x_data, 1, x_data.ndim).reshape(
(t_data.size, x_data.shape[1]))
t = t_data.ravel()
loss_shape = x_data.shape[0:1] + x_data.shape[2:]
loss_expect = numpy.zeros(loss_shape, x_data.dtype)
for i, (ti, loss_idx) in enumerate(zip(t, numpy.ndindex(*loss_shape))):
xi = x[i]
if ti == -1:
continue
log_z = numpy.ufunc.reduce(numpy.logaddexp, xi)
if class_weight is None:
loss_expect[loss_idx] = -(xi - log_z)[ti]
else:
loss_expect[loss_idx] = -(xi - log_z)[ti] * class_weight[ti]
return numpy.asarray(loss_expect, dtype=x.dtype)
示例8: sample_from_logprobabilities
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import logaddexp [as 别名]
def sample_from_logprobabilities(log_probabilities, size=1, rst=None):
""" Sample from log probabilities (robust to many bins and small probabilities).
+-np.inf and np.nan will be interpreted as zero probability
"""
if rst is None:
rst = np.random
log_probabilities = np.asarray(log_probabilities)
valid_indices = np.nonzero(np.isfinite(log_probabilities))[0]
valid_log_probabilities = log_probabilities[valid_indices]
ndxs = valid_log_probabilities.argsort()
sorted_log_probabilities = valid_log_probabilities[ndxs]
cumsums = np.logaddexp.accumulate(sorted_log_probabilities)
cumsums -= cumsums[-1]
tmps = -rst.exponential(size=size)
js = np.searchsorted(cumsums, tmps)
valid_values = ndxs[js]
values = valid_indices[valid_values]
return values
示例9: sigmoid
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import logaddexp [as 别名]
def sigmoid(self, a): #numerically stable sigmoid function
return math.exp(-np.logaddexp(0, -a)) -0.5 #compresses values from 0 to 1 and is reduced by 0.5 to get between -1/2 and 1/2
示例10: ctc_loss
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import logaddexp [as 别名]
def ctc_loss(label, prob, remainder, seq_length, batch_size, num_gpu=1, big_num=1e10):
label_ = [0, 0]
prob[prob < 1 / big_num] = 1 / big_num
log_prob = np.log(prob)
l = len(label)
for i in range(l):
label_.append(int(label[i]))
label_.append(0)
l_ = 2 * l + 1
a = np.full((seq_length, l_ + 1), -big_num)
a[0][1] = log_prob[remainder][0]
a[0][2] = log_prob[remainder][label_[2]]
for i in range(1, seq_length):
row = i * int(batch_size / num_gpu) + remainder
a[i][1] = a[i - 1][1] + log_prob[row][0]
a[i][2] = np.logaddexp(a[i - 1][2], a[i - 1][1]) + log_prob[row][label_[2]]
for j in range(3, l_ + 1):
a[i][j] = np.logaddexp(a[i - 1][j], a[i - 1][j - 1])
if label_[j] != 0 and label_[j] != label_[j - 2]:
a[i][j] = np.logaddexp(a[i][j], a[i - 1][j - 2])
a[i][j] += log_prob[row][label_[j]]
return -np.logaddexp(a[seq_length - 1][l_], a[seq_length - 1][l_ - 1])
# label is done with remove_blank
# pred is got from pred_best
示例11: full_compute
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import logaddexp [as 别名]
def full_compute(self, g, r_prev):
'''Given prefix g, return the probability of all possible sequence y (where y = concat(g,c))
This function computes all possible tokens for c (memory inefficient)'''
prefix_length = len(g)
last_char = g[-1] if prefix_length > 0 else 0
# init. r
r = np.full((self.input_length, 2, self.odim),
self.logzero, dtype=np.float32)
# start from len(g) because is impossible for CTC to generate |y|>|X|
start = max(1, prefix_length)
if prefix_length == 0:
r[0, 0, :] = self.x[0, :] # if g = <sos>
psi = r[start-1, 0, :]
phi = np.logaddexp(r_prev[:, 0], r_prev[:, 1])
for t in range(start, self.input_length):
# prev_blank
prev_blank = np.full((self.odim), r_prev[t-1, 1], dtype=np.float32)
# prev_nonblank
prev_nonblank = np.full(
(self.odim), r_prev[t-1, 0], dtype=np.float32)
prev_nonblank[last_char] = self.logzero
phi = np.logaddexp(prev_nonblank, prev_blank)
# P(h|current step is non-blank) = [ P(prev. step = y) + P()]*P(c)
r[t, 0, :] = np.logaddexp(r[t-1, 0, :], phi) + self.x[t, :]
# P(h|current step is blank) = [P(prev. step is blank) + P(prev. step is non-blank)]*P(now=blank)
r[t, 1, :] = np.logaddexp(
r[t-1, 1, :], r[t-1, 0, :]) + self.x[t, self.blank]
psi = np.logaddexp(psi, phi+self.x[t, :])
#psi[self.eos] = np.logaddexp(r_prev[-1,0], r_prev[-1,1])
return psi, np.rollaxis(r, 2)
示例12: cheap_compute
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import logaddexp [as 别名]
def cheap_compute(self, g, r_prev, candidates):
'''Given prefix g, return the probability of all possible sequence y (where y = concat(g,c))
This function considers only those tokens in candidates for c (memory efficient)'''
prefix_length = len(g)
odim = len(candidates)
last_char = g[-1] if prefix_length > 0 else 0
# init. r
r = np.full((self.input_length, 2, len(candidates)),
self.logzero, dtype=np.float32)
# start from len(g) because is impossible for CTC to generate |y|>|X|
start = max(1, prefix_length)
if prefix_length == 0:
r[0, 0, :] = self.x[0, candidates] # if g = <sos>
psi = r[start-1, 0, :]
# Phi = (prev_nonblank,prev_blank)
sum_prev = np.logaddexp(r_prev[:, 0], r_prev[:, 1])
phi = np.repeat(sum_prev[..., None],odim,axis=-1)
# Handle edge case : last tok of prefix in candidates
if prefix_length>0 and last_char in candidates:
phi[:,candidates.index(last_char)] = r_prev[:,1]
for t in range(start, self.input_length):
# prev_blank
# prev_blank = np.full((odim), r_prev[t-1, 1], dtype=np.float32)
# prev_nonblank
# prev_nonblank = np.full((odim), r_prev[t-1, 0], dtype=np.float32)
# phi = np.logaddexp(prev_nonblank, prev_blank)
# P(h|current step is non-blank) = P(prev. step = y)*P(c)
r[t, 0, :] = np.logaddexp( r[t-1, 0, :], phi[t-1]) + self.x[t, candidates]
# P(h|current step is blank) = [P(prev. step is blank) + P(prev. step is non-blank)]*P(now=blank)
r[t, 1, :] = np.logaddexp( r[t-1, 1, :], r[t-1, 0, :]) + self.x[t, self.blank]
psi = np.logaddexp(psi, phi[t-1,]+self.x[t, candidates])
# P(end of sentence) = P(g)
if self.eos in candidates:
psi[candidates.index(self.eos)] = sum_prev[-1]
return psi, np.rollaxis(r, 2)
示例13: test_logaddexp_values
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import logaddexp [as 别名]
def test_logaddexp_values(self):
x = [1, 2, 3, 4, 5]
y = [5, 4, 3, 2, 1]
z = [6, 6, 6, 6, 6]
for dt, dec_ in zip(['f', 'd', 'g'], [6, 15, 15]):
xf = np.log(np.array(x, dtype=dt))
yf = np.log(np.array(y, dtype=dt))
zf = np.log(np.array(z, dtype=dt))
assert_almost_equal(np.logaddexp(xf, yf), zf, decimal=dec_)
示例14: test_logaddexp_range
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import logaddexp [as 别名]
def test_logaddexp_range(self):
x = [1000000, -1000000, 1000200, -1000200]
y = [1000200, -1000200, 1000000, -1000000]
z = [1000200, -1000000, 1000200, -1000000]
for dt in ['f', 'd', 'g']:
logxf = np.array(x, dtype=dt)
logyf = np.array(y, dtype=dt)
logzf = np.array(z, dtype=dt)
assert_almost_equal(np.logaddexp(logxf, logyf), logzf)
示例15: test_inf
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import logaddexp [as 别名]
def test_inf(self):
inf = np.inf
x = [inf, -inf, inf, -inf, inf, 1, -inf, 1]
y = [inf, inf, -inf, -inf, 1, inf, 1, -inf]
z = [inf, inf, inf, -inf, inf, inf, 1, 1]
with np.errstate(invalid='raise'):
for dt in ['f', 'd', 'g']:
logxf = np.array(x, dtype=dt)
logyf = np.array(y, dtype=dt)
logzf = np.array(z, dtype=dt)
assert_equal(np.logaddexp(logxf, logyf), logzf)