Python cupy.ones() Examples

The following are 30 code examples of cupy.ones(). 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: gla_gpu.py    From Deep_VoiceChanger with MIT License 6 votes vote down vote up
def __init__(self, parallel, wave_len=254, wave_dif=64, buffer_size=5, loop_num=5, window=np.hanning(254)):
        self.wave_len = wave_len
        self.wave_dif = wave_dif
        self.buffer_size = buffer_size
        self.loop_num = loop_num
        self.parallel = parallel
        self.window = cp.array([window for _ in range(parallel)])

        self.wave_buf = cp.zeros((parallel, wave_len+wave_dif), dtype=float)
        self.overwrap_buf = cp.zeros((parallel, wave_dif*buffer_size+(wave_len-wave_dif)), dtype=float)
        self.spectrum_buffer = cp.ones((parallel, self.buffer_size, self.wave_len), dtype=complex)
        self.absolute_buffer = cp.ones((parallel, self.buffer_size, self.wave_len), dtype=complex)
        
        self.phase = cp.zeros((parallel, self.wave_len), dtype=complex)
        self.phase += cp.random.random((parallel, self.wave_len))-0.5 + cp.random.random((parallel, self.wave_len))*1j - 0.5j
        self.phase[self.phase == 0] = 1
        self.phase /= cp.abs(self.phase) 
Example #2
Source File: test_cudnn.py    From cupy with MIT License 6 votes vote down vote up
def setUp(self):
        self.layout = libcudnn.CUDNN_TENSOR_NHWC
        n = 16
        x_c, y_c = 64, 64
        x_h, x_w = 32, 32
        y_h, y_w = x_h // self.stride, x_w // self.stride
        self.pad = (self.ksize - 1) // 2
        if self.layout == libcudnn.CUDNN_TENSOR_NHWC:
            x_shape = (n, x_h, x_w, x_c)
            y_shape = (n, y_h, y_w, y_c)
            W_shape = (y_c, self.ksize, self.ksize, x_c)
        else:
            x_shape = (n, x_c, x_h, x_w)
            y_shape = (n, y_c, y_h, y_w)
            W_shape = (y_c, x_c, self.ksize, self.ksize)
        self.x = cupy.ones(x_shape, dtype=self.dtype)
        self.W = cupy.ones(W_shape, dtype=self.dtype)
        self.y = cupy.empty(y_shape, dtype=self.dtype)
        self.gx = cupy.empty(x_shape, dtype=self.dtype)
        self.gW = cupy.empty(W_shape, dtype=self.dtype)
        self.gy = cupy.ones(y_shape, dtype=self.dtype)
        self._workspace_size = cudnn.get_max_workspace_size()
        cudnn.set_max_workspace_size(0) 
Example #3
Source File: test_cbpdn.py    From sporco with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_30(self):
        N = 16
        Nd = 5
        M = 4
        D = cp.random.randn(Nd, Nd, M)
        s = cp.random.randn(N, N)
        w = cp.ones(s.shape)
        dt = cp.float32
        opt = cbpdn.ConvBPDN.Options(
            {'Verbose': False, 'MaxMainIter': 20, 'AutoRho': {'Enabled': True},
             'DataType': dt})
        lmbda = 1e-1
        b = cbpdn.AddMaskSim(cbpdn.ConvBPDN, D, s, w, lmbda, opt=opt)
        b.solve()
        assert b.cbpdn.X.dtype == dt
        assert b.cbpdn.Y.dtype == dt
        assert b.cbpdn.U.dtype == dt 
Example #4
Source File: test_ndarray_scatter.py    From cupy with MIT License 6 votes vote down vote up
def test_scatter_minmax_differnt_dtypes(self, src_dtype, dst_dtype):
        shape = (2, 3)
        a = cupy.zeros(shape, dtype=src_dtype)
        value = cupy.array(1, dtype=dst_dtype)
        slices = ([1, 1], slice(None))
        a.scatter_max(slices, value)
        numpy.testing.assert_almost_equal(
            a.get(),
            numpy.array([[0, 0, 0], [1, 1, 1]], dtype=src_dtype))

        a = cupy.ones(shape, dtype=src_dtype)
        value = cupy.array(0, dtype=dst_dtype)
        a.scatter_min(slices, value)
        numpy.testing.assert_almost_equal(
            a.get(),
            numpy.array([[1, 1, 1], [0, 0, 0]], dtype=src_dtype)) 
