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


Python numpy.true_divide方法代码示例

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


在下文中一共展示了numpy.true_divide方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: reduce_fit

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import true_divide [as 别名]
def reduce_fit(interface, state, label, inp):
    """
    Function joins all partially calculated matrices ETE and ETDe, aggregates them and it calculates final parameters.
    """
    import numpy as np

    out = interface.output(0)
    sum_etde = 0
    sum_ete = [0 for _ in range(len(state["X_indices"]) + 1)]
    for key, value in inp:
        if key == "etde":
            sum_etde += value
        else:
            sum_ete[key] += value

    sum_ete += np.true_divide(np.eye(len(sum_ete)), state["nu"])
    out.add("params", np.linalg.lstsq(sum_ete, sum_etde)[0]) 
开发者ID:romanorac,项目名称:discomll,代码行数:19,代码来源:linear_svm.py

示例2: test_NotImplemented_not_returned

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import true_divide [as 别名]
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod,
            np.greater, np.greater_equal, np.less, np.less_equal,
            np.equal, np.not_equal]

        a = np.array('1')
        b = 1
        c = np.array([1., 2.])
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b)
            assert_raises(TypeError, f, c, a) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:21,代码来源:test_ufunc.py

示例3: test_NotImplemented_not_returned

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import true_divide [as 别名]
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 
开发者ID:abhisuri97,项目名称:auto-alt-text-lambda-api,代码行数:22,代码来源:test_ufunc.py

示例4: confusion_matrix

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import true_divide [as 别名]
def confusion_matrix(ap, r1, cam_p, nCam):
    ap_mat = np.zeros((nCam, nCam), np.float32)
    r1_mat = np.zeros((nCam, nCam), np.float32)
    count1 = np.zeros((nCam, nCam), np.float32) + 1e-5
    count2 = np.zeros((nCam, nCam), np.float32) + 1e-5

    for i_p, p_i in enumerate(cam_p):
        for cam_i in range(nCam):
            ap_mat[p_i, cam_i] += ap[i_p, cam_i]
            if ap[i_p, cam_i] != 0:
                count1[p_i, cam_i] += 1
            if r1[i_p, cam_i] >= 0:
                r1_mat[p_i, cam_i] += r1[i_p, cam_i]
                count2[p_i, cam_i] += 1

    ap_mat = np.true_divide(ap_mat, count1)
    r1_mat = np.true_divide(r1_mat, count2)
    return r1_mat, ap_mat 
开发者ID:yolomax,项目名称:person-reid-lib,代码行数:20,代码来源:eval_mars.py

示例5: fit_cube_param

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import true_divide [as 别名]
def fit_cube_param(vol_dim, cube_size, ita):
    dim = np.asarray(vol_dim)
    fold = dim / cube_size + ita
    ovlap = np.ceil(
        np.true_divide(
            (fold * cube_size - dim),
            (fold - 1)))  # dim+ita*cubesize-dim
    ovlap = ovlap.astype('int')
    # print( "ovlap:", str( ovlap ) )#[62 62 86]
    fold = np.ceil(np.true_divide((dim + (fold - 1) * ovlap), cube_size))
    fold = fold.astype('int')
    # print( "fold:", str( fold) ) fold: [8 8 6]
    return fold, ovlap


# decompose volume into list of cubes 
开发者ID:JohnleeHIT,项目名称:Brats2019,代码行数:18,代码来源:utils.py

示例6: true_divide

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import true_divide [as 别名]
def true_divide(x1, x2):
  def _avoid_float64(x1, x2):
    if x1.dtype == x2.dtype and x1.dtype in (tf.int32, tf.int64):
      x1 = tf.cast(x1, dtype=tf.float32)
      x2 = tf.cast(x2, dtype=tf.float32)
    return x1, x2

  def f(x1, x2):
    if x1.dtype == tf.bool:
      assert x2.dtype == tf.bool
      float_ = dtypes.default_float_type()
      x1 = tf.cast(x1, float_)
      x2 = tf.cast(x2, float_)
    if not dtypes.is_allow_float64():
      # tf.math.truediv in Python3 produces float64 when both inputs are int32
      # or int64. We want to avoid that when is_allow_float64() is False.
      x1, x2 = _avoid_float64(x1, x2)
    return tf.math.truediv(x1, x2)
  return _bin_op(f, x1, x2) 
