Python cupy.sqrt() Examples

The following are 11 code examples of cupy.sqrt(). 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: measurements.py    From cupy with MIT License 6 votes vote down vote up
def standard_deviation(input, labels=None, index=None):
    """Calculates the standard deviation of the values of an n-D image array,
    optionally at specified sub-regions.

    Args:
        input (cupy.ndarray): Nd-image data to process.
        labels (cupy.ndarray or None): Labels defining sub-regions in `input`.
            If not None, must be same shape as `input`.
        index (cupy.ndarray or None): `labels` to include in output. If None
            (default), all values where `labels` is non-zero are used.

    Returns:
        standard_deviation (cupy.ndarray): standard deviation of values, for
        each sub-region if `labels` and `index` are specified.

    .. seealso:: :func:`scipy.ndimage.standard_deviation`
    """
    return cupy.sqrt(variance(input, labels, index)) 
Example #2
Source File: test_cutensor.py    From cupy with MIT License 6 votes vote down vote up
def test_elementwise_trinary(self):
        desc_a = cutensor.create_tensor_descriptor(self.a, ct.OP_SQRT)
        desc_b = cutensor.create_tensor_descriptor(self.b, ct.OP_TANH)
        desc_c = cutensor.create_tensor_descriptor(self.c, ct.OP_COS)

        d = cutensor.elementwise_trinary(
            self.alpha, self.a, desc_a, self.mode_a,
            self.beta, self.b, desc_b, self.mode_b,
            self.gamma, self.c, desc_c, self.mode_c,
            op_AB=ct.OP_ADD, op_ABC=ct.OP_MUL
        )

        testing.assert_allclose(
            (self.alpha * cupy.sqrt(self.a_transposed) +
             self.beta * cupy.tanh(self.b_transposed)) *
            self.gamma * cupy.cos(self.c),
            d,
            rtol=1e-6, atol=1e-6
        ) 
Example #3
Source File: fft.py    From cupy with MIT License 6 votes vote down vote up
def hfft(a, n=None, axis=-1, norm=None):
    """Compute the FFT of a signal that has Hermitian symmetry.

    Args:
        a (cupy.ndarray): Array to be transform.
        n (None or int): Length of the transformed axis of the output. For
            ``n`` output points, ``n//2+1`` input points are necessary. If
            ``n`` is not given, it is determined from the length of the input
            along the axis specified by ``axis``.
        axis (int): Axis over which to compute the FFT.
        norm (None or ``"ortho"``): Keyword to specify the normalization mode.

    Returns:
        cupy.ndarray:
            The transformed array which shape is specified by ``n`` and type
            will convert to complex if the input is other. If ``n`` is not
            given, the length of the transformed axis is ``2*(m-1)`` where `m`
            is the length of the transformed axis of the input.

    .. seealso:: :func:`numpy.fft.hfft`
    """
    a = irfft(a.conj(), n, axis)
    return a * (a.shape[axis] if norm is None else
                cupy.sqrt(a.shape[axis], dtype=a.dtype)) 
Example #4
Source File: train.py    From style_transfer_3d with MIT License 6 votes vote down vote up
def extract_features(vgg16, images, masks=None):
    mean = cp.array([103.939, 116.779, 123.68], 'float32')  # BGR
    images = images[:, ::-1] * 255 - mean[None, :, None, None]
    features = vgg16(images, layers=['conv1_2', 'conv2_2', 'conv3_3', 'conv4_3']).values()

    if masks is None:
        masks = cp.ones((images.shape[0], images.shape[2], images.shape[3]), 'float32')
    else:
        masks = masks.data

    style_features = []
    for f in features:
        scale = masks.shape[-1] / f.shape[-1]
        m = cf.average_pooling_2d(masks[:, None, :, :], scale, scale).data
        dim = f.shape[1]

        m = m.reshape((m.shape[0], -1))
        f2 = f.transpose((0, 2, 3, 1))
        f2 = f2.reshape((f2.shape[0], -1, f2.shape[-1]))
        f2 *= cp.sqrt(m)[:, :, None]
        f2 = cf.batch_matmul(f2.transpose((0, 2, 1)), f2)
        f2 /= dim * m.sum(axis=1)[:, None, None]
        style_features.append(f2)

    return style_features 