Example #5
Source File: test_ndarray_scatter.py    From cupy with MIT License 6 votes vote down vote up
def test_scatter_minmax_differnt_dtypes_mask(self, src_dtype, dst_dtype):
        shape = (2, 3)
        a = cupy.zeros(shape, dtype=src_dtype)
        value = cupy.array(1, dtype=dst_dtype)
        slices = (numpy.array([[True, False, False], [False, True, True]]))
        a.scatter_max(slices, value)
        numpy.testing.assert_almost_equal(
            a.get(),
            numpy.array([[1, 0, 0], [0, 1, 1]], dtype=src_dtype))

        a = cupy.ones(shape, dtype=src_dtype)
        value = cupy.array(0, dtype=dst_dtype)
        a.scatter_min(slices, value)
        numpy.testing.assert_almost_equal(
            a.get(),
            numpy.array([[0, 1, 1], [1, 0, 0]], dtype=src_dtype)) 
Example #6
Source File: test_rasterize.py    From neural_renderer with MIT License 5 votes vote down vote up
def test_backward_case1(self):
        """Backward if non-zero gradient is out of a face."""

        vertices = [
            [0.8, 0.8, 1.],
            [0.0, -0.5, 1.],
            [0.2, -0.4, 1.]]
        faces = [[0, 1, 2]]
        pxi = 35
        pyi = 25
        grad_ref = [
            [1.6725862, -0.26021874, 0.],
            [1.41986704, -1.64284933, 0.],
            [0., 0., 0.],
        ]

        renderer = neural_renderer.Renderer()
        renderer.image_size = 64
        renderer.anti_aliasing = False
        renderer.perspective = False
        renderer.light_intensity_ambient = 1.0
        renderer.light_intensity_directional = 0.0

        vertices = cp.array(vertices, 'float32')
        faces = cp.array(faces, 'int32')
        textures = cp.ones((faces.shape[0], 4, 4, 4, 3), 'float32')
        grad_ref = cp.array(grad_ref, 'float32')
        vertices, faces, textures, grad_ref = utils.to_minibatch((vertices, faces, textures, grad_ref))
        vertices = chainer.Variable(vertices)

        images = renderer.render(vertices, faces, textures)
        images = cf.mean(images, axis=1)
        loss = cf.sum(cf.absolute(images[:, pyi, pxi] - 1))
        loss.backward()

        chainer.testing.assert_allclose(vertices.grad, grad_ref, rtol=1e-2) 
Example #7
Source File: test_tvl2.py    From sporco with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_02(self):
        lmbda = 1e-1
        opt = tvl2.TVL2Deconv.Options(
            {'Verbose': False, 'gEvalY': False, 'MaxMainIter': 250})
        b = tvl2.TVL2Deconv(cp.ones((1)), self.D, lmbda, opt, axes=(0, 1, 2))
        X = b.solve()
        assert cp.abs(b.itstat[-1].ObjFun - 567.72425227) < 1e-3
        assert sm.mse(self.U, X) < 1e-3 
Example #8
Source File: test_rasterize.py    From neural_renderer with MIT License 5 votes vote down vote up
def test_backward_case2(self):
        """Backward if non-zero gradient is on a face."""

        vertices = [
            [0.8, 0.8, 1.],
            [-0.5, -0.8, 1.],
            [0.8, -0.8, 1.]]
        faces = [[0, 1, 2]]
        pyi = 40
        pxi = 50
        grad_ref = [
            [0.98646867, 1.04628897, 0.],
            [-1.03415668, - 0.10403691, 0.],
            [3.00094461, - 1.55173182, 0.],
        ]

        renderer = neural_renderer.Renderer()
        renderer.image_size = 64
        renderer.anti_aliasing = False
        renderer.perspective = False
        renderer.light_intensity_ambient = 1.0
        renderer.light_intensity_directional = 0.0

        vertices = cp.array(vertices, 'float32')
        faces = cp.array(faces, 'int32')
        textures = cp.ones((faces.shape[0], 4, 4, 4, 3), 'float32')
        grad_ref = cp.array(grad_ref, 'float32')
        vertices, faces, textures, grad_ref = utils.to_minibatch((vertices, faces, textures, grad_ref))
        vertices = chainer.Variable(vertices)

        images = renderer.render(vertices, faces, textures)
        images = cf.mean(images, axis=1)
        loss = cf.sum(cf.absolute(images[:, pyi, pxi]))
        loss.backward()

        grad_ref = cp.array(grad_ref, 'float32')
        chainer.testing.assert_allclose(vertices.grad, grad_ref, rtol=1e-2) 