开发者ID:google,项目名称:trax,代码行数:21,代码来源:math_ops.py

示例7: f1_score_from_stats

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import true_divide [as 别名]
def f1_score_from_stats(tp, fp, fn, average='micro'):
    assert len(tp) == len(fp)
    assert len(fp) == len(fn)

    if average not in set(['micro', 'macro']):
        raise ValueError("Specify micro or macro")

    if average == 'micro':
        f1 = 2*numpy.sum(tp) / \
            float(2*numpy.sum(tp) + numpy.sum(fp) + numpy.sum(fn))

    elif average == 'macro':

        def safe_div(a, b):
            """ ignore / 0, div0( [-1, 0, 1], 0 ) -> [0, 0, 0] """
            with numpy.errstate(divide='ignore', invalid='ignore'):
                c = numpy.true_divide(a, b)
            return c[numpy.isfinite(c)]

        f1 = numpy.mean(safe_div(2*tp, 2*tp + fp + fn))

    return f1 
开发者ID:QData,项目名称:LaMP,代码行数:24,代码来源:evals.py

示例8: testFloatBasic

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import true_divide [as 别名]
def testFloatBasic(self):
    x = np.linspace(-5, 20, 15).reshape(1, 3, 5).astype(np.float32)
    y = np.linspace(20, -5, 15).reshape(1, 3, 5).astype(np.float32)
    self._compareBoth(x, y, np.add, tf.add, also_compare_variables=True)
    self._compareBoth(x, y, np.subtract, tf.sub)
    self._compareBoth(x, y, np.multiply, tf.mul)
    self._compareBoth(x, y + 0.1, np.true_divide, tf.truediv)
    self._compareBoth(x, y + 0.1, np.floor_divide, tf.floordiv)
    self._compareBoth(x, y, np.add, _ADD)
    self._compareBoth(x, y, np.subtract, _SUB)
    self._compareBoth(x, y, np.multiply, _MUL)
    self._compareBoth(x, y + 0.1, np.true_divide, _TRUEDIV)
    self._compareBoth(x, y + 0.1, np.floor_divide, _FLOORDIV)
    try:
      from scipy import special  # pylint: disable=g-import-not-at-top
      a_pos_small = np.linspace(0.1, 2, 15).reshape(1, 3, 5).astype(np.float32)
      x_pos_small = np.linspace(0.1, 10, 15).reshape(1, 3, 5).astype(np.float32)
      self._compareBoth(a_pos_small, x_pos_small, special.gammainc, tf.igamma)
      self._compareBoth(a_pos_small, x_pos_small, special.gammaincc, tf.igammac)
      # Need x > 1
      self._compareBoth(x_pos_small + 1, a_pos_small, special.zeta, tf.zeta)
      n_small = np.arange(0, 15).reshape(1, 3, 5).astype(np.float32)
      self._compareBoth(n_small, x_pos_small, special.polygamma, tf.polygamma)
    except ImportError as e:
      tf.logging.warn("Cannot test special functions: %s" % str(e)) 
开发者ID:tobegit3hub,项目名称:deep_image_model,代码行数:27,代码来源:cwise_ops_test.py

示例9: testDoubleBasic

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import true_divide [as 别名]
def testDoubleBasic(self):
    x = np.linspace(-5, 20, 15).reshape(1, 3, 5).astype(np.float64)
    y = np.linspace(20, -5, 15).reshape(1, 3, 5).astype(np.float64)
    self._compareBoth(x, y, np.add, tf.add)
    self._compareBoth(x, y, np.subtract, tf.sub)
    self._compareBoth(x, y, np.multiply, tf.mul)
    self._compareBoth(x, y + 0.1, np.true_divide, tf.truediv)
    self._compareBoth(x, y + 0.1, np.floor_divide, tf.floordiv)
    self._compareBoth(x, y, np.add, _ADD)
    self._compareBoth(x, y, np.subtract, _SUB)
    self._compareBoth(x, y, np.multiply, _MUL)
    self._compareBoth(x, y + 0.1, np.true_divide, _TRUEDIV)
    self._compareBoth(x, y + 0.1, np.floor_divide, _FLOORDIV)
    try:
      from scipy import special  # pylint: disable=g-import-not-at-top
      a_pos_small = np.linspace(0.1, 2, 15).reshape(1, 3, 5).astype(np.float32)
      x_pos_small = np.linspace(0.1, 10, 15).reshape(1, 3, 5).astype(np.float32)
      self._compareBoth(a_pos_small, x_pos_small, special.gammainc, tf.igamma)
      self._compareBoth(a_pos_small, x_pos_small, special.gammaincc, tf.igammac)
    except ImportError as e:
      tf.logging.warn("Cannot test special functions: %s" % str(e)) 
开发者ID:tobegit3hub,项目名称:deep_image_model,代码行数:23,代码来源:cwise_ops_test.py

示例10: testInt32Basic

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import true_divide [as 别名]
def testInt32Basic(self):
    x = np.arange(1, 13, 2).reshape(1, 3, 2).astype(np.int32)
    y = np.arange(1, 7, 1).reshape(1, 3, 2).astype(np.int32)
    self._compareBoth(x, y, np.add, tf.add)
    self._compareBoth(x, y, np.subtract, tf.sub)
    self._compareBoth(x, y, np.multiply, tf.mul)
    self._compareBoth(x, y, np.true_divide, tf.truediv)
    self._compareBoth(x, y, np.floor_divide, tf.floordiv)
    self._compareBoth(x, y, np.mod, tf.mod)
    self._compareBoth(x, y, np.add, _ADD)
    self._compareBoth(x, y, np.subtract, _SUB)
    self._compareBoth(x, y, np.multiply, _MUL)
    self._compareBoth(x, y, np.true_divide, _TRUEDIV)
    self._compareBoth(x, y, np.floor_divide, _FLOORDIV)
    self._compareBoth(x, y, np.mod, _MOD)
    # _compareBoth tests on GPU only for floating point types, so test
    # _MOD for int32 on GPU by calling _compareGpu
    self._compareGpu(x, y, np.mod, _MOD) 
开发者ID:tobegit3hub,项目名称:deep_image_model,代码行数:20,代码来源:cwise_ops_test.py

示例11: h

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import true_divide [as 别名]
def h(values):
    """
    Function calculates entropy.

    values: list of integers
    """
    ent = np.true_divide(values, np.sum(values))
    return -np.sum(np.multiply(ent, np.log2(ent))) 
开发者ID:romanorac,项目名称:discomll,代码行数:10,代码来源:measures.py

示例12: info_gain_numeric

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import true_divide [as 别名]
def info_gain_numeric(x, y, accuracy):
    x_unique = list(np.unique(x))
    if len(x_unique) == 1:
        return None
    indices = x.argsort()  # sort numeric attribute
    x, y = x[indices], y[indices]  # save sorted features with sorted labels

    right_dist = np.bincount(y)
    dummy_class = np.array([len(right_dist)])
    class_indices = right_dist.nonzero()[0]
    right_dist = right_dist[class_indices]
    left_dist = np.zeros(len(class_indices))

    diffs = np.nonzero(y[:-1] != y[1:])[0] + 1  # different neighbor classes have value True
    if accuracy > 0:
        diffs = np.array([diffs[i] for i in range(1, len(diffs)) if diffs[i] - diffs[i - 1] > accuracy],
                         dtype=np.int32) if len(diffs) > 15 else diffs
    intervals = np.array((np.concatenate(([0], diffs[:-1])), diffs)).T
    if len(diffs) < 2:
        return None

    max_ig, max_i, max_j = 0, 0, 0
    prior_h = h(right_dist)  # calculate prior entropy

    for i, j in intervals:
        dist = np.bincount(np.concatenate((dummy_class, y[i:j])))[class_indices]
        left_dist += dist
        right_dist -= dist
        coef = np.true_divide((np.sum(left_dist), np.sum(right_dist)), len(y))
        ig = prior_h - np.dot(coef, [h(left_dist[left_dist.nonzero()]), h(right_dist[right_dist.nonzero()])])
        if ig > max_ig:
            max_ig, max_i, max_j = ig, i, j

    if x[max_i] == x[max_j]:
        ind = x_unique.index(x[max_i])
        mean = np.float32(np.mean((x_unique[1 if ind == 0 else ind - 1], x_unique[ind])))
    else:
        mean = np.float32(np.mean((x[max_i], x[max_j])))

    return float(max_ig), [mean, mean] 
开发者ID:romanorac,项目名称:discomll,代码行数:42,代码来源:measures.py

示例13: qgram_similarity

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import true_divide [as 别名]
def qgram_similarity(s1, s2, include_wb=True, ngram=(2, 2)):

    if len(s1) != len(s2):
        raise ValueError('Arrays or Series have to be same length.')

    if len(s1) == len(s2) == 0:
        return []

    # include word boundaries or not
    analyzer = 'char_wb' if include_wb is True else 'char'

    # prepare data
    data = s1.append(s2).fillna('')

    # The vectorizer
    vectorizer = CountVectorizer(
        analyzer=analyzer, strip_accents='unicode', ngram_range=ngram)

    vec_fit = vectorizer.fit_transform(data)

    def _metric_sparse_euclidean(u, v):

        match_ngrams = u.minimum(v).sum(axis=1)
        total_ngrams = np.maximum(u.sum(axis=1), v.sum(axis=1))

        # division by zero is not possible in our case, but 0/0 is possible.
        # Numpy raises a warning in that case.

        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            m = np.true_divide(match_ngrams, total_ngrams).A1

        return m

    return _metric_sparse_euclidean(vec_fit[:len(s1)], vec_fit[len(s1):]) 
开发者ID:J535D165,项目名称:recordlinkage,代码行数:37,代码来源:string.py

示例14: img_scaling

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import true_divide [as 别名]
def img_scaling(img, scale='0,1'):
        if scale == '0,1':
            try:
                img /= 255.
            except TypeError:  # ufunc 'true divide' output ~
                img = np.true_divide(img, 255.0, casting='unsafe')
        elif scale == '-1,1':
            try:
                img = (img / 127.5) - 1.
            except TypeError:
                img = np.true_divide(img, 127.5, casting='unsafe') - 1.
        else:
            raise ValueError("[-] Only '0,1' or '-1,1' please - (%s)" % scale)

        return img 
开发者ID:kozistr,项目名称:rcan-tensorflow,代码行数:17,代码来源:dataset.py

示例15: _hist_bin_doane

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import true_divide [as 别名]
def _hist_bin_doane(x, range):
    """
    Doane's histogram bin estimator.

    Improved version of Sturges' formula which works better for
    non-normal data. See
    stats.stackexchange.com/questions/55134/doanes-formula-for-histogram-binning

    Parameters
    ----------
    x : array_like
        Input data that is to be histogrammed, trimmed to range. May not
        be empty.

    Returns
    -------
    h : An estimate of the optimal bin width for the given data.
    """
    del range  # unused
    if x.size > 2:
        sg1 = np.sqrt(6.0 * (x.size - 2) / ((x.size + 1.0) * (x.size + 3)))
        sigma = np.std(x)
        if sigma > 0.0:
            # These three operations add up to
            # g1 = np.mean(((x - np.mean(x)) / sigma)**3)
            # but use only one temp array instead of three
            temp = x - np.mean(x)
            np.true_divide(temp, sigma, temp)
            np.power(temp, 3, temp)
            g1 = np.mean(temp)
            return x.ptp() / (1.0 + np.log2(x.size) +
                                    np.log2(1.0 + np.absolute(g1) / sg1))
    return 0.0 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:35,代码来源:histograms.py


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