Python cupy.sum() Examples

The following are 30 code examples of cupy.sum(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cupy , or try the search function .
Example #1
Source File: norms.py    From cupy with MIT License 6 votes vote down vote up
def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
    """Returns the sum along the diagonals of an array.

    It computes the sum along the diagonals at ``axis1`` and ``axis2``.

    Args:
        a (cupy.ndarray): Array to take trace.
        offset (int): Index of diagonals. Zero indicates the main diagonal, a
            positive value an upper diagonal, and a negative value a lower
            diagonal.
        axis1 (int): The first axis along which the trace is taken.
        axis2 (int): The second axis along which the trace is taken.
        dtype: Data type specifier of the output.
        out (cupy.ndarray): Output array.

    Returns:
        cupy.ndarray: The trace of ``a`` along axes ``(axis1, axis2)``.

    .. seealso:: :func:`numpy.trace`

    """
    # TODO(okuta): check type
    return a.trace(offset, axis1, axis2, dtype, out) 
Example #2
Source File: norms.py    From cupy with MIT License 6 votes vote down vote up
def matrix_rank(M, tol=None):
    """Return matrix rank of array using SVD method

    Args:
        M (cupy.ndarray): Input array. Its `ndim` must be less than or equal to
            2.
        tol (None or float): Threshold of singular value of `M`.
            When `tol` is `None`, and `eps` is the epsilon value for datatype
            of `M`, then `tol` is set to `S.max() * max(M.shape) * eps`,
            where `S` is the singular value of `M`.
            It obeys :func:`numpy.linalg.matrix_rank`.

    Returns:
        cupy.ndarray: Rank of `M`.

    .. seealso:: :func:`numpy.linalg.matrix_rank`
    """
    if M.ndim < 2:
        return (M != 0).any().astype(int)
    S = decomposition.svd(M, compute_uv=False)
    if tol is None:
        tol = (S.max(axis=-1, keepdims=True) * max(M.shape[-2:]) *
               numpy.finfo(S.dtype).eps)
    return (S > tol).sum(axis=-1, dtype=numpy.intp) 
Example #3
Source File: sumprod.py    From cupy with MIT License 6 votes vote down vote up
def cumsum(a, axis=None, dtype=None, out=None):
    """Returns the cumulative sum of an array along a given axis.

    Args:
        a (cupy.ndarray): Input array.
        axis (int): Axis along which the cumulative sum is taken. If it is not
            specified, the input is flattened.
        dtype: Data type specifier.
        out (cupy.ndarray): Output array.

    Returns:
        cupy.ndarray: The result array.

    .. seealso:: :func:`numpy.cumsum`

    """
    return _math.scan_core(a, axis, _math.scan_op.SCAN_SUM, dtype, out) 
Example #4
Source File: test_cbpdn.py    From sporco with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_11(self):
        N = 63
        M = 4
        Nd = 8
        D = cp.random.randn(Nd, Nd, M)
        X0 = cp.zeros((N, N, M))
        xr = cp.random.randn(N, N, M)
        xp = cp.abs(xr) > 3
        X0[xp] = cp.random.randn(X0[xp].size)
        S = cp.sum(ifftn(fftn(D, (N, N), (0, 1)) *
                         fftn(X0, None, (0, 1)), None, (0, 1)).real,
                   axis=2)
        lmbda = 1e-2
        L = 1e3
        opt = cbpdn.ConvBPDN.Options({'Verbose': False, 'MaxMainIter': 2000,
                                      'RelStopTol': 1e-9, 'L': L,
                                      'BackTrack': {'Enabled': False}})
        b = cbpdn.ConvBPDN(D, S, lmbda, opt)
        b.solve()
        X1 = b.X.squeeze()
        assert rrs(X0, X1) < 5e-4
        Sr = b.reconstruct().squeeze()
        assert rrs(S, Sr) < 2e-4 
Example #5
Source File: test_cbpdn.py    From sporco with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_10(self):
        N = 64
        M = 4
        Nd = 8
        D = cp.random.randn(Nd, Nd, M)
        X0 = cp.zeros((N, N, M))
        xr = cp.random.randn(N, N, M)
        xp = cp.abs(xr) > 3
        X0[xp] = cp.random.randn(X0[xp].size)
        S = cp.sum(ifftn(fftn(D, (N, N), (0, 1)) *
                            fftn(X0, None, (0, 1)), None, (0, 1)).real,
                   axis=2)
        lmbda = 1e-2
        L = 1e3
        opt = cbpdn.ConvBPDN.Options({'Verbose': False, 'MaxMainIter': 2000,
                                      'RelStopTol': 1e-9, 'L': L,
                                      'BackTrack': {'Enabled': False}})
        b = cbpdn.ConvBPDN(D, S, lmbda, opt)
        b.solve()
        X1 = b.X.squeeze()
        assert rrs(X0, X1) < 5e-4
        Sr = b.reconstruct().squeeze()
        assert rrs(S, Sr) < 3e-4 
Example #6
Source File: test_linalg.py    From sporco with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_14(self):
        rho = 1e-1
        N = 64
        M = 32
        C = 3
        K = 8
        D = signal.complex_randn(N, N, C, 1, M)
        X = signal.complex_randn(N, N, 1, K, M)
        S = cp.sum(D*X, axis=4, keepdims=True)

        Xop = lambda x: cp.sum(X * x, axis=4, keepdims=True)
        XHop = lambda x: cp.sum(cp.conj(X) * x, axis=3, keepdims=True)
        Z = (XHop(Xop(D)) + rho*D - XHop(S)) / rho
        Dslv = linalg.solvemdbi_rsm(X, rho, XHop(S) + rho*Z, 3)

        assert linalg.rrs(XHop(Xop(Dslv)) + rho*Dslv, XHop(S) + rho*Z) < 1e-11 
Example #7
Source File: generator.py    From cupy with MIT License 6 votes vote down vote up
def dirichlet(self, alpha, size=None, dtype=float):
        """Returns an array of samples drawn from the dirichlet distribution.

        .. seealso::
            :func:`cupy.random.dirichlet` for full documentation,
            :meth:`numpy.random.RandomState.dirichlet
            <numpy.random.mtrand.RandomState.dirichlet>`
        """
        alpha = cupy.asarray(alpha)
        if size is None:
            size = alpha.shape
        else:
            size += alpha.shape
        y = cupy.empty(shape=size, dtype=dtype)
        _kernels.standard_gamma_kernel(alpha, self._rk_seed, y)
        y /= y.sum(axis=-1, keepdims=True)
        self._update_seed(y.size)
        return y 
Example #8
Source File: test_linalg.py    From sporco with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_12(self):
        rho = 1e-1
        N = 32
        M = 16
        C = 3
        K = 8
        D = signal.complex_randn(N, N, C, 1, M)
        X = signal.complex_randn(N, N, 1, K, M)
        S = cp.sum(D*X, axis=4, keepdims=True)

        Xop = lambda x: cp.sum(X * x, axis=4, keepdims=True)
        XHop = lambda x: cp.sum(cp.conj(X)* x, axis=3, keepdims=True)
        Z = (XHop(Xop(D)) + rho*D - XHop(S)) / rho
        Dslv = linalg.solvemdbi_ism(X, rho, XHop(S) + rho*Z, 4, 3)

        assert linalg.rrs(XHop(Xop(Dslv)) + rho*Dslv, XHop(S) + rho*Z) < 1e-11 
Example #9
Source File: test_cbpdn.py    From sporco with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_10(self):
        N = 64
        M = 4
        Nd = 8
        D = cp.random.randn(Nd, Nd, M)
        X0 = cp.zeros((N, N, M))
        xr = cp.random.randn(N, N, M)
        xp = cp.abs(xr) > 3
        X0[xp] = cp.random.randn(X0[xp].size)
        S = cp.sum(fftconv(D, X0), axis=2)
        lmbda = 1e-4
        rho = 1e-1
        opt = cbpdn.ConvBPDN.Options({'Verbose': False, 'MaxMainIter': 500,
                                      'RelStopTol': 1e-3, 'rho': rho,
                                      'AutoRho': {'Enabled': False}})
        b = cbpdn.ConvBPDN(D, S, lmbda, opt)
        b.solve()
        X1 = b.Y.squeeze()
        assert rrs(X0, X1) < 5e-5
        Sr = b.reconstruct().squeeze()
        assert rrs(S, Sr) < 1e-4 
Example #10
Source File: test_cbpdn.py    From sporco with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_11(self):
        N = 63
        M = 4
        Nd = 8
        D = cp.random.randn(Nd, Nd, M)
        X0 = cp.zeros((N, N, M))
        xr = cp.random.randn(N, N, M)
        xp = cp.abs(xr) > 3
        X0[xp] = cp.random.randn(X0[xp].size)
        S = cp.sum(ifftn(fftn(D, (N, N), (0, 1)) *
                         fftn(X0, None, (0, 1)), None, (0, 1)).real,
                   axis=2)
        lmbda = 1e-4
        rho = 1e-1
        opt = cbpdn.ConvBPDN.Options({'Verbose': False, 'MaxMainIter': 500,
                                      'RelStopTol': 1e-3, 'rho': rho,
                                      'AutoRho': {'Enabled': False}})
        b = cbpdn.ConvBPDN(D, S, lmbda, opt)
        b.solve()
        X1 = b.Y.squeeze()
        assert rrs(X0, X1) < 5e-5
        Sr = b.reconstruct().squeeze()
        assert rrs(S, Sr) < 1e-4 
Example #11
Source File: test_linalg.py    From sporco with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_10(self):
        N = 32
        M = 16
        K = 8
        D = signal.complex_randn(N, N, 1, 1, M)
        X = signal.complex_randn(N, N, 1, K, M)
        S = cp.sum(D*X, axis=4, keepdims=True)
        d = 1e-1 * (cp.random.randn(N, N, 1, 1, M).astype('complex') +
            cp.random.randn(N, N, 1, 1, M).astype('complex') * 1.0j)
        Z = (D.conj()*cp.sum(D*X, axis=4, keepdims=True) +
             d*X - D.conj()*S) / d
        Xslv = linalg.solvedbd_sm(D, d, D.conj()*S + d*Z)
        assert linalg.rrs(D.conj()*cp.sum(D*Xslv, axis=4, keepdims=True) +
                          d*Xslv, D.conj()*S + d*Z) < 1e-11 
Example #12
Source File: spectralloss.py    From TSNetVocoder with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _overlapadd(self, F):
        N = len(F)
        F = F[:,:,:self.fl]
        X = cupy.sum(cupy.stack([cupy.hstack([cupy.zeros((N, i, 1), cupy.float32), F[:,:,i:i+1], cupy.zeros((N, self.fl-1-i, 1), cupy.float32)]) for i in range(self.fl)]), axis=0)
        return X 
Example #13
Source File: test_cbpdn.py    From sporco with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_22(self):
        N = 32
        M = 4
        Nd = 8
        D = cp.random.randn(Nd, Nd, M)
        D /= cp.sqrt(cp.sum(D**2, axis=(0, 1)))
        X0 = cp.zeros((N, N, M))
        xr = cp.random.randn(N, N, M)
        xp = cp.abs(xr) > 3
        X0[xp] = cp.random.randn(X0[xp].size)
        S = cp.sum(fftconv(D, X0), axis=2)
        lmbda = 1e-3
        opt = cbpdn.ConvBPDN.Options(
            {'Verbose': False, 'MaxMainIter': 500, 'RelStopTol': 1e-5,
             'rho': 5e-1, 'AutoRho': {'Enabled': False}})
        bp = cbpdn.ConvBPDN(D, S, lmbda, opt)
        Xp = bp.solve()
        epsilon = cp.linalg.norm(bp.reconstruct(Xp).squeeze() - S)
        opt = cbpdn.ConvMinL1InL2Ball.Options(
            {'Verbose': False, 'MaxMainIter': 500, 'RelStopTol': 1e-5,
             'rho': 2e2, 'RelaxParam': 1.0, 'AutoRho': {'Enabled': False}})
        bc = cbpdn.ConvMinL1InL2Ball(D, S, epsilon=epsilon, opt=opt)
        Xc = bc.solve()
        assert cp.linalg.norm(Xp - Xc) / cp.linalg.norm(Xp) < 1e-3
        assert cp.abs(cp.linalg.norm(Xp.ravel(), 1) -
                      cp.linalg.norm(Xc.ravel(), 1)) < 1e-3 
Example #14
Source File: test_linalg.py    From sporco with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_09(self):
        rho = 1e-1
        N = 32
        M = 16
        K = 8
        D = signal.complex_randn(N, N, 1, 1, M)
        X = signal.complex_randn(N, N, 1, K, M)
        S = cp.sum(D*X, axis=4, keepdims=True)
        Z = (D.conj()*cp.sum(D*X, axis=4, keepdims=True) + \
             rho*X - D.conj()*S) / rho
        Xslv = linalg.solvedbi_sm(D, rho, D.conj()*S + rho*Z)
        assert linalg.rrs(D.conj()*cp.sum(D*Xslv, axis=4, keepdims=True) +
                          rho * Xslv, D.conj() * S + rho*Z) < 1e-11 
Example #15
Source File: __init__.py    From dybm with Apache License 2.0 5 votes vote down vote up
def _rbf_kernel(x, y, gamma=None):
    xn, nx = x.shape
    _, ny = y.shape
    assert nx == ny, ('The number ({}) of columns of x must be the same as '
                      'the number ({}) of rows of y'.format(nx, ny))

    if gamma is None:
        gamma = 1.0 / xn

    xy = cupy.dot(x, y.transpose())
    x2 = (x * x).sum(axis=1)
    y2 = (y * y).sum(axis=1)

    return cupy.exp((x2[:, cupy.newaxis] - 2 * xy + y2) * -gamma) 
Example #16
Source File: test_linalg.py    From sporco with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_13(self):
        rho = 1e-1
        N = 32
        M = 16
        K = 8
        D = signal.complex_randn(N, N, 1, 1, M)
        X = signal.complex_randn(N, N, 1, K, M)
        S = cp.sum(D*X, axis=4, keepdims=True)

        Xop = lambda x: cp.sum(X * x, axis=4, keepdims=True)
        XHop = lambda x: cp.sum(cp.conj(X) * x, axis=3, keepdims=True)
        Z = (XHop(Xop(D)) + rho*D - XHop(S)) / rho
        Dslv = linalg.solvemdbi_rsm(X, rho, XHop(S) + rho*Z, 3)

        assert linalg.rrs(XHop(Xop(Dslv)) + rho*Dslv, XHop(S) + rho*Z) < 1e-11 
Example #17
Source File: cupy.py    From chainladder-python with Mozilla Public License 2.0 5 votes vote down vote up
def nansum(a, *args, **kwargs):
    """ For cupy v0.6.0 compatibility """
    return cp.sum(cp.nan_to_num(a), *args, **kwargs) 
Example #18
Source File: cupy.py    From chainladder-python with Mozilla Public License 2.0 5 votes vote down vote up
def nanmean(a, *args, **kwargs):
    """ For cupy v0.6.0 compatibility """
    return cp.sum(cp.nan_to_num(a), *args, **kwargs) / \
           cp.sum(~cp.isnan(a), *args, **kwargs) 
Example #19
Source File: test_reduction.py    From cupy with MIT License 5 votes vote down vote up
def test_sum_axis(self, xp):
        return lambda x: cupy.sum(x, self.axis) 
Example #20
Source File: sumprod.py    From cupy with MIT License 5 votes vote down vote up
def nansum(a, axis=None, dtype=None, out=None, keepdims=False):
    """Returns the sum of an array along given axes treating Not a Numbers
    (NaNs) as zero.

    Args:
        a (cupy.ndarray): Array to take sum.
        axis (int or sequence of ints): Axes along which the sum is taken.
        dtype: Data type specifier.
        out (cupy.ndarray): Output array.
        keepdims (bool): If ``True``, the specified axes are remained as axes
            of length one.

    Returns:
        cupy.ndarray: The result array.

    .. seealso:: :func:`numpy.nansum`

    """
    if _fusion_thread_local.is_fusing():
        if keepdims:
            raise NotImplementedError(
                'cupy.nansum does not support `keepdims` in fusion yet.')
        if a.dtype in 'FD':
            func = _math._nansum_complex_dtype
        elif dtype is None:
            func = _math._nansum_auto_dtype
        else:
            func = _math._nansum_keep_dtype
        return _fusion_thread_local.call_reduction(
            func, a, axis=axis, dtype=dtype, out=out)

    # TODO(okuta): check type
    return _math._nansum(a, axis, dtype, out, keepdims) 
Example #21
Source File: test_reduction.py    From cupy with MIT License 5 votes vote down vote up
def test_multistage_reductions(self, xp):
        return lambda x: x.prod(axis=(-1, 1)).sum(axis=(0, 1)) 
Example #22
Source File: test_reduction.py    From cupy with MIT License 5 votes vote down vote up
def test_multistage_reductions_and_elementwise(self, xp):
        return lambda x: (xp.sqrt(x).prod(axis=0) + x).sum(axis=1) * 2 
Example #23
Source File: test_reduction.py    From cupy with MIT License 5 votes vote down vote up
def test_multistage_reductions(self, xp):
        return lambda x: x.prod(axis=1).sum(axis=1) 
Example #24
Source File: test_reduction.py    From cupy with MIT License 5 votes vote down vote up
def test_two_reductions_and_elementwise(self, xp):
        return lambda x, y: x.sum(self.axis1) + y.sum(self.axis2) 
Example #25
Source File: test_reduction.py    From cupy with MIT License 5 votes vote down vote up
def test_two_distinct_reductions(self, xp):
        return lambda x, y: (x.sum(self.axis1), y.sum(self.axis2)) 
Example #26
Source File: test_reduction.py    From cupy with MIT License 5 votes vote down vote up
def test_premap_postmap(self, xp):
        return lambda x, y: xp.sum(xp.sqrt(x) + y, self.axis) * 2 + y

    # TODO(asi1024): Uncomment after replace fusion implementaiton.
    # @fusion_utils.check_fusion()
    # def test_premap_inplace(self, xp):
    #     def impl(x, y):
    #         x += 2
    #         y += x
    #         return xp.sum(y, self.axis)
    #     return impl 
Example #27
Source File: test_reduction.py    From cupy with MIT License 5 votes vote down vote up
def test_postmap_two_arrays(self, xp):
        return lambda x, y: xp.sum(x, self.axis) + y 
Example #28
Source File: test_reduction.py    From cupy with MIT License 5 votes vote down vote up
def test_postmap_one_array(self, xp):
        return lambda x, y: xp.sum(x, self.axis) + 3 
Example #29
Source File: test_reduction.py    From cupy with MIT License 5 votes vote down vote up
def test_premap_two_arrays(self, xp):
        return lambda x, y: xp.sum(x + y, self.axis) 
Example #30
Source File: test_reduction.py    From cupy with MIT License 5 votes vote down vote up
def test_premap_one_array(self, xp):
        return lambda x, y: xp.sum(x * 3, self.axis)