Example #9
Source File: sample_space_model.py    From pyCFTrackers with MIT License 5 votes vote down vote up
def __init__(self, num_samples,config):
        self._num_samples = num_samples
        self.config=config
        if not gpu_config.use_gpu:
            self._distance_matrix = np.ones((num_samples, num_samples), dtype=np.float32) * np.inf
            self._gram_matrix = np.ones((num_samples, num_samples), dtype=np.float32) * np.inf
            self.prior_weights = np.zeros((num_samples, 1), dtype=np.float32)
        else:
            self._distance_matrix = cp.ones((num_samples, num_samples), dtype=cp.float32) * cp.inf
            self._gram_matrix = cp.ones((num_samples, num_samples), dtype=cp.float32) * cp.inf
            self.prior_weights = cp.zeros((num_samples, 1), dtype=cp.float32)
        # find the minimum allowed sample weight. samples are discarded if their weights become lower
        self.minimum_sample_weight = self.config.learning_rate * (1 - self.config.learning_rate) ** (2 * self.config.num_samples) 
Example #10
Source File: test_tvl2.py    From sporco with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_02(self):
        lmbda = 1e-1
        opt = tvl2.TVL2Deconv.Options(
            {'Verbose': False, 'gEvalY': False, 'MaxMainIter': 250})
        b = tvl2.TVL2Deconv(cp.ones((1)), self.D, lmbda, opt)
        X = b.solve()
        assert cp.abs(b.itstat[-1].ObjFun - 45.45958573088) < 1e-3
        assert sm.mse(self.U, X) < 1e-3 
Example #11
Source File: test_tvl2.py    From sporco with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_02(self):
        lmbda = 3
        try:
            b = tvl2.TVL2Deconv(cp.ones((1, )), self.D, lmbda)
            b.solve()
        except Exception as e:
            print(e)
            assert 0 
Example #12
Source File: test_tvl2.py    From sporco with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_06(self):
        lmbda = 3
        dt = cp.float32
        opt = tvl2.TVL2Deconv.Options(
            {'Verbose': False, 'MaxMainIter': 20, 'AutoRho':
             {'Enabled': True}, 'DataType': dt})
        b = tvl2.TVL2Deconv(cp.ones((1, )), self.D, lmbda, opt=opt)
        b.solve()
        assert b.X.dtype == dt
        assert b.Y.dtype == dt
        assert b.U.dtype == dt 
Example #13
Source File: test_tvl2.py    From sporco with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_07(self):
        lmbda = 3
        dt = cp.float64
        opt = tvl2.TVL2Deconv.Options(
            {'Verbose': False, 'MaxMainIter': 20, 'AutoRho':
             {'Enabled': True}, 'DataType': dt})
        b = tvl2.TVL2Deconv(cp.ones((1, )), self.D, lmbda, opt=opt)
        b.solve()
        assert b.X.dtype == dt
        assert b.Y.dtype == dt
        assert b.U.dtype == dt 
Example #14
Source File: test_tvl2.py    From sporco with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup_method(self, method):
        np.random.seed(12345)
        N = 64
        self.U = cp.ones((N, N))
        self.U[:, 0:(old_div(N, 2))] = -1
        self.V = 1e-1 * cp.asarray(np.random.randn(N, N))
        self.D = self.U + self.V 
Example #15
Source File: test_tvl2.py    From sporco with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup_method(self, method):
        np.random.seed(12345)
        N = 32
        self.U = cp.ones((N, N, N))
        self.U[:, 0:(old_div(N, 2)), :] = -1
        self.V = 1e-1 * cp.asarray(np.random.randn(N, N, N))
        self.D = self.U + self.V 
Example #16
Source File: test_cbpdn.py    From sporco with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_15(self):
        N = 16
        Nd = 5
        M = 4
        D = cp.random.randn(Nd, Nd, M)
        s = cp.random.randn(N, N)
        w = cp.ones(s.shape)
        lmbda = 1e-1
        try:
            b = cbpdn.ConvBPDNMask(D, s, lmbda, w)
            b.solve()
            b.reconstruct()
        except Exception as e:
            print(e)
            assert 0 
Example #17
Source File: test_histogram.py    From cupy with MIT License 5 votes vote down vote up
def test_histogram_float_weights_dtype(self, xp, dtype):
        # Check the type of the returned histogram
        a = xp.arange(10, dtype=dtype)
        h, b = xp.histogram(a, weights=xp.ones(10, float))
        assert xp.issubdtype(h.dtype, xp.floating)
        return h 