Example #5
Source File: correlation.py    From cupy with MIT License 5 votes vote down vote up
def corrcoef(a, y=None, rowvar=True, bias=None, ddof=None):
    """Returns the Pearson product-moment correlation coefficients of an array.

    Args:
        a (cupy.ndarray): Array to compute the Pearson product-moment
            correlation coefficients.
        y (cupy.ndarray): An additional set of variables and observations.
        rowvar (bool): If ``True``, then each row represents a variable, with
            observations in the columns. Otherwise, the relationship is
            transposed.
        bias (None): Has no effect, do not use.
        ddof (None): Has no effect, do not use.

    Returns:
        cupy.ndarray: The Pearson product-moment correlation coefficients of
        the input array.

    .. seealso:: :func:`numpy.corrcoef`

    """
    if bias is not None or ddof is not None:
        warnings.warn('bias and ddof have no effect and are deprecated',
                      DeprecationWarning)

    out = cov(a, y, rowvar)
    try:
        d = cupy.diag(out)
    except ValueError:
        return out / out

    stddev = cupy.sqrt(d.real)
    out /= stddev[:, None]
    out /= stddev[None, :]

    cupy.clip(out.real, -1, 1, out=out.real)
    if cupy.iscomplexobj(out):
        cupy.clip(out.imag, -1, 1, out=out.imag)

    return out 
