本文整理汇总了Python中numpy.inf方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.inf方法的具体用法?Python numpy.inf怎么用?Python numpy.inf使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.inf方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: is_pos_def
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import inf [as 别名]
def is_pos_def(self, A):
"""
Check for positive definiteness.
Parameters
---------
A : array
square symmetric matrix.
Returns
-------
bool
whether matrix is positive-definite.
Warning! Returns false for arrays containing inf or NaN.
"""
# Check for valid numbers
if np.any(np.isnan(A)) or np.any(np.isinf(A)):
return False
else:
return np.all(np.real(np.linalg.eigvals(A)) > 0)
示例2: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import inf [as 别名]
def __init__(self, sess, saver, option, learner, data):
self.sess = sess
self.saver = saver
self.option = option
self.learner = learner
self.data = data
# helpers
self.msg_with_time = lambda msg: \
"%s Time elapsed %0.2f hrs (%0.1f mins)" \
% (msg, (time.time() - self.start) / 3600.,
(time.time() - self.start) / 60.)
self.start = time.time()
self.epoch = 0
self.best_valid_loss = np.inf
self.best_valid_in_top = 0.
self.train_stats = []
self.valid_stats = []
self.test_stats = []
self.early_stopped = False
self.log_file = open(os.path.join(self.option.this_expsdir, "log.txt"), "w")
示例3: test_attack_strength
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import inf [as 别名]
def test_attack_strength(self):
"""
If clipping is not done at each iteration (not passing clip_min and
clip_max to fgm), this attack fails by
np.mean(orig_labels == new_labels) == .39.
"""
x_val = np.random.rand(100, 2)
x_val = np.array(x_val, dtype=np.float32)
x_adv = self.attack.generate_np(x_val, eps=1.0, ord=np.inf,
clip_min=0.5, clip_max=0.7,
nb_iter=5)
orig_labs = np.argmax(self.sess.run(self.model(x_val)), axis=1)
new_labs = np.argmax(self.sess.run(self.model(x_adv)), axis=1)
self.assertTrue(np.mean(orig_labs == new_labs) < 0.1)
示例4: generate
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import inf [as 别名]
def generate(self, x, **kwargs):
"""
Generates the adversarial sample for the given input.
:param x: The model's inputs.
:param eps: (optional float) attack step size (input variation)
:param ord: (optional) Order of the norm (mimics NumPy).
Possible values: np.inf, 1 or 2.
:param y: (optional) A tf variable` with the model labels. Only provide
this parameter if you'd like to use true labels when crafting
adversarial samples. Otherwise, model predictions are used as
labels to avoid the "label leaking" effect (explained in this
paper: https://arxiv.org/abs/1611.01236). Default is None.
Labels should be one-hot-encoded.
:param y_target: (optional) A tf variable` with the labels to target.
Leave y_target=None if y is also set.
Labels should be one-hot-encoded.
:param clip_min: (optional float) Minimum input component value
:param clip_max: (optional float) Maximum input component value
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
labels, nb_classes = self.get_or_guess_labels(x, kwargs)
return self.fgm(x, labels=labels, targeted=(self.y_target is not None))
示例5: test_clip_eta_goldilocks
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import inf [as 别名]
def test_clip_eta_goldilocks(self):
# Test that the clipping handles perturbations that are
# too small, just right, and too big correctly
eta = tf.constant([[2.], [3.], [4.]])
assert eta.dtype == tf.float32, eta.dtype
eps = 3.
for ord_arg in [np.inf, 1, 2]:
for sign in [-1., 1.]:
clipped = clip_eta(eta * sign, ord_arg, eps)
clipped_value = self.sess.run(clipped)
gold = sign * np.array([[2.], [3.], [3.]])
self.assertClose(clipped_value, gold)
grad, = tf.gradients(clipped, eta)
grad_value = self.sess.run(grad)
# Note: the second 1. is debatable (the left-sided derivative
# and the right-sided derivative do not match, so formally
# the derivative is not defined). This test makes sure that
# we at least handle this oddity consistently across all the
# argument values we test
gold = sign * np.array([[1.], [1.], [0.]])
assert np.allclose(grad_value, gold)
示例6: apply_cmap
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import inf [as 别名]
def apply_cmap(zs, cmap, vmin=None, vmax=None, unit=None, logrescale=False):
'''
apply_cmap(z, cmap) applies the given cmap to the values in z; if vmin and/or vmax are passed,
they are used to scale z.
Note that this function can automatically rescale data into log-space if the colormap is a
neuropythy log-space colormap such as log_eccentricity. To enable this behaviour use the
optional argument logrescale=True.
'''
zs = pimms.mag(zs) if unit is None else pimms.mag(zs, unit)
zs = np.asarray(zs, dtype='float')
if pimms.is_str(cmap): cmap = matplotlib.cm.get_cmap(cmap)
if logrescale:
if vmin is None: vmin = np.log(np.nanmin(zs))
if vmax is None: vmax = np.log(np.nanmax(zs))
mn = np.exp(vmin)
u = zdivide(nanlog(zs + mn) - vmin, vmax - vmin, null=np.nan)
else:
if vmin is None: vmin = np.nanmin(zs)
if vmax is None: vmax = np.nanmax(zs)
u = zdivide(zs - vmin, vmax - vmin, null=np.nan)
u[np.isnan(u)] = -np.inf
return cmap(u)
示例7: cos_edge
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import inf [as 别名]
def cos_edge(f=Ellipsis, width=np.pi, offset=0, scale=1):
'''
cos_edge() yields a potential function g(x) that calculates 0 for x < pi/2, 1 for x > pi/2, and
0.5*(1 + cos(pi/2*(1 - x))) for x between -pi/2 and pi/2.
The full formulat of the cosine well is, including optional arguments:
scale/2 * (1 + cos(pi*(0.5 - (x - offset)/width)
The following optional arguments may be given:
* width (default: pi) specifies that the frequency of the cos-curve should be pi/width; the
width is the distance between the points on the cos-curve with the value of 1.
* offset (default: 0) specifies the offset of the minimum value of the coine curve on the
x-axis.
* scale (default: 1) specifies the height of the cosine well.
'''
f = to_potential(f)
freq = np.pi/2
(xmn,xmx) = (offset - width/2, offset + width/2)
F = piecewise(scale,
((-np.inf, xmn), 0),
((xmn,xmx), scale/2 * (1 + cos(np.pi*(0.5 - (identity - offset)/width)))))
if is_const_potential(f): return const_potential(F.value(f.c))
elif is_identity_potential(f): return F
else: return compose(F, f)
示例8: sigmoid
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import inf [as 别名]
def sigmoid(f=Ellipsis, mu=0, sigma=1, scale=1, invert=False, normalize=False):
'''
sigmoid() yields a potential function that is equivalent to the integral of gaussian(), i.e.,
the error function, but scaled to match gaussian().
sigmoid(f) is equivalent to compose(sigmoid(), f).
All options that are accepted by the gaussian() function are accepted by sigmoid() with the same
default values and are handled in an equivalent manner with the exception of the invert option;
when a sigmoid is inverted, the function approaches its maximum value at -inf and approaches 0
at inf.
Note that because sigmoid() explicitly matches gaussian(), the base formula used is as follows:
f(x) = scale * sigma * sqrt(pi/2) * erf((x - mu) / (sqrt(2) * sigma))
k*sig*Sqrt[Pi/2] Erf[(x - mu)/sig/Sqrt[2]]
'''
f = to_potential(f)
F = erf((f - mu) / (sigma * np.sqrt(2.0)))
if invert: F = 1 - F
F = np.sqrt(np.pi / 2) * scale * F
if normalize: F = F / (np.sqrt(2.0*np.pi) * sigma)
return F
示例9: arcsine
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import inf [as 别名]
def arcsine(x, null=(-np.inf, np.inf)):
'''
arcsine(x) is equivalent to asin(x) except that it also works on sparse arrays.
The optional argument null (default, (-numpy.inf, numpy.inf)) may be specified to indicate what
value(s) should be assigned when x < -1 or x > 1. If only one number is given, then it is used
for both values; otherwise the first value corresponds to <-1 and the second to >1. If null is
None, then an error is raised when invalid values are encountered.
'''
if sps.issparse(x):
x = x.copy()
x.data = arcsine(x.data, null=null, rtol=rtol, atol=atol)
return x
else: x = np.asarray(x)
try: (nln,nlp) = null
except Exception: (nln,nlp) = (null,null)
ii = None if nln is None else np.where(x < -1)
jj = None if nlp is None else np.where(x > 1)
if ii: x[ii] = 0
if jj: x[jj] = 0
x = np.arcsin(x)
if ii: x[ii] = nln
if jj: x[jj] = nlp
return x
示例10: arccosine
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import inf [as 别名]
def arccosine(x, null=(-np.inf, np.inf)):
'''
arccosine(x) is equivalent to acos(x) except that it also works on sparse arrays.
The optional argument null (default, (-numpy.inf, numpy.inf)) may be specified to indicate what
value(s) should be assigned when x < -1 or x > 1. If only one number is given, then it is used
for both values; otherwise the first value corresponds to <-1 and the second to >1. If null is
None, then an error is raised when invalid values are encountered.
'''
if sps.issparse(x): x = x.toarray()
else: x = np.asarray(x)
try: (nln,nlp) = null
except Exception: (nln,nlp) = (null,null)
ii = None if nln is None else np.where(x < -1)
jj = None if nlp is None else np.where(x > 1)
if ii: x[ii] = 0
if jj: x[jj] = 0
x = np.arccos(x)
if ii: x[ii] = nln
if jj: x[jj] = nlp
return x
示例11: rollout
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import inf [as 别名]
def rollout(env, agent, max_path_length=np.inf):
reward = []
o = env.reset()
# agent.reset()
path_length = 0
while path_length < max_path_length:
o = o.reshape((1, -1))
a = agent.get_action(o)
next_o, r, d, _ = env.step(a)
reward.append(r)
path_length += 1
if d:
break
o = next_o
return reward
示例12: convert_clip
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import inf [as 别名]
def convert_clip(node, **kwargs):
"""Map MXNet's Clip operator attributes to onnx's Clip operator
and return the created node.
"""
onnx = import_onnx_modules()
name = node["name"]
input_idx = kwargs["index_lookup"][node["inputs"][0][0]]
proc_nodes = kwargs["proc_nodes"]
input_node = proc_nodes[input_idx].name
attrs = node["attrs"]
a_min = np.float(attrs.get('a_min', -np.inf))
a_max = np.float(attrs.get('a_max', np.inf))
clip_node = onnx.helper.make_node(
"Clip",
[input_node],
[name],
name=name,
min=a_min,
max=a_max
)
return [clip_node]
示例13: _compute_delta
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import inf [as 别名]
def _compute_delta(self, log_moments, eps):
"""Compute delta for given log_moments and eps.
Args:
log_moments: the log moments of privacy loss, in the form of pairs
of (moment_order, log_moment)
eps: the target epsilon.
Returns:
delta
"""
min_delta = 1.0
for moment_order, log_moment in log_moments:
if math.isinf(log_moment) or math.isnan(log_moment):
sys.stderr.write("The %d-th order is inf or Nan\n" % moment_order)
continue
if log_moment < moment_order * eps:
min_delta = min(min_delta,
math.exp(log_moment - moment_order * eps))
return min_delta
示例14: _compute_delta
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import inf [as 别名]
def _compute_delta(log_moments, eps):
"""Compute delta for given log_moments and eps.
Args:
log_moments: the log moments of privacy loss, in the form of pairs
of (moment_order, log_moment)
eps: the target epsilon.
Returns:
delta
"""
min_delta = 1.0
for moment_order, log_moment in log_moments:
if moment_order == 0:
continue
if math.isinf(log_moment) or math.isnan(log_moment):
sys.stderr.write("The %d-th order is inf or Nan\n" % moment_order)
continue
if log_moment < moment_order * eps:
min_delta = min(min_delta,
math.exp(log_moment - moment_order * eps))
return min_delta
示例15: _compute_eps
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import inf [as 别名]
def _compute_eps(log_moments, delta):
"""Compute epsilon for given log_moments and delta.
Args:
log_moments: the log moments of privacy loss, in the form of pairs
of (moment_order, log_moment)
delta: the target delta.
Returns:
epsilon
"""
min_eps = float("inf")
for moment_order, log_moment in log_moments:
if moment_order == 0:
continue
if math.isinf(log_moment) or math.isnan(log_moment):
sys.stderr.write("The %d-th order is inf or Nan\n" % moment_order)
continue
min_eps = min(min_eps, (log_moment - math.log(delta)) / moment_order)
return min_eps