Example #18
Source File: type_test.py    From cupy with MIT License 5 votes vote down vote up
def isreal(x):
    """Returns a bool array, where True if input element is real.

    If element has complex type with zero complex part, the return value
    for that element is True.

    Args:
        x (cupy.ndarray): Input array.

    Returns:
        cupy.ndarray: Boolean array of same shape as ``x``.

    .. seealso::
        :func:`iscomplex`, :func:`isrealobj`

    Examples
    --------
    >>> cupy.isreal(cp.array([1+1j, 1+0j, 4.5, 3, 2, 2j]))
    array([False,  True,  True,  True,  True, False])

    """
    if numpy.isscalar(x):
        return numpy.isreal(x)
    if not isinstance(x, cupy.ndarray):
        return cupy.asarray(numpy.isreal(x))
    if x.dtype.kind == 'c':
        return x.imag == 0
    return cupy.ones(x.shape, bool) 
Example #19
Source File: truth.py    From cupy with MIT License 5 votes vote down vote up
def in1d(ar1, ar2, assume_unique=False, invert=False):
    """Tests whether each element of a 1-D array is also present in a second
    array.

    Returns a boolean array the same length as ``ar1`` that is ``True``
    where an element of ``ar1`` is in ``ar2`` and ``False`` otherwise.

    Args:
        ar1 (cupy.ndarray): Input array.
        ar2 (cupy.ndarray): The values against which to test each value of
            ``ar1``.
        assume_unique (bool, optional): Ignored
        invert (bool, optional): If ``True``, the values in the returned array
            are inverted (that is, ``False`` where an element of ``ar1`` is in
            ``ar2`` and ``True`` otherwise). Default is ``False``.

    Returns:
        cupy.ndarray, bool: The values ``ar1[in1d]`` are in ``ar2``.

    """
    # Ravel both arrays, behavior for the first array could be different
    ar1 = ar1.ravel()
    ar2 = ar2.ravel()
    if ar1.size == 0 or ar2.size == 0:
        if invert:
            return cupy.ones(ar1.shape, dtype=cupy.bool_)
        else:
            return cupy.zeros(ar1.shape, dtype=cupy.bool_)

    shape = (ar1.size, ar2.size)
    ar1_broadcast = cupy.broadcast_to(ar1[..., cupy.newaxis], shape)
    ar2_broadcast = cupy.broadcast_to(ar2, shape)
    count = (ar1_broadcast == ar2_broadcast).sum(axis=1)
    if invert:
        return count == 0
    else:
        return count > 0 
Example #20
Source File: window.py    From cupy with MIT License 5 votes vote down vote up
def hamming(M):
    """Returns the Hamming window.

    The Hamming window is defined as

    .. math::
        w(n) = 0.54 - 0.46\\cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
        \\qquad 0 \\leq n \\leq M-1

    Args:
        M (:class:`~int`):
            Number of points in the output window. If zero or less, an empty
            array is returned.

    Returns:
        ~cupy.ndarray: Output ndarray.

    .. seealso:: :func:`numpy.hamming`
    """
    if M == 1:
        return cupy.ones(1, dtype=cupy.float64)
    if M <= 0:
        return cupy.array([])
    alpha = numpy.pi * 2 / (M - 1)
    out = cupy.empty(M, dtype=cupy.float64)
    return _hamming_kernel(alpha, out) 
Example #21
Source File: window.py    From cupy with MIT License 5 votes vote down vote up
def blackman(M):
    """Returns the Blackman window.

    The Blackman window is defined as

    .. math::
        w(n) = 0.42 - 0.5 \\cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
        + 0.08 \\cos\\left(\\frac{4\\pi{n}}{M-1}\\right)
        \\qquad 0 \\leq n \\leq M-1

    Args:
        M (:class:`~int`):
            Number of points in the output window. If zero or less, an empty
            array is returned.

    Returns:
        ~cupy.ndarray: Output ndarray.

    .. seealso:: :func:`numpy.blackman`
    """
    if M == 1:
        return cupy.ones(1, dtype=cupy.float64)
    if M <= 0:
        return cupy.array([])
    alpha = numpy.pi * 2 / (M - 1)
    out = cupy.empty(M, dtype=cupy.float64)
    return _blackman_kernel(alpha, out) 
