本文整理匯總了Python中numpy.sign方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.sign方法的具體用法?Python numpy.sign怎麽用?Python numpy.sign使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.sign方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: perturb
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import sign [as 別名]
def perturb(self, x_nat, y, sess):
"""Given a set of examples (x_nat, y), returns a set of adversarial
examples within epsilon of x_nat in l_infinity norm."""
if self.rand:
x = x_nat + np.random.uniform(-self.epsilon, self.epsilon, x_nat.shape)
else:
x = np.copy(x_nat)
for i in range(self.k):
grad = sess.run(self.grad, feed_dict={self.model.x_input: x,
self.model.y_input: y})
x += self.a * np.sign(grad)
x = np.clip(x, x_nat - self.epsilon, x_nat + self.epsilon)
x = np.clip(x, 0, 1) # ensure valid pixel range
return x
示例2: _retinotopic_field_sign_triangles
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import sign [as 別名]
def _retinotopic_field_sign_triangles(m, retinotopy):
t = m.tess if isinstance(m, geo.Mesh) or isinstance(m, geo.Topology) else m
# get the polar angle and eccen data as a complex number in degrees
if pimms.is_str(retinotopy):
(x,y) = as_retinotopy(retinotopy_data(m, retinotopy), 'geographical')
elif retinotopy is Ellipsis:
(x,y) = as_retinotopy(retinotopy_data(m, 'any'), 'geographical')
else:
(x,y) = as_retinotopy(retinotopy, 'geographical')
# Okay, now we want to make some coordinates...
coords = np.asarray([x, y])
us = coords[:, t.indexed_faces[1]] - coords[:, t.indexed_faces[0]]
vs = coords[:, t.indexed_faces[2]] - coords[:, t.indexed_faces[0]]
(us,vs) = [np.concatenate((xs, np.full((1, t.face_count), 0.0))) for xs in [us,vs]]
xs = np.cross(us, vs, axis=0)[2]
xs[np.isclose(xs, 0)] = 0
return np.sign(xs)
示例3: __init__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import sign [as 別名]
def __init__(self):
"""init"""
self.status = 'empty'
self.train_X = []
self.train_Y = []
self.W = []
self.data_num = 0
self.data_demension = 0
self.test_X = []
self.test_Y = []
self.feature_transform_mode = ''
self.feature_transform_degree = 1
self.sign = 1
self.feature_index = 0
self.theta = 0
self.u = None
示例4: test_quantize_float32_to_int8
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import sign [as 別名]
def test_quantize_float32_to_int8():
shape = rand_shape_nd(4)
data = rand_ndarray(shape, 'default', dtype='float32')
min_range = mx.nd.min(data)
max_range = mx.nd.max(data)
qdata, min_val, max_val = mx.nd.contrib.quantize(data, min_range, max_range, out_type='int8')
data_np = data.asnumpy()
min_range = min_range.asscalar()
max_range = max_range.asscalar()
real_range = np.maximum(np.abs(min_range), np.abs(max_range))
quantized_range = 127.0
scale = quantized_range / real_range
assert qdata.dtype == np.int8
assert min_val.dtype == np.float32
assert max_val.dtype == np.float32
assert same(min_val.asscalar(), -real_range)
assert same(max_val.asscalar(), real_range)
qdata_np = (np.sign(data_np) * np.minimum(np.abs(data_np) * scale + 0.5, quantized_range)).astype(np.int8)
assert_almost_equal(qdata.asnumpy(), qdata_np, atol = 1)
示例5: move
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import sign [as 別名]
def move(self, P0, P1):
"""
Move a point P0 to a new legal location
:param P0: ndarray[2]
:param P1: ndarray[2]
:return: ndarray[2]
"""
x_dist, y_dist = P1 - P0
tdist = np.sqrt(y_dist**2+x_dist**2)
if self.is_in(P1):
return P1
else:
x_steps = int(np.sign(x_dist) * np.ceil(abs(x_dist / self.dx)))#, self.max_step
y_steps = int(np.sign(y_dist) * np.ceil(abs(y_dist / self.dy)))#, self.max_step
i0, j0 = self.locate_ij(P0)
P2 = self.locate_xy(i0, j0)
P_off = P2 - P0
self.loop_i = 0
i1, j1 = self.valid_move(i0, j0, x_steps, y_steps, P_off)
P2 = self.locate_xy(i1, j1) + P_off
return P2
示例6: step
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import sign [as 別名]
def step(self, action):
ob, rew, done, info = self.env.step(action)
if BreakoutWrapper.find_ball(ob) is None and self.ball_down_skip != 0:
for _ in range(self.ball_down_skip):
# We assume that nothing interesting happens during ball_down_skip
# and discard all information.
# We fire all the time to start new game
ob, _, _, _ = self.env.step(BreakoutWrapper.FIRE_ACTION)
self.direction_info.append(BreakoutWrapper.find_ball(ob))
ob = self.process_observation(ob)
self.points_gained = self.points_gained or rew > 0
if self.reward_clipping:
rew = np.sign(rew)
return ob, rew, done, info
示例7: _noisy_class_counts
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import sign [as 別名]
def _noisy_class_counts(self, y):
unique_y = np.unique(y)
n_total = y.shape[0]
# Use 1/3 of total epsilon budget for getting noisy class counts
mech = GeometricTruncated().set_epsilon(self.epsilon / 3).set_sensitivity(1).set_bounds(1, n_total)
noisy_counts = np.array([mech.randomise((y == y_i).sum()) for y_i in unique_y])
argsort = np.argsort(noisy_counts)
i = 0 if noisy_counts.sum() > n_total else len(unique_y) - 1
while np.sum(noisy_counts) != n_total:
_i = argsort[i]
sgn = np.sign(n_total - noisy_counts.sum())
noisy_counts[_i] = np.clip(noisy_counts[_i] + sgn, 1, n_total)
i = (i - sgn) % len(unique_y)
return noisy_counts
示例8: randomise
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import sign [as 別名]
def randomise(self, value):
"""Randomise `value` with the mechanism.
Parameters
----------
value : float
The value to be randomised.
Returns
-------
float
The randomised value.
"""
self.check_inputs(value)
scale = self._sensitivity / (self._epsilon - np.log(1 - self._delta))
unif_rv = random() - 0.5
return value - scale * np.sign(unif_rv) * np.log(1 - 2 * np.abs(unif_rv))
示例9: _evaluate
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import sign [as 別名]
def _evaluate(self, X, out, *args, **kwargs):
if self.w == 0:
X1 = X[:, 0]
X2 = X[:, 1]
else:
# If rotated, we rotate it back by applying the inverted rotation matrix to X
Y = np.array([np.matmul(self.IRM, x) for x in X])
X1 = Y[:, 0]
X2 = Y[:, 1]
a, b, c = self.a, self.b, self.c
t1_hat = sign(X1) * ceil((abs(X1) - a - c / 2) / (2 * a + c))
t2_hat = sign(X2) * ceil((abs(X2) - b / 2) / b)
one = ones(len(X))
t1 = sign(t1_hat) * min(np.vstack((abs(t1_hat), one)), axis=0)
t2 = sign(t2_hat) * min(np.vstack((abs(t2_hat), one)), axis=0)
p1 = X1 - t1 * c
p2 = X2 - t2 * b
f1 = (p1 + a) ** 2 + p2 ** 2
f2 = (p1 - a) ** 2 + p2 ** 2
out["F"] = np.vstack((f1, f2)).T
示例10: _pattern_move
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import sign [as 別名]
def _pattern_move(self, _current, _next):
# get the direction and assign the corresponding delta value
direction = (_next.X - _current.X)
# get the delta sign adjusted
sign = np.sign(direction)
sign[sign == 0] = -1
self.explr_delta = sign * np.abs(self.explr_delta)
# calculate the new X and repair out of bounds if necessary
X = _current.X + self.pattern_step * direction
repair_out_of_bounds_manually(X, *self.problem.bounds())
# create the new center individual without evaluating it
trial = Individual(X=X)
return trial
示例11: predict
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import sign [as 別名]
def predict(self, X):
"""
predict classify result
Args:
X [[float]] array: feature vectors of learnig data
Returns:
[int]: labels of classification result
"""
_H = self._sigmoid(np.dot(self.W, self._add_bias(X).T))
y = np.dot(_H.T, self.beta)
if self.out_num == 1:
return np.sign(y)
else:
return np.argmax(y, 1) + np.ones(y.shape[0])
示例12: _rsp_findpeaks_outliers
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import sign [as 別名]
def _rsp_findpeaks_outliers(rsp_cleaned, extrema, amplitude_min=0.3):
# Only consider those extrema that have a minimum vertical distance to
# their direct neighbor, i.e., define outliers in absolute amplitude
# difference between neighboring extrema.
vertical_diff = np.abs(np.diff(rsp_cleaned[extrema]))
median_diff = np.median(vertical_diff)
min_diff = np.where(vertical_diff > (median_diff * amplitude_min))[0]
extrema = extrema[min_diff]
# Make sure that the alternation of peaks and troughs is unbroken. If
# alternation of sign in extdiffs is broken, remove the extrema that
# cause the breaks.
amplitudes = rsp_cleaned[extrema]
extdiffs = np.sign(np.diff(amplitudes))
extdiffs = np.add(extdiffs[0:-1], extdiffs[1:])
removeext = np.where(extdiffs != 0)[0] + 1
extrema = np.delete(extrema, removeext)
amplitudes = np.delete(amplitudes, removeext)
return extrema, amplitudes
示例13: predict
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import sign [as 別名]
def predict(self, Z):
"""
Make predictions on new dataset.
Parameters
----------
Z : array
new data set (M samples by D features)
Returns
-------
preds : array
label predictions (M samples by 1)
"""
# Data shape
M, D = Z.shape
# If classifier is trained, check for same dimensionality
if self.is_trained:
if not self.train_data_dim == D:
raise ValueError('''Test data is of different dimensionality
than training data.''')
# Check for augmentation
if not self.train_data_dim == D:
Z = np.concatenate((np.dot(Z, self.C), Z), axis=1)
# Call scikit's predict function
preds = self.clf.predict(Z)
# For quadratic loss function, correct predictions
if self.loss == 'quadratic':
preds = (np.sign(preds)+1)/2.
# Return predictions array
return preds
示例14: predict
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import sign [as 別名]
def predict(self, Z):
"""
Make predictions on new dataset.
Parameters
----------
Z : array
new data set (M samples by D features)
Returns
-------
preds : array
label predictions (M samples by 1)
"""
# Data shape
M, D = Z.shape
# If classifier is trained, check for same dimensionality
if self.is_trained:
if not self.train_data_dim == D:
raise ValueError('''Test data is of different dimensionality
than training data.''')
# Call scikit's predict function
preds = self.clf.predict(Z)
# For quadratic loss function, correct predictions
if self.loss == 'quadratic':
preds = (np.sign(preds)+1)/2.
# Return predictions array
return preds
示例15: predict
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import sign [as 別名]
def predict(self, Z):
"""
Make predictions on new dataset.
Parameters
----------
Z : array
new data set (M samples by D features)
Returns
-------
preds : array
label predictions (M samples by 1)
"""
# Data shape
M, D = Z.shape
# If classifier is trained, check for same dimensionality
if self.is_trained:
if not self.train_data_dim == D:
raise ValueError('''Test data is of different dimensionality
than training data.''')
# Compute kernel for new data
K = self.kernel(Z, self.XZ, type=self.kernel_type,
bandwidth=self.bandwidth, order=self.order)
# Map new data onto transfer components
Z = np.dot(K, self.C)
# Call scikit's predict function
preds = self.clf.predict(Z)
# For quadratic loss function, correct predictions
if self.loss == 'quadratic':
preds = (np.sign(preds)+1)/2.
# Return predictions array
return preds