當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。