• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python numpy.negative函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中numpy.negative函数的典型用法代码示例。如果您正苦于以下问题:Python negative函数的具体用法?Python negative怎么用?Python negative使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了negative函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)')
开发者ID:Darriall,项目名称:pypy,代码行数:28,代码来源:test_outarg.py


示例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)
开发者ID:pslh,项目名称:nhlib,代码行数:27,代码来源:mesh_test.py


示例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())
开发者ID:j-min,项目名称:tensorflow,代码行数:27,代码来源:variables_test.py


示例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
开发者ID:Qointum,项目名称:pypy,代码行数:25,代码来源:test_ufuncs.py


示例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())
开发者ID:0ruben,项目名称:tensorflow,代码行数:27,代码来源:variables_test.py


示例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
开发者ID:GeorgeMcIntire,项目名称:BDA_py_demos,代码行数:32,代码来源:sinvchi2.py


示例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()
开发者ID:ASU-CompMethodsPhysics-PHY494,项目名称:final-digital-signal-processor,代码行数:7,代码来源:buffer.py


示例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]],
    ])
开发者ID:CV-IP,项目名称:opensurfaces,代码行数:28,代码来源:geom.py


示例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,
开发者ID:Fhrozen,项目名称:chainer,代码行数:7,代码来源:trigonometric.py


示例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
开发者ID:FairSky,项目名称:pycmb,代码行数:28,代码来源:observation.py


示例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
开发者ID:HK-Zhang,项目名称:Corn,代码行数:8,代码来源:Numpy100.py


示例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,
开发者ID:KotaroSetoyama,项目名称:chainer,代码行数:8,代码来源:trigonometric.py


示例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:])
开发者ID:eruffaldi,项目名称:stereocalib,代码行数:58,代码来源:se3d.py


示例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
开发者ID:danelliottster,项目名称:ANN,代码行数:57,代码来源:backProp.py


示例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
开发者ID:bencesomogyi,项目名称:pyCFD,代码行数:9,代码来源:generic_operator.py


示例16: generate_unit_phase_shifts

def generate_unit_phase_shifts(shape, float_type=float):
    """
        Computes the complex phase shift's angle due to a unit spatial shift.

        This is meant to be a helper function for ``register_mean_offsets``. It
        does this by computing a table of the angle of the phase of a unit
        shift in each dimension (with a factor of :math:`2\pi`).

        This allows arbitrary phase shifts to be made in each dimensions by
        multiplying these angles by the size of the shift and added to the
        existing angle to induce the proper phase shift in fourier space, which
        is equivalent to the spatial translation.

        Args:
            shape(tuple of ints):       shape of the data to be shifted.

            float_type(real type):      phase type (default numpy.float64)

        Returns:
            (numpy.ndarray):            an array containing the angle of the
                                        complex phase shift to use for each
                                        dimension.

        Examples:
            >>> generate_unit_phase_shifts((2,4))
            array([[[-0.        , -0.        , -0.        , -0.        ],
                    [-3.14159265, -3.14159265, -3.14159265, -3.14159265]],
            <BLANKLINE>
                   [[-0.        , -1.57079633, -3.14159265, -4.71238898],
                    [-0.        , -1.57079633, -3.14159265, -4.71238898]]])
    """

    # Convert to `numpy`-based type if not done already.
    float_type = numpy.dtype(float_type).type

    # Must be of type float.
    assert issubclass(float_type, numpy.floating)
    assert numpy.dtype(float_type).itemsize >= 4

    # Get the negative wave vector
    negative_wave_vector = numpy.asarray(shape, dtype=float_type)
    numpy.reciprocal(negative_wave_vector, out=negative_wave_vector)
    negative_wave_vector *= 2*numpy.pi
    numpy.negative(negative_wave_vector, out=negative_wave_vector)

    # Get the indices for each point in the selected space.
    indices = xnumpy.cartesian_product([numpy.arange(_) for _ in shape])

    # Determine the phase offset for each point in space.
    complex_angle_unit_shift = indices * negative_wave_vector
    complex_angle_unit_shift = complex_angle_unit_shift.T.copy()
    complex_angle_unit_shift = complex_angle_unit_shift.reshape(
        (len(shape),) + shape
    )

    return(complex_angle_unit_shift)
开发者ID:DudLab,项目名称:nanshe,代码行数:56,代码来源:registration.py


