当前位置: 首页>>代码示例>>Python>>正文


Python numpy.sign方法代码示例

本文整理汇总了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 
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:20,代码来源:pgd_cw_whitebox.py

示例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) 
开发者ID:noahbenson,项目名称:neuropythy,代码行数:19,代码来源:retinotopy.py

示例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 
开发者ID:fukuball,项目名称:fuku-ml,代码行数:21,代码来源:DecisionStump.py

示例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) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:21,代码来源:test_quantization.py

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

示例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 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:21,代码来源:gym_utils.py

示例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 
开发者ID:IBM,项目名称:differential-privacy-library,代码行数:21,代码来源:naive_bayes.py

示例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)) 
开发者ID:IBM,项目名称:differential-privacy-library,代码行数:23,代码来源:laplace.py

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

示例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 
开发者ID:msu-coinlab,项目名称:pymoo,代码行数:20,代码来源:so_pattern_search.py

示例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]) 
开发者ID:masaponto,项目名称:Python-ELM,代码行数:19,代码来源:elm.py

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

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

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

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


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