本文整理汇总了Python中numpy.negative函数的典型用法代码示例。如果您正苦于以下问题:Python negative函数的具体用法?Python negative怎么用?Python negative使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了negative函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_ufunc_out
def test_ufunc_out(self):
from numpy import array, negative, zeros, sin
from math import sin as msin
a = array([[1, 2], [3, 4]])
c = zeros((2,2,2))
b = negative(a + a, out=c[1])
#test for view, and also test that forcing out also forces b
assert (c[:, :, 1] == [[0, 0], [-4, -8]]).all()
assert (b == [[-2, -4], [-6, -8]]).all()
#Test broadcast, type promotion
b = negative(3, out=a)
assert (a == -3).all()
c = zeros((2, 2), dtype=float)
b = negative(3, out=c)
assert b.dtype.kind == c.dtype.kind
assert b.shape == c.shape
a = array([1, 2])
b = sin(a, out=c)
assert(c == [[msin(1), msin(2)]] * 2).all()
b = sin(a, out=c+c)
assert (c == b).all()
#Test shape agreement
a = zeros((3,4))
b = zeros((3,5))
raises(ValueError, 'negative(a, out=b)')
b = zeros((1,4))
raises(ValueError, 'negative(a, out=b)')
示例2: test_rectangular
def test_rectangular(self):
lons = numpy.array(range(100)).reshape((10, 10))
lats = numpy.negative(lons)
mesh = RectangularMesh(lons, lats, depths=None)
bounding_mesh = mesh._get_bounding_mesh()
expected_lons = numpy.array([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
19, 29, 39, 49, 59, 69, 79, 89,
99, 98, 97, 96, 95, 94, 93, 92, 91,
90, 80, 70, 60, 50, 40, 30, 20, 10
])
expected_lats = numpy.negative(expected_lons)
self.assertTrue((bounding_mesh.lons == expected_lons).all())
self.assertTrue((bounding_mesh.lats == expected_lats).all())
self.assertIsNone(bounding_mesh.depths)
depths = lons + 10
mesh = RectangularMesh(lons, lats, depths)
expected_depths = expected_lons + 10
bounding_mesh = mesh._get_bounding_mesh()
self.assertIsNotNone(bounding_mesh.depths)
self.assertTrue((bounding_mesh.depths
== expected_depths.flatten()).all())
bounding_mesh = mesh._get_bounding_mesh(with_depths=False)
self.assertIsNone(bounding_mesh.depths)
示例3: testInitializerFunction
def testInitializerFunction(self):
value = [[-42], [133.7]]
shape = [2, 1]
with self.test_session():
initializer = lambda: constant_op.constant(value)
v1 = variables.Variable(initializer, dtype=dtypes.float32)
self.assertEqual(shape, v1.get_shape())
self.assertEqual(shape, v1.shape)
self.assertAllClose(value, v1.initial_value.eval())
with self.assertRaises(errors_impl.FailedPreconditionError):
v1.eval()
v2 = variables.Variable(
math_ops.negative(v1.initialized_value()), dtype=dtypes.float32)
self.assertEqual(v1.get_shape(), v2.get_shape())
self.assertEqual(v1.shape, v2.shape)
self.assertAllClose(np.negative(value), v2.initial_value.eval())
# Once v2.initial_value.eval() has been called, v1 has effectively been
# initialized.
self.assertAllClose(value, v1.eval())
with self.assertRaises(errors_impl.FailedPreconditionError):
v2.eval()
variables.global_variables_initializer().run()
self.assertAllClose(np.negative(value), v2.eval())
示例4: test_negative
def test_negative(self):
from numpy import array, negative
a = array([-5.0, 0.0, 1.0])
b = negative(a)
for i in range(3):
assert b[i] == -a[i]
a = array([-5.0, 1.0])
b = negative(a)
a[0] = 5.0
assert b[0] == 5.0
a = array(range(30))
assert negative(a + a)[3] == -6
a = array([[1, 2], [3, 4]])
b = negative(a + a)
assert (b == [[-2, -4], [-6, -8]]).all()
class Obj(object):
def __neg__(self):
return "neg"
x = Obj()
assert type(negative(x)) is str
示例5: testInitializerFunction
def testInitializerFunction(self):
value = [[-42], [133.7]]
shape = [2, 1]
with self.test_session():
initializer = lambda: tf.constant(value)
with self.assertRaises(ValueError):
# Checks that dtype must be specified.
tf.Variable(initializer)
v1 = tf.Variable(initializer, dtype=tf.float32)
self.assertEqual(shape, v1.get_shape())
self.assertAllClose(value, v1.initial_value.eval())
with self.assertRaises(tf.errors.FailedPreconditionError):
v1.eval()
v2 = tf.Variable(tf.neg(v1.initialized_value()), dtype=tf.float32)
self.assertEqual(v1.get_shape(), v2.get_shape())
self.assertAllClose(np.negative(value), v2.initial_value.eval())
# Once v2.initial_value.eval() has been called, v1 has effectively been
# initialized.
self.assertAllClose(value, v1.eval())
with self.assertRaises(tf.errors.FailedPreconditionError):
v2.eval()
tf.initialize_all_variables().run()
self.assertAllClose(np.negative(value), v2.eval())
示例6: logpdf
def logpdf(x, nu, s2=1):
"""Log of the scaled inverse chi-squared probability density function.
Parameters
----------
x : array_like
quantiles
nu : array_like
degrees of freedom
s2 : array_like, optional
scale (default 1)
Returns
-------
logpdf : ndarray
Log of the probability density function evaluated at `x`.
"""
x = np.asarray(x)
nu = np.asarray(nu)
s2 = np.asarray(s2)
nu_2 = nu/2
y = np.log(x)
y *= (nu_2 +1)
np.negative(y, out=y)
y -= (nu_2*s2)/x
y += np.log(s2)*nu_2
y -= gammaln(nu_2)
y += np.log(nu_2)*nu_2
return y
示例7: neg
def neg(target):
a = pyext.Buffer(target)
# in place transformation (see Python array ufuncs)
N.negative(a[:],a[:])
# must mark buffer content as dirty to update graph
# (no explicit assignment occurred)
a.dirty()
示例8: construct_uvn_frame
def construct_uvn_frame(n, u, b=None, flip_to_match_image=True):
""" Returns an orthonormal 3x3 frame from a normal and one in-plane vector """
n = normalized(n)
u = normalized(np.array(u) - np.dot(n, u) * n)
v = normalized_cross(n, u)
# flip to match image orientation
if flip_to_match_image:
if abs(u[1]) > abs(v[1]):
u, v = v, u
if u[0] < 0:
u = np.negative(u)
if v[1] < 0:
v = np.negative(v)
if b is None:
if n[2] < 0:
n = np.negative(n)
else:
if np.dot(n, b) > 0:
n = np.negative(n)
# return uvn matrix, column major
return np.matrix([
[u[0], v[0], n[0]],
[u[1], v[1], n[1]],
[u[2], v[2], n[2]],
])
示例9: forward_cpu
def forward_cpu(self, inputs):
self.retain_inputs((0, 1))
x, gy = inputs
gx = utils.force_array(numpy.sin(x))
numpy.negative(gx, out=gx)
gx *= gy
return gx,
示例10: unmask_temperature
def unmask_temperature(self, signal, order='nested', seed=None):
"""
Given the harmonic sphere map ``signal`` as the underlying signal,
provide a map where the mask has been removed and replaced with the
contents of signal. Noise consistent with the noise properties
of the observation (without the mask) will be added.
"""
Nside, lmin, lmax = self.Nside, signal.lmin, signal.lmax
random_state = as_random_state(seed)
temperature = self.load_temperature_mutable(order)
inverse_mask = (self.properties.load_mask_mutable(order) == 1).view(np.ndarray)
np.negative(inverse_mask, inverse_mask) # invert the mask in-place
# First, smooth the signal with the beam and pixel window
smoothed_signal = self.properties.load_beam_transfer_matrix(lmin, lmax) * signal
pixwin = load_temperature_pixel_window_matrix(Nside, lmin, lmax)
smoothed_signal = pixwin * smoothed_signal
# Create map from signal, and replace unmasked values in temperature map
signal_map = smoothed_signal.to_pixel(self.Nside)
signal_map.change_order_inplace(order)
temperature[inverse_mask] = signal_map[inverse_mask]
# Finally, add RMS to unmasked area
rms_in_mask = self.properties.load_rms(order)[inverse_mask]
temperature[inverse_mask] += random_state.normal(scale=rms_in_mask)
return temperature
示例11: negateVal
def negateVal():
"""negate a boolean, change the sign of a float inplace"""
Z=np.random.randint(0,2,100)
np.logical_not(Z,out=Z)
print Z
W=np.random.uniform(-1.0,1.0,100)
np.negative(Z,out=Z)
print Z
示例12: backward_cpu
def backward_cpu(self, x, gy):
gx = utils.force_array(numpy.square(x[0]))
numpy.negative(gx, out=gx)
gx += 1
numpy.sqrt(gx, out=gx)
numpy.reciprocal(gx, out=gx)
gx *= gy[0]
return gx,
示例13: _quaternion_from_matrix
def _quaternion_from_matrix(matrix, isprecise=False):
"""Summary
Args:
matrix (TYPE): Description
isprecise (bool, optional): Description
Returns:
TYPE: Description
"""
M = np.array(matrix, dtype=np.float64, copy=False)[:4, :4]
if isprecise:
q = np.empty((4, ))
t = np.trace(M)
if t > M[3, 3]:
q[0] = t
q[3] = M[1, 0] - M[0, 1]
q[2] = M[0, 2] - M[2, 0]
q[1] = M[2, 1] - M[1, 2]
else:
i, j, k = 1, 2, 3
if M[1, 1] > M[0, 0]:
i, j, k = 2, 3, 1
if M[2, 2] > M[i, i]:
i, j, k = 3, 1, 2
t = M[i, i] - (M[j, j] + M[k, k]) + M[3, 3]
q[i] = t
q[j] = M[i, j] + M[j, i]
q[k] = M[k, i] + M[i, k]
q[3] = M[k, j] - M[j, k]
q *= 0.5 / math.sqrt(t * M[3, 3])
# NEED MORMALIZE
else:
m00 = M[0, 0]
m01 = M[0, 1]
m02 = M[0, 2]
m10 = M[1, 0]
m11 = M[1, 1]
m12 = M[1, 2]
m20 = M[2, 0]
m21 = M[2, 1]
m22 = M[2, 2]
# symmetric matrix K
K = np.array([[m00-m11-m22, 0.0, 0.0, 0.0],
[m01+m10, m11-m00-m22, 0.0, 0.0],
[m02+m20, m12+m21, m22-m00-m11, 0.0],
[m21-m12, m02-m20, m10-m01, m00+m11+m22]])
K /= 3.0
# quaternion is eigenvector of K that corresponds to largest eigenvalue
w, V = np.linalg.eigh(K)
q = V[[3, 0, 1, 2], np.argmax(w)]
if q[0] < 0.0:
np.negative(q, q)
n = np.linalg.norm(q)
if n > 1.0:
q = q/n
# taken from ransformations.py so w first
return (q[0], q[1:])
示例14: backProp_epoch
def backProp_epoch(I,T,W_IH,W_HO,A_O,
DeltaW_IH,DeltaW_HO,
net_H=None,net_O=None,A_H=None,
Delta_H=None,Delta_O=None,
sigma_H=(afs.sigmoid,afs.sigmoid_prime),
sigma_O=(afs.sigmoid,afs.sigmoid_prime),
errorF=(efs.sumSquaredError,efs.sumSquaredError_prime)):
"""
net: node input function result
A: node activation
sigma: activation function
errorF: ( error function(target,output),error function derivative(target,output) )
"""
(M_H,M_I) = W_IH.shape; M_I-=1;
(M_O,blah) = W_HO.shape;
(M,N) = I.shape
if net_H == None:
net_H = np.empty((M_H,1))
if net_O == None:
net_O = np.empty((M_O,1))
if A_H == None:
A_H = np.empty_like(net_H)
if Delta_H == None:
Delta_H = np.empty_like(net_H)
if Delta_O == None:
Delta_O = np.empty_like(net_O)
# compute hidden layer inputs
np.dot(W_IH[:,:-1],I,net_H) # net_H is M_H x N
np.add(net_H,np.dot(W_IH[:,-1:],np.ones((1,N))),net_H) # bias
# compute hidden layer activations
sigma_H[0](net_H,A_H) # A_H is M_H x N
# compute output layer inputs
np.dot(W_HO[:,:-1],A_H,net_O)
np.add(net_O,np.dot(W_HO[:,-1:],np.ones((1,N))),net_O) # bias
# compute output layer activations
sigma_O[0](net_O,A_O)
# compute output error
errorVal = errorF[0](A_O,T)
# compute output error gradient
errorF[1](T,A_O,Delta_O) # Delta_O holds tmp value
np.negative(Delta_O,Delta_O)
sigma_O[1](A_O,net_O) # reusing net_O matrix as tmp storage
np.multiply(Delta_O,net_O,Delta_O)
# compute output weight update
tmpA_H = np.append(A_H,np.ones((1,N)),axis=0) # add bias inputs
np.dot(Delta_O,tmpA_H.T,DeltaW_HO) # TODO: compute using tanspose for speed-up?
# compute hidden error gradient
sigma_H[1](A_H,Delta_H) # Delta_H holds tmp value
np.multiply(Delta_H,
np.dot(W_HO[:,:-1].T,Delta_O), # TODO: W^T*Delta_O too wasteful
Delta_H)
# compute hidden weight update
tmpI = np.append(I,np.ones((1,N)),axis=0) # add bias inputs
np.dot(Delta_H,tmpI.T,DeltaW_IH) # TODO: compute using transpose for speed-up?
# np.multiply(DeltaW_IH,alpha,DeltaW_IH) # apply learning rate
# TODO: force garbage collection at key areas where temporaries are created
return errorVal
示例15: __neg__
def __neg__(self):
"""
return negated
"""
self.A = numpy.negative(self.A)
self.bX = numpy.negative(self.bX)
self.bY = numpy.negative(self.bY)
self.bZ = numpy.negative(self.bZ)
return self