Example #6
Source File: spectralloss.py    From TSNetVocoder with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, alpha, fl=400, fftl=512):
        super(SpectralLoss, self).__init__()
        self.alpha = alpha[:,fl//2-1:-fl//2]
        self.fl = fl
        self.fftl = fftl
        self.norm = cupy.sqrt(self.fftl, dtype=cupy.float32) 
Example #7
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 #8
Source File: __init__.py    From dybm with Apache License 2.0 5 votes vote down vote up
def root_mean_square_err(expect, correct):
    return cupy.sqrt(mean_squared_error(expect, correct))


# Matrix operations 
Example #9
Source File: fft.py    From cupy with MIT License 4 votes vote down vote up
def _exec_fft(a, direction, value_type, norm, axis, overwrite_x,
              out_size=None, out=None, plan=None):
    fft_type = _convert_fft_type(a.dtype, value_type)

    if axis % a.ndim != a.ndim - 1:
        a = a.swapaxes(axis, -1)

    if a.base is not None or not a.flags.c_contiguous:
        a = a.copy()

    if out_size is None:
        out_size = a.shape[-1]

    batch = a.size // a.shape[-1]
    curr_plan = cufft.get_current_plan()
    if curr_plan is not None:
        if plan is None:
            plan = curr_plan
        else:
            raise RuntimeError('Use the cuFFT plan either as a context manager'
                               ' or as an argument.')
    if plan is None:
        devices = None if not config.use_multi_gpus else config._devices
        plan = cufft.Plan1d(out_size, fft_type, batch, devices=devices)
    else:
        # check plan validity
        if not isinstance(plan, cufft.Plan1d):
            raise ValueError('expected plan to have type cufft.Plan1d')
        if fft_type != plan.fft_type:
            raise ValueError('cuFFT plan dtype mismatch.')
        if out_size != plan.nx:
            raise ValueError('Target array size does not match the plan.',
                             out_size, plan.nx)
        if batch != plan.batch:
            raise ValueError('Batch size does not match the plan.')
        if config.use_multi_gpus != plan._use_multi_gpus:
            raise ValueError('Unclear if multiple GPUs are to be used or not.')

    if overwrite_x and value_type == 'C2C':
        out = a
    elif out is not None:
        # verify that out has the expected shape and dtype
        plan.check_output_array(a, out)
    else:
        out = plan.get_output_array(a)

    plan.fft(a, out, direction)

    sz = out.shape[-1]
    if fft_type == cufft.CUFFT_R2C or fft_type == cufft.CUFFT_D2Z:
        sz = a.shape[-1]
    if norm is None:
        if direction == cufft.CUFFT_INVERSE:
            out /= sz
    else:
        out /= math.sqrt(sz)

    if axis % a.ndim != a.ndim - 1:
        out = out.swapaxes(axis, -1)

    return out 
Example #10
Source File: _mass_ts.py    From mass-ts with Apache License 2.0 4 votes vote down vote up
def mass2_gpu(ts, query):
    """
    Compute the distance profile for the given query over the given time 
    series. This require cupy to be installed.

    Parameters
    ----------
    ts : array_like
        The array to create a rolling window on.
    query : array_like
        The query.

    Returns
    -------
    An array of distances.

    Raises
    ------
    ValueError
        If ts is not a list or np.array.
        If query is not a list or np.array.
        If ts or query is not one dimensional.
    """
    def moving_mean_std_gpu(a, w):
        s = cp.concatenate([cp.array([0]), cp.cumsum(a)])
        sSq = cp.concatenate([cp.array([0]), cp.cumsum(a ** 2)])
        segSum = s[w:] - s[:-w]
        segSumSq = sSq[w:] -sSq[:-w]
    
        movmean = segSum / w
        movstd = cp.sqrt(segSumSq / w - (segSum / w) ** 2)
    
        return (movmean, movstd)

    x = cp.asarray(ts)
    y = cp.asarray(query)
    n = x.size
    m = y.size

    meany = cp.mean(y)
    sigmay = cp.std(y)
    
    meanx, sigmax = moving_mean_std_gpu(x, m)
    meanx = cp.concatenate([cp.ones(n - meanx.size), meanx])
    sigmax = cp.concatenate([cp.zeros(n - sigmax.size), sigmax])
    
    y = cp.concatenate((cp.flip(y, axis=0), cp.zeros(n - m)))
    
    X = cp.fft.fft(x)
    Y = cp.fft.fft(y)
    Z = X * Y
    z = cp.fft.ifft(Z)
    
    dist = 2 * (m - (z[m - 1:n] - m * meanx[m - 1:n] * meany) / 
                    (sigmax[m - 1:n] * sigmay))
    dist = cp.sqrt(dist)

    return cp.asnumpy(dist) 
Example #11
Source File: _mass_ts.py    From mass-ts with Apache License 2.0 4 votes vote down vote up
def mass2(ts, query):
    """
    Compute the distance profile for the given query over the given time 
    series. Optionally, the correlation coefficient can be returned.

    Parameters
    ----------
    ts : array_like
        The array to create a rolling window on.
    query : array_like
        The query.

    Returns
    -------
    An array of distances.

    Raises
    ------
    ValueError
        If ts is not a list or np.array.
        If query is not a list or np.array.
        If ts or query is not one dimensional.
    """
    ts, query = mtscore.precheck_series_and_query(ts, query)

    n = len(ts)
    m = len(query)
    x = ts
    y = query

    meany = np.mean(y)
    sigmay = np.std(y)
    
    meanx = mtscore.moving_average(x, m)
    meanx = np.append(np.ones([1, len(x) - len(meanx)]), meanx)
    sigmax = mtscore.moving_std(x, m)
    sigmax = np.append(np.zeros([1, len(x) - len(sigmax)]), sigmax)
    
    y = np.append(np.flip(y), np.zeros([1, n - m]))
    
    X = np.fft.fft(x)
    Y = np.fft.fft(y)
    Y.resize(X.shape)
    Z = X * Y
    z = np.fft.ifft(Z)
    
    dist = 2 * (m - (z[m - 1:n] - m * meanx[m - 1:n] * meany) / 
                    (sigmax[m - 1:n] * sigmay))
    dist = np.sqrt(dist)
    
    return dist