當前位置: 首頁>>代碼示例>>Python>>正文


Python numpy.broadcast方法代碼示例

本文整理匯總了Python中numpy.broadcast方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.broadcast方法的具體用法?Python numpy.broadcast怎麽用?Python numpy.broadcast使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在numpy的用法示例。


在下文中一共展示了numpy.broadcast方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _broadcast_to

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import broadcast [as 別名]
def _broadcast_to(array, shape, subok, readonly):
    shape = tuple(shape) if np.iterable(shape) else (shape,)
    array = np.array(array, copy=False, subok=subok)
    if not shape and array.shape:
        raise ValueError('cannot broadcast a non-scalar to a scalar array')
    if any(size < 0 for size in shape):
        raise ValueError('all elements of broadcast shape must be non-'
                         'negative')
    needs_writeable = not readonly and array.flags.writeable
    extras = ['reduce_ok'] if needs_writeable else []
    op_flag = 'readwrite' if needs_writeable else 'readonly'
    broadcast = np.nditer(
        (array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras,
        op_flags=[op_flag], itershape=shape, order='C').itviews[0]
    result = _maybe_view_as_subclass(array, broadcast)
    if needs_writeable and not result.flags.writeable:
        result.flags.writeable = True
    return result 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:20,代碼來源:stride_tricks.py

示例2: _broadcast_to

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import broadcast [as 別名]
def _broadcast_to(array, shape, subok, readonly):
    shape = tuple(shape) if np.iterable(shape) else (shape,)
    array = np.array(array, copy=False, subok=subok)
    if not shape and array.shape:
        raise ValueError('cannot broadcast a non-scalar to a scalar array')
    if any(size < 0 for size in shape):
        raise ValueError('all elements of broadcast shape must be non-'
                         'negative')
    needs_writeable = not readonly and array.flags.writeable
    extras = ['reduce_ok'] if needs_writeable else []
    op_flag = 'readwrite' if needs_writeable else 'readonly'
    it = np.nditer(
        (array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras,
        op_flags=[op_flag], itershape=shape, order='C')
    with it:
        # never really has writebackifcopy semantics
        broadcast = it.itviews[0]
    result = _maybe_view_as_subclass(array, broadcast)
    if needs_writeable and not result.flags.writeable:
        result.flags.writeable = True
    return result 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:23,代碼來源:stride_tricks.py

示例3: _broadcast_shape

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import broadcast [as 別名]
def _broadcast_shape(*args):
    """Returns the shape of the arrays that would result from broadcasting the
    supplied arrays against each other.
    """
    if not args:
        return ()
    # use the old-iterator because np.nditer does not handle size 0 arrays
    # consistently
    b = np.broadcast(*args[:32])
    # unfortunately, it cannot handle 32 or more arguments directly
    for pos in range(32, len(args), 31):
        # ironically, np.broadcast does not properly handle np.broadcast
        # objects (it treats them as scalars)
        # use broadcasting to avoid allocating the full array
        b = broadcast_to(0, b.shape)
        b = np.broadcast(b, *args[pos:(pos + 31)])
    return b.shape 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:19,代碼來源:stride_tricks.py

示例4: _broadcast_shape

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import broadcast [as 別名]
def _broadcast_shape(*args):
    """Returns the shape of the ararys that would result from broadcasting the
    supplied arrays against each other.
    """
    if not args:
        raise ValueError('must provide at least one argument')
    # use the old-iterator because np.nditer does not handle size 0 arrays
    # consistently
    b = np.broadcast(*args[:32])
    # unfortunately, it cannot handle 32 or more arguments directly
    for pos in range(32, len(args), 31):
        # ironically, np.broadcast does not properly handle np.broadcast
        # objects (it treats them as scalars)
        # use broadcasting to avoid allocating the full array
        b = broadcast_to(0, b.shape)
        b = np.broadcast(b, *args[pos:(pos + 31)])
    return b.shape 
開發者ID:abhisuri97,項目名稱:auto-alt-text-lambda-api,代碼行數:19,代碼來源:stride_tricks.py

示例5: broadcast_shape

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import broadcast [as 別名]
def broadcast_shape(*shapes, **kwargs):
    """
    Similar to ``np.broadcast()`` but for shapes.
    Equivalent to ``np.broadcast(*map(np.empty, shapes)).shape``.
    :param tuple shapes: shapes of tensors.
    :param bool strict: whether to use extend-but-not-resize broadcasting.
    :returns: broadcasted shape
    :rtype: tuple
    :raises: ValueError
    """
    strict = kwargs.pop('strict', False)
    reversed_shape = []
    for shape in shapes:
        for i, size in enumerate(reversed(shape)):
            if i >= len(reversed_shape):
                reversed_shape.append(size)
            elif reversed_shape[i] == 1 and not strict:
                reversed_shape[i] = size
            elif reversed_shape[i] != size and (size != 1 or strict):
                raise ValueError('shape mismatch: objects cannot be broadcast to a single shape: {}'.format(
                    ' vs '.join(map(str, shapes))))
    return tuple(reversed(reversed_shape)) 
開發者ID:pyro-ppl,項目名稱:funsor,代碼行數:24,代碼來源:util.py

示例6: broadcastable

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import broadcast [as 別名]
def broadcastable(*names):
    """returns a function - this function takes a dict of args
    (should be used in _all validator)
    asserts that every array in that list is broadcastable
    """
    # todo - do we check whether these are numpy objs first?
    # cause you can write numpy funcs on lists sometimes
    import numpy as np

    def _broadcastable(all_args):
        arrs = [all_args[x] for x in names]
        try:
            np.broadcast(*arrs)
        except ValueError:
            raise ValidationError(
                "Cannot broadcast %s with shapes %s", names,
                [getattr(x, 'shape', 'no shape') for x in arrs])
    return _broadcastable 
開發者ID:hhuuggoo,項目名稱:thedoctor,代碼行數:20,代碼來源:validators.py

示例7: check_power_divergence

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import broadcast [as 別名]
def check_power_divergence(self, f_obs, f_exp, ddof, axis, lambda_,
                               expected_stat):
        f_obs = np.asarray(f_obs)
        if axis is None:
            num_obs = f_obs.size
        else:
            b = np.broadcast(f_obs, f_exp)
            num_obs = b.shape[axis]
        stat, p = stats.power_divergence(f_obs=f_obs, f_exp=f_exp, ddof=ddof,
                                         axis=axis, lambda_=lambda_)
        assert_allclose(stat, expected_stat)

        if lambda_ == 1 or lambda_ == "pearson":
            # Also test stats.chisquare.
            stat, p = stats.chisquare(f_obs=f_obs, f_exp=f_exp, ddof=ddof,
                                      axis=axis)
            assert_allclose(stat, expected_stat)

        ddof = np.asarray(ddof)
        expected_p = stats.chisqprob(expected_stat, num_obs - 1 - ddof)
        assert_allclose(p, expected_p) 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:23,代碼來源:test_stats.py

示例8: broadcast_shape

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import broadcast [as 別名]
def broadcast_shape(shp1, shp2):
    """Broadcast the shape of those arrays

    Parameters
    ----------
    shp1 : tuple
        shape of array 1
    shp2 : tuple
        shape of array 2

    Returns
    -------
    tuple
        shape resulting from broadcasting two arrays using numpy rules

    Raises
    ------
    ValueError
        Arrays cannot be broadcasted
    """
    try:
        return np.broadcast(np.empty(shp1), np.empty(shp2)).shape
    except ValueError:
        raise ValueError("Arrays cannot be broadcasted - %s and %s " % (str(shp1), str(shp2))) 
開發者ID:jgolebiowski,項目名稱:graphAttack,代碼行數:26,代碼來源:coreNode.py

示例9: expect_broadcast_shapes

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import broadcast [as 別名]
def expect_broadcast_shapes(*shape_types):
    """Checks if shapes can be broadcasted together.

    Args:
        shapes_types: Type-checked shapes of the arrays to broadcast.

    """
    shapes = [eval(s) for s in shape_types]
    error = None
    try:
        # simulate the shape calculation using zero-sized arrays
        numpy.broadcast(*[numpy.empty(s + (0,)) for s in shapes])
    except ValueError:
        msgs = ['cannot broadcast inputs of the following shapes:']
        for shape_type, shape in six.moves.zip(shape_types, shapes):
            msgs.append('{} = {}'.format(shape_type, shape))
        error = InvalidType('', '', msg='\n'.join(msgs))
    if error is not None:
        raise error 
開發者ID:chainer,項目名稱:chainer,代碼行數:21,代碼來源:type_check.py

示例10: broadcast_to

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import broadcast [as 別名]
def broadcast_to(array, shape, subok=False):
    """Broadcast an array to a new shape.

    Parameters
    ----------
    array : array_like
        The array to broadcast.
    shape : tuple
        The shape of the desired array.
    subok : bool, optional
        If True, then sub-classes will be passed-through, otherwise
        the returned array will be forced to be a base-class array (default).

    Returns
    -------
    broadcast : array
        A readonly view on the original array with the given shape. It is
        typically not contiguous. Furthermore, more than one element of a
        broadcasted array may refer to a single memory location.

    Raises
    ------
    ValueError
        If the array is not compatible with the new shape according to NumPy's
        broadcasting rules.

    Notes
    -----
    .. versionadded:: 1.10.0

    Examples
    --------
    >>> x = np.array([1, 2, 3])
    >>> np.broadcast_to(x, (3, 3))
    array([[1, 2, 3],
           [1, 2, 3],
           [1, 2, 3]])
    """
    return _broadcast_to(array, shape, subok=subok, readonly=True) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:41,代碼來源:stride_tricks.py

示例11: test_boolean_assignment_value_mismatch

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import broadcast [as 別名]
def test_boolean_assignment_value_mismatch(self):
        # A boolean assignment should fail when the shape of the values
        # cannot be broadcast to the subscription. (see also gh-3458)
        a = np.arange(4)

        def f(a, v):
            a[a > -1] = v

        assert_raises(ValueError, f, a, [])
        assert_raises(ValueError, f, a, [1, 2, 3])
        assert_raises(ValueError, f, a[:1], [1, 2, 3]) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:13,代碼來源:test_indexing.py

示例12: _compare_index_result

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import broadcast [as 別名]
def _compare_index_result(self, arr, index, mimic_get, no_copy):
        """Compare mimicked result to indexing result.
        """
        arr = arr.copy()
        indexed_arr = arr[index]
        assert_array_equal(indexed_arr, mimic_get)
        # Check if we got a view, unless its a 0-sized or 0-d array.
        # (then its not a view, and that does not matter)
        if indexed_arr.size != 0 and indexed_arr.ndim != 0:
            assert_(np.may_share_memory(indexed_arr, arr) == no_copy)
            # Check reference count of the original array
            if HAS_REFCOUNT:
                if no_copy:
                    # refcount increases by one:
                    assert_equal(sys.getrefcount(arr), 3)
                else:
                    assert_equal(sys.getrefcount(arr), 2)

        # Test non-broadcast setitem:
        b = arr.copy()
        b[index] = mimic_get + 1000
        if b.size == 0:
            return  # nothing to compare here...
        if no_copy and indexed_arr.ndim != 0:
            # change indexed_arr in-place to manipulate original:
            indexed_arr += 1000
            assert_array_equal(arr, b)
            return
        # Use the fact that the array is originally an arange:
        arr.flat[indexed_arr.ravel()] += 1000
        assert_array_equal(arr, b) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:33,代碼來源:test_indexing.py

示例13: test_broadcast_in_args

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import broadcast [as 別名]
def test_broadcast_in_args(self):
        # gh-5881
        arrs = [np.empty((6, 7)), np.empty((5, 6, 1)), np.empty((7,)),
                np.empty((5, 1, 7))]
        mits = [np.broadcast(*arrs),
                np.broadcast(np.broadcast(*arrs[:2]), np.broadcast(*arrs[2:])),
                np.broadcast(arrs[0], np.broadcast(*arrs[1:-1]), arrs[-1])]
        for mit in mits:
            assert_equal(mit.shape, (5, 6, 7))
            assert_equal(mit.ndim, 3)
            assert_equal(mit.nd, 3)
            assert_equal(mit.numiter, 4)
            for a, ia in zip(arrs, mit.iters):
                assert_(a is ia.base) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:16,代碼來源:test_numeric.py

示例14: test_broadcast_single_arg

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import broadcast [as 別名]
def test_broadcast_single_arg(self):
        # gh-6899
        arrs = [np.empty((5, 6, 7))]
        mit = np.broadcast(*arrs)
        assert_equal(mit.shape, (5, 6, 7))
        assert_equal(mit.ndim, 3)
        assert_equal(mit.nd, 3)
        assert_equal(mit.numiter, 1)
        assert_(arrs[0] is mit.iters[0].base) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:11,代碼來源:test_numeric.py

示例15: test_number_of_arguments

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import broadcast [as 別名]
def test_number_of_arguments(self):
        arr = np.empty((5,))
        for j in range(35):
            arrs = [arr] * j
            if j < 1 or j > 32:
                assert_raises(ValueError, np.broadcast, *arrs)
            else:
                mit = np.broadcast(*arrs)
                assert_equal(mit.numiter, j) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:11,代碼來源:test_numeric.py


注:本文中的numpy.broadcast方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。