Example #22
Source File: window.py    From cupy with MIT License 5 votes vote down vote up
def bartlett(M):
    """Returns the Bartlett window.

    The Bartlett window is defined as

    .. math::
            w(n) = \\frac{2}{M-1} \\left(
            \\frac{M-1}{2} - \\left|n - \\frac{M-1}{2}\\right|
            \\right)

    Args:
        M (int):
            Number of points in the output window. If zero or less, an empty
            array is returned.

    Returns:
        ~cupy.ndarray: Output ndarray.

    .. seealso:: :func:`numpy.bartlett`
    """
    if M == 1:
        return cupy.ones(1, dtype=cupy.float64)
    if M <= 0:
        return cupy.array([])
    alpha = (M - 1) / 2.0
    out = cupy.empty(M, dtype=cupy.float64)
    return _bartlett_kernel(alpha, out) 
Example #23
Source File: test_who.py    From cupy with MIT License 5 votes vote down vote up
def test_who_dict_empty(self, capsys):
        global x
        x = cupy.ones(10)  # NOQA
        cupy.who({})
        out, err = capsys.readouterr()
        lines = out.split('\n')
        assert lines[-2] == 'Upper bound on total bytes  =       0' 
Example #24
Source File: test_who.py    From cupy with MIT License 5 votes vote down vote up
def test_who_dict_arrays(self, capsys):
        var_dict = {'x': cupy.ones(10)}
        cupy.who(var_dict)
        out, err = capsys.readouterr()
        lines = out.split('\n')
        assert lines[-4].split() == ['x', '10', '80', 'float64']
        assert lines[-2] == 'Upper bound on total bytes  =       80' 
Example #25
Source File: test_who.py    From cupy with MIT License 5 votes vote down vote up
def test_who_global(self, capsys):
        global x
        x = cupy.ones(10)  # NOQA
        cupy.who()
        out, err = capsys.readouterr()
        lines = out.split('\n')
        assert lines[-4].split() == ['x', '10', '80', 'float64']
        assert lines[-2] == 'Upper bound on total bytes  =       80' 
Example #26
Source File: test_who.py    From cupy with MIT License 5 votes vote down vote up
def test_who_local_var(self, capsys):
        # Variables declared inside an object function are not visible
        # this is true also for numpy
        x = cupy.ones(10)  # NOQA
        cupy.who()
        out, err = capsys.readouterr()
        lines = out.split('\n')
        assert len(lines) == 3
        assert lines[1] == 'Upper bound on total bytes  =       0' 
Example #27
Source File: test_basic.py    From cupy with MIT License 5 votes vote down vote up
def test_ones_like_reshape_cupy_only(self, dtype):
        a = testing.shaped_arange((2, 3, 4), cupy, dtype)
        b = cupy.ones_like(a, shape=self.shape)
        c = cupy.ones(self.shape, dtype=dtype)

        testing.assert_array_equal(b, c) 
Example #28
Source File: test_basic.py    From cupy with MIT License 5 votes vote down vote up
def test_ones(self, xp, dtype):
        return xp.ones((2, 3, 4), dtype=dtype) 
Example #29
Source File: test_histogram.py    From cupy with MIT License 5 votes vote down vote up
def test_histogram_weights_basic(self):
        v = cupy.random.rand(100)
        w = cupy.ones(100) * 5
        a, b = cupy.histogram(v)
        na, nb = cupy.histogram(v, density=True)
        wa, wb = cupy.histogram(v, weights=w)
        nwa, nwb = cupy.histogram(v, weights=w, density=True)
        testing.assert_array_almost_equal(a * 5, wa)
        testing.assert_array_almost_equal(na, nwa) 
Example #30
Source File: sample_space_model.py    From pyECO with MIT License 5 votes vote down vote up
def __init__(self, num_samples):
        self._num_samples = num_samples
        if not config.use_gpu:
            self._distance_matrix = np.ones((num_samples, num_samples), dtype=np.float32) * np.inf
            self._gram_matrix = np.ones((num_samples, num_samples), dtype=np.float32) * np.inf
            self.prior_weights = np.zeros((num_samples, 1), dtype=np.float32)
        else:
            self._distance_matrix = cp.ones((num_samples, num_samples), dtype=cp.float32) * cp.inf
            self._gram_matrix = cp.ones((num_samples, num_samples), dtype=cp.float32) * cp.inf
            self.prior_weights = cp.zeros((num_samples, 1), dtype=cp.float32)
        # find the minimum allowed sample weight. samples are discarded if their weights become lower
        self.minimum_sample_weight = config.learning_rate * (1 - config.learning_rate)**(2*config.num_samples)