def isinfinite(variable):
import math
return bool(math.isfinite(variable))
# Find The Length Of A Value
python类isfinite()的实例源码
def decode(self, words, pos_seq): # <<<<<<>>>>>>
dy.renew_cg()
init_conf = \
Configuration.construct_init_configuration(
words, pos_seq, self.params, self.action_storage, self.all_s2i)
current_beam = [init_conf]
best_finished_conf = None
best_finished_conf_log_prob = -float('inf')
while not self.whole_beam_finished(current_beam):
options = []
for c in current_beam:
if c.is_final_configuration():
if best_finished_conf_log_prob < c.log_prob.value():
best_finished_conf = c
best_finished_conf_log_prob = c.log_prob.value()
else:
log_probs = c.action_log_probabilities().npvalue()
for i in range(len(log_probs)):
if isfinite(log_probs[i]) and log_probs[i] > best_finished_conf_log_prob:
options.append((c, i, c.log_prob.value()+log_probs[i]))
kbest_options = heapq.nlargest(self.beam_size, options, key=lambda x:x[2])
new_beam = []
for c, t, _ in kbest_options:
new_beam.append(c.transition(t))
current_beam = new_beam
for c in current_beam:
if best_finished_conf_log_prob < c.log_prob.value():
best_finished_conf = c
best_finished_conf_log_prob = c.log_prob.value()
tree = best_finished_conf.stack.top()
if tree.label != "root":
pro_index = self.action_storage.get_pro_index_for_string_label("root")
best_finished_conf = best_finished_conf.transition(pro_index)
tree = best_finished_conf.stack.top()
return best_finished_conf, tree
def test_one():
from math import sin, cos, tan, asin, acos, atan
from math import sinh, cosh, tanh, asinh, acosh, atanh
from math import exp, expm1, log, log10, log1p, sqrt, lgamma
from math import fabs, ceil, floor, trunc, erf, erfc
try:
from math import log2
except ImportError:
def log2(x):
return log(x) / log(2)
def wrapper(f, v):
try:
return f(v)
except ValueError:
if f == sqrt:
return float('nan')
if v >= 0:
return float('inf')
else:
return -float('inf')
def compare(a, b):
if isfinite(a) and isfinite(b):
return assert_almost_equals(a, b)
return str(a) == str(b)
for f in [sin, cos, tan, asin, acos, atan,
sinh, cosh, tanh, asinh, acosh, atanh,
exp, expm1, log, log2, log10, log1p, sqrt,
lgamma,
fabs, ceil, floor, trunc,
erf, erfc]:
for p in [0.5, 1]:
a = random_lst(p=p)
b = SparseArray.fromlist(a)
c = getattr(b, f.__name__)()
res = [wrapper(f, x) for x in a]
index = [k for k, v in enumerate(res) if v != 0]
res = [x for x in res if x != 0]
print(f, p, c.non_zero, len(res))
assert c.non_zero == len(res)
[assert_almost_equals(v, w) for v, w in zip(index,
c.index)]
[compare(v, w) for v, w in zip(res,
c.data)]