示例17: test_lower_align

 def test_lower_align(self):
     # check data that is not aligned to element size
     # i.e doubles are aligned to 4 bytes on i386
     d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64)
     assert_equal(np.abs(d), d)
     assert_equal(np.negative(d), -d)
     np.negative(d, out=d)
     np.negative(np.ones_like(d), out=d)
     np.abs(d, out=d)
     np.abs(np.ones_like(d), out=d)
开发者ID:pombredanne,项目名称:linuxtrail,代码行数:10,代码来源:test_umath.py


示例18: getMountainWeights

def getMountainWeights(bgDiff, mountainCenter, halfLife = 0.1):
    mountainWeights = bgDiff - mountainCenter
    
    k = np.log(2) / halfLife
    mountainWeights *= k
    
    np.abs(mountainWeights, out = mountainWeights)
    np.negative(mountainWeights, out = mountainWeights)
    np.exp(mountainWeights, out = mountainWeights)
    return mountainWeights
开发者ID:evanshort73,项目名称:transparency,代码行数:10,代码来源:transparency.py


示例19: decompose

    def decompose(self):
        M = numpy.array(self._data, dtype = numpy.float64, copy = True).T
        if abs(M[3, 3]) < self._EPS:
            raise ValueError("M[3, 3] is zero")
        M /= M[3, 3]
        P = M.copy()
        P[:, 3] = 0.0, 0.0, 0.0, 1.0
        if not numpy.linalg.det(P):
            raise ValueError("matrix is singular")

        scale = numpy.zeros((3, ))
        shear = [0.0, 0.0, 0.0]
        angles = [0.0, 0.0, 0.0]
        mirror = [1, 1, 1]

        translate = M[3, :3].copy()
        M[3, :3] = 0.0

        row = M[:3, :3].copy()
        scale[0] = math.sqrt(numpy.dot(row[0], row[0]))
        row[0] /= scale[0]
        shear[0] = numpy.dot(row[0], row[1])
        row[1] -= row[0] * shear[0]
        scale[1] = math.sqrt(numpy.dot(row[1], row[1]))
        row[1] /= scale[1]
        shear[0] /= scale[1]
        shear[1] = numpy.dot(row[0], row[2])
        row[2] -= row[0] * shear[1]
        shear[2] = numpy.dot(row[1], row[2])
        row[2] -= row[1] * shear[2]
        scale[2] = math.sqrt(numpy.dot(row[2], row[2]))
        row[2] /= scale[2]
        shear[1:] /= scale[2]

        if numpy.dot(row[0], numpy.cross(row[1], row[2])) < 0:
            numpy.negative(scale, scale)
            numpy.negative(row, row)

        # If the scale was negative, we give back a seperate mirror vector to indicate this.
        if M[0, 0] < 0:
            mirror[0] = -1
        if M[1, 1] < 0:
            mirror[1] = -1
        if M[2, 2] < 0:
            mirror[2] = -1

        angles[1] = math.asin(-row[0, 2])
        if math.cos(angles[1]):
            angles[0] = math.atan2(row[1, 2], row[2, 2])
            angles[2] = math.atan2(row[0, 1], row[0, 0])
        else:
            angles[0] = math.atan2(-row[2, 1], row[1, 1])
            angles[2] = 0.0

        return Vector(data = scale), Vector(data = shear), Vector(data = angles), Vector(data = translate), Vector(data = mirror)
开发者ID:senttech,项目名称:Uranium,代码行数:55,代码来源:Matrix.py


示例20: computeDeltaW

def computeDeltaW(tmpDeltaW,A_O,y,DeltaW,errorF):
    # init values and allocate memory
    M_O = A_O.shape[0]          # num vector elements
    errors = np.zeros_like(y)
    # compute errors
    errorF[1](y,A_O,errors)
    np.negative(errors,errors)
    # compute Delta_W
    for i in range(M_O):
        tmpDeltaW[i,:,:] *= errors[i]
        np.add(DeltaW,tmpDeltaW[i,:,:],DeltaW)
开发者ID:danelliottster,项目名称:ANN,代码行数:11,代码来源:rtrl.py



注:本文中的numpy.negative函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python numpy.nextafter函数代码示例发布时间:2022-05-27
下一篇:
Python numpy.nditer函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap