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


Python numpy.full_like方法代码示例

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


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

示例1: as_strided_writeable

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import full_like [as 别名]
def as_strided_writeable():
    arr = np.ones(10)
    view = as_strided(arr, writeable=False)
    assert_(not view.flags.writeable)

    # Check that writeable also is fine:
    view = as_strided(arr, writeable=True)
    assert_(view.flags.writeable)
    view[...] = 3
    assert_array_equal(arr, np.full_like(arr, 3))

    # Test that things do not break down for readonly:
    arr.flags.writeable = False
    view = as_strided(arr, writeable=False)
    view = as_strided(arr, writeable=True)
    assert_(not view.flags.writeable) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:18,代码来源:test_stride_tricks.py

示例2: get_C_hat_transpose

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import full_like [as 别名]
def get_C_hat_transpose():
    probs = []
    net.eval()
    for batch_idx, (data, target) in enumerate(train_gold_deterministic_loader):
        # we subtract 10 because we added 10 to gold so we could identify which example is gold in train_phase2
        data, target = torch.autograd.Variable(data.cuda(), volatile=True),\
                       torch.autograd.Variable((target - num_classes).cuda(), volatile=True)

        # forward
        output = net(data)
        pred = F.softmax(output)
        probs.extend(list(pred.data.cpu().numpy()))

    probs = np.array(probs, dtype=np.float32)
    preds = np.argmax(probs, axis=1)
    C_hat = np.zeros([num_classes, num_classes])
    for i in range(len(train_data_gold.train_labels)):
        C_hat[int(np.rint(train_data_gold.train_labels[i] - num_classes)), preds[i]] += 1

    C_hat /= (np.sum(C_hat, axis=1, keepdims=True) + 1e-7)
    C_hat = C_hat * 0.99 + np.full_like(C_hat, 1/num_classes) * 0.01  # smoothing

    return C_hat.T.astype(np.float32) 
开发者ID:mmazeika,项目名称:glc,代码行数:25,代码来源:train_confusion.py

示例3: decode

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import full_like [as 别名]
def decode(self, buf, out=None):

        # normalise input
        enc = ensure_ndarray(buf).view(self.astype)

        # flatten to simplify implementation
        enc = enc.reshape(-1, order='A')

        # setup output
        dec = np.full_like(enc, fill_value='', dtype=self.dtype)

        # apply decoding
        for i, l in enumerate(self.labels):
            dec[enc == (i + 1)] = l

        # handle output
        dec = ndarray_copy(dec, out)

        return dec 
开发者ID:zarr-developers,项目名称:numcodecs,代码行数:21,代码来源:categorize.py

示例4: _is_feasible

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import full_like [as 别名]
def _is_feasible(kind, enforce_feasibility, f0):
    keyword = kind[0]
    if keyword == "equals":
        lb = np.asarray(kind[1], dtype=float)
        ub = np.asarray(kind[1], dtype=float)
    elif keyword == "greater":
        lb = np.asarray(kind[1], dtype=float)
        ub = np.full_like(lb, np.inf, dtype=float)
    elif keyword == "less":
        ub = np.asarray(kind[1], dtype=float)
        lb = np.full_like(ub, -np.inf, dtype=float)
    elif keyword == "interval":
        lb = np.asarray(kind[1], dtype=float)
        ub = np.asarray(kind[2], dtype=float)
    else:
        raise RuntimeError("Never be here.")

    return ((lb[enforce_feasibility] <= f0[enforce_feasibility]).all()
            and (f0[enforce_feasibility] <= ub[enforce_feasibility]).all()) 
开发者ID:antonior92,项目名称:ip-nonlinear-solver,代码行数:21,代码来源:_constraints.py

示例5: estimate_mem_use

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import full_like [as 别名]
def estimate_mem_use(targets, costs):
    """Estimate memory usage in GB, probably not very accurate.

    Parameters
    ----------
    targets : numpy array
        2D array of targets.
    costs : numpy array
        2D array of costs.

    Returns
    -------
    est_mem : float
        Estimated memory requirement in GB.
    """

    # make sure these match the ones used in optimise below
    visited = np.zeros_like(targets, dtype=np.int8)
    dist = np.full_like(costs, np.nan, dtype=np.float32)
    prev = np.full_like(costs, np.nan, dtype=object)

    est_mem_arr = [targets, costs, visited, dist, prev]
    est_mem = len(pickle.dumps(est_mem_arr, -1))

    return est_mem / 1e9 
开发者ID:carderne,项目名称:gridfinder,代码行数:27,代码来源:gridfinder.py

示例6: test_power_transformer_nans

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import full_like [as 别名]
def test_power_transformer_nans(method):
    # Make sure lambda estimation is not influenced by NaN values
    # and that transform() supports NaN silently

    X = np.abs(X_1col)
    pt = PowerTransformer(method=method)
    pt.fit(X)
    lmbda_no_nans = pt.lambdas_[0]

    # concat nans at the end and check lambda stays the same
    X = np.concatenate([X, np.full_like(X, np.nan)])
    X = shuffle(X, random_state=0)

    pt.fit(X)
    lmbda_nans = pt.lambdas_[0]

    assert_almost_equal(lmbda_no_nans, lmbda_nans, decimal=5)

    X_trans = pt.transform(X)
    assert_array_equal(np.isnan(X_trans), np.isnan(X)) 
开发者ID:PacktPublishing,项目名称:Mastering-Elasticsearch-7.0,代码行数:22,代码来源:test_data.py

示例7: windowed_pass_2d

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import full_like [as 别名]
def windowed_pass_2d(x, win):
    """
    The same as windowed pass, but explicitly
    iterates over the `value()` return array
    and allocates it in the `result`.

    This allows 2-dimensional arrays to be returned
    from `value()` functions, before we support
    the behaviour properly using AST transforms.

    This allows for extremely fast iteration
    for items such as OLS, and at the same time
    calculating t-stats / r^2.
    """
    result = np.full_like(x, np.nan)
    for i in range(win, x.shape[0]+1):
        res = value(x[i-win:i])
        for j, j_val in enumerate(res):
            result[i-1, j] = j_val
    return result 
开发者ID:fastats,项目名称:fastats,代码行数:22,代码来源:windowed_pass.py

示例8: full_like

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import full_like [as 别名]
def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None):  # pylint: disable=missing-docstring,redefined-outer-name
  """order, subok and shape arguments mustn't be changed."""
  if order != 'K':
    raise ValueError('Non-standard orders are not supported.')
  if not subok:
    raise ValueError('subok being False is not supported.')
  if shape:
    raise ValueError('Overriding the shape is not supported.')

  a = asarray(a).data
  dtype = dtype or utils.result_type(a)
  fill_value = asarray(fill_value, dtype=dtype)
  return arrays_lib.tensor_to_ndarray(
      tf.broadcast_to(fill_value.data, tf.shape(a)))


# TODO(wangpeng): investigate whether we can make `copy` default to False.
# TODO(wangpeng): utils.np_doc can't handle np.array because np.array is a
#   builtin function. Make utils.np_doc support builtin functions. 
开发者ID:google,项目名称:trax,代码行数:21,代码来源:array_ops.py

示例9: testFullLike

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import full_like [as 别名]
def testFullLike(self):
    # List of 2-tuples of fill value and shape.
    data = [
        (5, ()),
        (5, (7,)),
        (5., (7,)),
        ([5, 8], (2,)),
        ([5, 8], (3, 2)),
        ([[5], [8]], (2, 3)),
        ([[5], [8]], (3, 2, 5)),
        ([[5.], [8.]], (3, 2, 5)),
    ]
    zeros_builders = [array_ops.zeros, np.zeros]
    for f, s in data:
      for fn1, fn2, arr_dtype in itertools.product(
          self.array_transforms, zeros_builders, self.all_types):
        fill_value = fn1(f)
        arr = fn2(s, arr_dtype)
        self.match(
            array_ops.full_like(arr, fill_value), np.full_like(arr, fill_value))
        for dtype in self.all_types:
          self.match(
              array_ops.full_like(arr, fill_value, dtype=dtype),
              np.full_like(arr, fill_value, dtype=dtype)) 
开发者ID:google,项目名称:trax,代码行数:26,代码来源:array_ops_test.py

示例10: setLOS

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import full_like [as 别名]
def setLOS(self, phi, theta):
        """Set the sandbox's LOS vector

        :param phi: phi in degree
        :type phi: int
        :param theta: theta in degree
        :type theta: int
        """
        if self.reference is not None:
            self._log.warning('Cannot change a referenced model!')
            return

        self._log.debug(
            'Changing model LOS to %d phi and %d theta', phi, theta)

        self.theta = num.full_like(self.theta, theta*r2d)
        self.phi = num.full_like(self.phi, phi*r2d)
        self.frame.updateExtent()

        self._clearModel()
        self.evChanged.notify() 
开发者ID:pyrocko,项目名称:kite,代码行数:23,代码来源:sandbox_scene.py

示例11: test_arrays_multi

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import full_like [as 别名]
def test_arrays_multi():
    apparent_zenith = np.array([[10, 10], [10, 10]])
    apparent_azimuth = np.array([[180, 180], [180, 180]])
    # singleaxis should fail for num dim > 1
    with pytest.raises(ValueError):
        tracking.singleaxis(apparent_zenith, apparent_azimuth,
                            axis_tilt=0, axis_azimuth=0,
                            max_angle=90, backtrack=True,
                            gcr=2.0/7.0)
    # uncomment if we ever get singleaxis to support num dim > 1 arrays
    # assert isinstance(tracker_data, dict)
    # expect = {'tracker_theta': np.full_like(apparent_zenith, 0),
    #           'aoi': np.full_like(apparent_zenith, 10),
    #           'surface_azimuth': np.full_like(apparent_zenith, 90),
    #           'surface_tilt': np.full_like(apparent_zenith, 0)}
    # for k, v in expect.items():
    #     assert_allclose(tracker_data[k], v) 
开发者ID:pvlib,项目名称:pvlib-python,代码行数:19,代码来源:test_tracking.py

示例12: test_old_wminkowski

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import full_like [as 别名]
def test_old_wminkowski(self):
        with suppress_warnings() as wrn:
            wrn.filter(message="`wminkowski` is deprecated")
            w = np.array([1.0, 2.0, 0.5])
            for x, y in self.cases:
                dist1 = old_wminkowski(x, y, p=1, w=w)
                assert_almost_equal(dist1, 3.0)
                dist1p5 = old_wminkowski(x, y, p=1.5, w=w)
                assert_almost_equal(dist1p5, (2.0**1.5+1.0)**(2./3))
                dist2 = old_wminkowski(x, y, p=2, w=w)
                assert_almost_equal(dist2, np.sqrt(5))

            # test weights Issue #7893
            arr = np.arange(4)
            w = np.full_like(arr, 4)
            assert_almost_equal(old_wminkowski(arr, arr + 1, p=2, w=w), 8.0)
            assert_almost_equal(wminkowski(arr, arr + 1, p=2, w=w), 4.0) 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:19,代码来源:test_distance.py

示例13: _do

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import full_like [as 别名]
def _do(self, problem, X, **kwargs):

        # The input of has the following shape (n_parents, n_matings, n_var)
        _, n_matings, n_var = X.shape

        # The output owith the shape (n_offsprings, n_matings, n_var)
        # Because there the number of parents and offsprings are equal it keeps the shape of X
        Y = np.full_like(X, None, dtype=np.object)

        # for each mating provided
        for k in range(n_matings):

            # get the first and the second parent
            a, b = X[0, k, 0], X[1, k, 0]

            # prepare the offsprings
            off_a = ["_"] * problem.n_characters
            off_b = ["_"] * problem.n_characters

            for i in range(problem.n_characters):
                if np.random.random() < 0.5:
                    off_a[i] = a[i]
                    off_b[i] = b[i]
                else:
                    off_a[i] = b[i]
                    off_b[i] = a[i]

            # join the character list and set the output
            Y[0, k, 0], Y[1, k, 0] = "".join(off_a), "".join(off_b)

        return Y 
开发者ID:msu-coinlab,项目名称:pymoo,代码行数:33,代码来源:usage_nsga2_custom.py

示例14: _assert_array_in_range

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import full_like [as 别名]
def _assert_array_in_range(array, low, high):
    assert isinstance(array, np.ndarray)
    assert low < high
    np.testing.assert_array_less(np.full_like(array, low), array)
    np.testing.assert_array_less(array, np.full_like(array, high)) 
开发者ID:chainer,项目名称:chainerrl,代码行数:7,代码来源:test_distribution.py

示例15: zdp

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import full_like [as 别名]
def zdp(z_h, z_v):
    """
    Reflectivity difference [dB].

    From Rinehart (1997), Eqn 10.3

    Parameters
    ----------
    z_h : float
        Horizontal reflectivity [mm^6/m^3]
    z_v : float
        Horizontal reflectivity [mm^6/m^3]

    Notes
    -----
    Ensure that both powers have the same units!

    Alternating horizontally and linearly polarized pulses are averaged.
    """
    zh = np.atleast_1d(z_h)
    zv = np.atleast_1d(z_v)
    if len(zh) != len(zv):
        raise ValueError('Input variables must be same length')
        return

    zdp = np.full_like(zh, np.nan)
    good = np.where(zh > zv)
    zdp[good] = 10.* np.log10(zh[good] - zv[good])
    return zdp 
开发者ID:nguy,项目名称:PyRadarMet,代码行数:31,代码来源:variables.py


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