Python cupy.asarray() Examples
The following are 30
code examples of cupy.asarray().
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: generator.py From cupy with MIT License | 6 votes |
def weibull(self, a, size=None, dtype=float): """Returns an array of samples drawn from the weibull distribution. .. warning:: This function may synchronize the device. .. seealso:: :func:`cupy.random.weibull` for full documentation, :meth:`numpy.random.RandomState.weibull <numpy.random.mtrand.RandomState.weibull>` """ a = cupy.asarray(a) if cupy.any(a < 0): # synchronize! raise ValueError('a < 0') x = self.standard_exponential(size, dtype) cupy.power(x, 1./a, out=x) return x
Example #2
Source File: generator.py From cupy with MIT License | 6 votes |
def exponential(self, scale=1.0, size=None, dtype=float): """Returns an array of samples drawn from a exponential distribution. .. warning:: This function may synchronize the device. .. seealso:: :func:`cupy.random.exponential` for full documentation, :meth:`numpy.random.RandomState.exponential <numpy.random.mtrand.RandomState.exponential>` """ scale = cupy.asarray(scale, dtype) if (scale < 0).any(): # synchronize! raise ValueError('scale < 0') if size is None: size = scale.shape x = self.standard_exponential(size, dtype) x *= scale return x
Example #3
Source File: generator.py From cupy with MIT License | 6 votes |
def noncentral_chisquare(self, df, nonc, size=None, dtype=float): """Returns an array of samples drawn from the noncentral chi-square distribution. .. warning:: This function may synchronize the device. .. seealso:: :func:`cupy.random.noncentral_chisquare` for full documentation, :meth:`numpy.random.RandomState.noncentral_chisquare <numpy.random.mtrand.RandomState.noncentral_chisquare>` """ df, nonc = cupy.asarray(df), cupy.asarray(nonc) if cupy.any(df <= 0): # synchronize! raise ValueError('df <= 0') if cupy.any(nonc < 0): # synchronize! raise ValueError('nonc < 0') if size is None: size = cupy.broadcast(df, nonc).shape y = cupy.empty(shape=size, dtype=dtype) _kernels.noncentral_chisquare_kernel(df, nonc, self._rk_seed, y) self._update_seed(y.size) return y
Example #4
Source File: generator.py From cupy with MIT License | 6 votes |
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 #5
Source File: generator.py From cupy with MIT License | 6 votes |
def negative_binomial(self, n, p, size=None, dtype=int): """Returns an array of samples drawn from the negative binomial distribution. .. warning:: This function may synchronize the device. .. seealso:: :func:`cupy.random.negative_binomial` for full documentation, :meth:`numpy.random.RandomState.negative_binomial <numpy.random.mtrand.RandomState.negative_binomial>` """ n = cupy.asarray(n) p = cupy.asarray(p) if cupy.any(n <= 0): # synchronize! raise ValueError('n <= 0') if cupy.any(p < 0): # synchronize! raise ValueError('p < 0') if cupy.any(p > 1): # synchronize! raise ValueError('p > 1') y = self.gamma(n, (1-p)/p, size) return self.poisson(y, dtype=dtype)
Example #6
Source File: generator.py From cupy with MIT License | 6 votes |
def rayleigh(self, scale=1.0, size=None, dtype=float): """Returns an array of samples drawn from a rayleigh distribution. .. warning:: This function may synchronize the device. .. seealso:: :func:`cupy.random.rayleigh` for full documentation, :meth:`numpy.random.RandomState.rayleigh <numpy.random.mtrand.RandomState.rayleigh>` """ scale = cupy.asarray(scale) if size is None: size = scale.shape if cupy.any(scale < 0): # synchronize! raise ValueError('scale < 0') x = self._random_sample_raw(size, dtype) x = cupy.log(x, out=x) x = cupy.multiply(x, -2., out=x) x = cupy.sqrt(x, out=x) x = cupy.multiply(x, scale, out=x) return x
Example #7
Source File: generator.py From cupy with MIT License | 6 votes |
def logistic(self, loc=0.0, scale=1.0, size=None, dtype=float): """Returns an array of samples drawn from the logistic distribution. .. seealso:: :func:`cupy.random.logistic` for full documentation, :meth:`numpy.random.RandomState.logistic <numpy.random.mtrand.RandomState.logistic>` """ loc, scale = cupy.asarray(loc), cupy.asarray(scale) if size is None: size = cupy.broadcast(loc, scale).shape x = cupy.empty(shape=size, dtype=dtype) _kernels.open_uniform_kernel(self._rk_seed, x) self._update_seed(x.size) x = (1.0 - x) / x cupy.log(x, out=x) cupy.multiply(x, scale, out=x) cupy.add(x, loc, out=x) return x
Example #8
Source File: generator.py From cupy with MIT License | 6 votes |
def gamma(self, shape, scale=1.0, size=None, dtype=float): """Returns an array of samples drawn from a gamma distribution. .. seealso:: :func:`cupy.random.gamma` for full documentation, :meth:`numpy.random.RandomState.gamma <numpy.random.mtrand.RandomState.gamma>` """ shape, scale = cupy.asarray(shape), cupy.asarray(scale) if size is None: size = cupy.broadcast(shape, scale).shape y = cupy.empty(shape=size, dtype=dtype) _kernels.standard_gamma_kernel(shape, self._rk_seed, y) y *= scale self._update_seed(y.size) return y
Example #9
Source File: test_array_function.py From cupy with MIT License | 6 votes |
def test_array_function(self): a = numpy.random.randn(100, 100) a_cpu = numpy.asarray(a) a_gpu = cupy.asarray(a) # The numpy call for both CPU and GPU arrays is intentional to test the # __array_function__ protocol qr_cpu = numpy.linalg.qr(a_cpu) qr_gpu = numpy.linalg.qr(a_gpu) if isinstance(qr_cpu, tuple): for b_cpu, b_gpu in zip(qr_cpu, qr_gpu): self.assertEqual(b_cpu.dtype, b_gpu.dtype) cupy.testing.assert_allclose(b_cpu, b_gpu, atol=1e-4) else: self.assertEqual(qr_cpu.dtype, qr_gpu.dtype) cupy.testing.assert_allclose(qr_cpu, qr_gpu, atol=1e-4)
Example #10
Source File: generator.py From cupy with MIT License | 6 votes |
def triangular(self, left, mode, right, size=None, dtype=float): """Returns an array of samples drawn from the triangular distribution. .. warning:: This function may synchronize the device. .. seealso:: :func:`cupy.random.triangular` for full documentation, :meth:`numpy.random.RandomState.triangular <numpy.random.mtrand.RandomState.triangular>` """ left, mode, right = \ cupy.asarray(left), cupy.asarray(mode), cupy.asarray(right) if cupy.any(left > mode): # synchronize! raise ValueError('left > mode') if cupy.any(mode > right): # synchronize! raise ValueError('mode > right') if cupy.any(left == right): # synchronize! raise ValueError('left == right') if size is None: size = cupy.broadcast(left, mode, right).shape x = self.random_sample(size=size, dtype=dtype) return RandomState._triangular_kernel(left, mode, right, x)
Example #11
Source File: matrix.py From cupy with MIT License | 6 votes |
def tril(m, k=0): """Returns a lower triangle of an array. Args: m (array-like): Array or array-like object. k (int): The diagonal above which to zero elements. Zero is the main diagonal, a positive value is above it, and a negative value is below. Returns: cupy.ndarray: A lower triangle of an array. .. seealso:: :func:`numpy.tril` """ m = cupy.asarray(m) mask = tri(*m.shape[-2:], k=k, dtype=bool) return cupy.where(mask, m, m.dtype.type(0))
Example #12
Source File: test_shape.py From cupy with MIT License | 6 votes |
def test_reshape_contiguity(self): shape_init, shape_final = self.shape_in_out a_cupy = testing.shaped_arange(shape_init, xp=cupy) a_cupy = cupy.asarray(a_cupy, order=self.order_init) b_cupy = a_cupy.reshape(shape_final, order=self.order_reshape) a_numpy = testing.shaped_arange(shape_init, xp=numpy) a_numpy = numpy.asarray(a_numpy, order=self.order_init) b_numpy = a_numpy.reshape(shape_final, order=self.order_reshape) assert b_cupy.flags.f_contiguous == b_numpy.flags.f_contiguous assert b_cupy.flags.c_contiguous == b_numpy.flags.c_contiguous testing.assert_array_equal(b_cupy.strides, b_numpy.strides) testing.assert_array_equal(b_cupy, b_numpy)
Example #13
Source File: generator.py From cupy with MIT License | 6 votes |
def zipf(self, a, size=None, dtype=int): """Returns an array of samples drawn from the Zipf distribution. .. warning:: This function may synchronize the device. .. seealso:: :func:`cupy.random.zipf` for full documentation, :meth:`numpy.random.RandomState.zipf <numpy.random.mtrand.RandomState.zipf>` """ a = cupy.asarray(a) if cupy.any(a <= 1.0): # synchronize! raise ValueError('\'a\' must be a valid float > 1.0') if size is None: size = a.shape y = cupy.empty(shape=size, dtype=dtype) _kernels.zipf_kernel(a, self._rk_seed, y) self._update_seed(y.size) return y
Example #14
Source File: generator.py From cupy with MIT License | 6 votes |
def hypergeometric(self, ngood, nbad, nsample, size=None, dtype=int): """Returns an array of samples drawn from the hypergeometric distribution. .. seealso:: :func:`cupy.random.hypergeometric` for full documentation, :meth:`numpy.random.RandomState.hypergeometric <numpy.random.mtrand.RandomState.hypergeometric>` """ ngood, nbad, nsample = \ cupy.asarray(ngood), cupy.asarray(nbad), cupy.asarray(nsample) if size is None: size = cupy.broadcast(ngood, nbad, nsample).shape y = cupy.empty(shape=size, dtype=dtype) _kernels.hypergeometric_kernel(ngood, nbad, nsample, self._rk_seed, y) self._update_seed(y.size) return y
Example #15
Source File: kmeans.py From cupy with MIT License | 6 votes |
def run(gpuid, n_clusters, num, max_iter, use_custom_kernel, output): samples = numpy.random.randn(num, 2) X_train = numpy.r_[samples + 1, samples - 1] with timer(' CPU '): centers, pred = fit_xp(X_train, n_clusters, max_iter) with cupy.cuda.Device(gpuid): X_train = cupy.asarray(X_train) with timer(' GPU '): if use_custom_kernel: centers, pred = fit_custom(X_train, n_clusters, max_iter) else: centers, pred = fit_xp(X_train, n_clusters, max_iter) if output is not None: index = numpy.random.choice(10000000, 300, replace=False) draw(X_train[index].get(), n_clusters, centers.get(), pred[index].get(), output)
Example #16
Source File: monitor.py From LaSO with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_percentiles(data, sigma): """Compute percentiles for data and return an array with the same length as the number of elements in ``sigma``. Args: data (array): 1-dimensional NumPy or CuPy arryay. sigma (tuple): Sigmas for which percentiles are computed. Returns: array: Array of percentiles. """ def _get_percentiles(_data, _sigma): try: return np.percentile(_data, _sigma) except IndexError: # Handle uninitialized model parameters return np.array((float('NaN'),) * 7) if isinstance(data, cupy.ndarray): # TODO(hvy): Make percentile computation faster for GPUs data = cupy.asnumpy(data) return cupy.asarray(_get_percentiles(data, sigma)) return _get_percentiles(data, sigma)
Example #17
Source File: fft.py From cupy with MIT License | 6 votes |
def __ua_convert__(dispatchables, coerce): if coerce: try: replaced = [ cupy.asarray(d.value) if d.coercible and d.type is np.ndarray else d.value for d in dispatchables] except TypeError: return NotImplemented else: replaced = [d.value for d in dispatchables] if not all(d.type is not np.ndarray or isinstance(r, cupy.ndarray) for r, d in zip(replaced, dispatchables)): return NotImplemented return replaced
Example #18
Source File: trigonometric.py From cupy with MIT License | 6 votes |
def unwrap(p, discont=numpy.pi, axis=-1): """Unwrap by changing deltas between values to 2*pi complement. Args: p (cupy.ndarray): Input array. discont (float): Maximum discontinuity between values, default is ``pi``. axis (int): Axis along which unwrap will operate, default is the last axis. Returns: cupy.ndarray: The result array. .. seealso:: :func:`numpy.unwrap` """ p = cupy.asarray(p) nd = p.ndim dd = sumprod.diff(p, axis=axis) slice1 = [slice(None, None)]*nd # full slices slice1[axis] = slice(1, None) slice1 = tuple(slice1) ph_correct = _unwrap_correct(dd, discont) up = cupy.array(p, copy=True, dtype='d') up[slice1] = p[slice1] + cupy.cumsum(ph_correct, axis=axis) return up
Example #19
Source File: fft.py From cupy with MIT License | 6 votes |
def fftshift(x, axes=None): """Shift the zero-frequency component to the center of the spectrum. Args: x (cupy.ndarray): Input array. axes (int or tuple of ints): Axes over which to shift. Default is ``None``, which shifts all axes. Returns: cupy.ndarray: The shifted array. .. seealso:: :func:`numpy.fft.fftshift` """ x = cupy.asarray(x) if axes is None: axes = list(range(x.ndim)) elif isinstance(axes, np.compat.integer_types): axes = (axes,) for axis in axes: x = cupy.roll(x, x.shape[axis] // 2, axis) return x
Example #20
Source File: fft.py From cupy with MIT License | 6 votes |
def ifftshift(x, axes=None): """The inverse of :meth:`fftshift`. Args: x (cupy.ndarray): Input array. axes (int or tuple of ints): Axes over which to shift. Default is ``None``, which shifts all axes. Returns: cupy.ndarray: The shifted array. .. seealso:: :func:`numpy.fft.ifftshift` """ x = cupy.asarray(x) if axes is None: axes = list(range(x.ndim)) elif isinstance(axes, np.compat.integer_types): axes = (axes,) for axis in axes: x = cupy.roll(x, -(x.shape[axis] // 2), axis) return x
Example #21
Source File: tracker.py From pyECO with MIT License | 6 votes |
def _get_interp_fourier(self, sz): """ compute the fourier series of the interpolation function. """ f1 = np.arange(-(sz[0]-1) / 2, (sz[0]-1)/2+1, dtype=np.float32)[:, np.newaxis] / sz[0] interp1_fs = np.real(cubic_spline_fourier(f1, config.interp_bicubic_a) / sz[0]) f2 = np.arange(-(sz[1]-1) / 2, (sz[1]-1)/2+1, dtype=np.float32)[np.newaxis, :] / sz[1] interp2_fs = np.real(cubic_spline_fourier(f2, config.interp_bicubic_a) / sz[1]) if config.interp_centering: f1 = np.arange(-(sz[0]-1) / 2, (sz[0]-1)/2+1, dtype=np.float32)[:, np.newaxis] interp1_fs = interp1_fs * np.exp(-1j*np.pi / sz[0] * f1) f2 = np.arange(-(sz[1]-1) / 2, (sz[1]-1)/2+1, dtype=np.float32)[np.newaxis, :] interp2_fs = interp2_fs * np.exp(-1j*np.pi / sz[1] * f2) if config.interp_windowing: win1 = np.hanning(sz[0]+2)[:, np.newaxis] win2 = np.hanning(sz[1]+2)[np.newaxis, :] interp1_fs = interp1_fs * win1[1:-1] interp2_fs = interp2_fs * win2[1:-1] if not config.use_gpu: return (interp1_fs[:, :, np.newaxis, np.newaxis], interp2_fs[:, :, np.newaxis, np.newaxis]) else: return (cp.asarray(interp1_fs[:, :, np.newaxis, np.newaxis]), cp.asarray(interp2_fs[:, :, np.newaxis, np.newaxis]))
Example #22
Source File: matrix.py From cupy with MIT License | 5 votes |
def triu(m, k=0): """Returns an upper triangle of an array. Args: m (array-like): Array or array-like object. k (int): The diagonal below which to zero elements. Zero is the main diagonal, a positive value is above it, and a negative value is below. Returns: cupy.ndarray: An upper triangle of an array. .. seealso:: :func:`numpy.triu` """ m = cupy.asarray(m) mask = tri(*m.shape[-2:], k=k-1, dtype=bool) return cupy.where(mask, m.dtype.type(0), m) # TODO(okuta): Implement vander # TODO(okuta): Implement mat # TODO(okuta): Implement bmat
Example #23
Source File: generator.py From cupy with MIT License | 5 votes |
def wald(self, mean, scale, size=None, dtype=float): """Returns an array of samples drawn from the Wald distribution. .. seealso:: :func:`cupy.random.wald` for full documentation, :meth:`numpy.random.RandomState.wald <numpy.random.mtrand.RandomState.wald>` """ mean, scale = \ cupy.asarray(mean, dtype=dtype), cupy.asarray(scale, dtype=dtype) if size is None: size = cupy.broadcast(mean, scale).shape x = self.normal(size=size, dtype=dtype) u = self.random_sample(size=size, dtype=dtype) return RandomState._wald_kernel(mean, scale, u, x)
Example #24
Source File: generator.py From cupy with MIT License | 5 votes |
def chisquare(self, df, size=None, dtype=float): """Returns an array of samples drawn from the chi-square distribution. .. seealso:: :func:`cupy.random.chisquare` for full documentation, :meth:`numpy.random.RandomState.chisquare <numpy.random.mtrand.RandomState.chisquare>` """ df = cupy.asarray(df) if size is None: size = df.shape y = cupy.empty(shape=size, dtype=dtype) _kernels.chisquare_kernel(df, self._rk_seed, y) self._update_seed(y.size) return y
Example #25
Source File: generator.py From cupy with MIT License | 5 votes |
def binomial(self, n, p, size=None, dtype=int): """Returns an array of samples drawn from the binomial distribution. .. seealso:: :func:`cupy.random.binomial` for full documentation, :meth:`numpy.random.RandomState.binomial <numpy.random.mtrand.RandomState.binomial>` """ n, p = cupy.asarray(n), cupy.asarray(p) if size is None: size = cupy.broadcast(n, p).shape y = cupy.empty(shape=size, dtype=dtype) _kernels.binomial_kernel(n, p, self._rk_seed, y) self._update_seed(y.size) return y
Example #26
Source File: generator.py From cupy with MIT License | 5 votes |
def beta(self, a, b, size=None, dtype=float): """Returns an array of samples drawn from the beta distribution. .. seealso:: :func:`cupy.random.beta` for full documentation, :meth:`numpy.random.RandomState.beta <numpy.random.mtrand.RandomState.beta>` """ a, b = cupy.asarray(a), cupy.asarray(b) if size is None: size = cupy.broadcast(a, b).shape y = cupy.empty(shape=size, dtype=dtype) _kernels.beta_kernel(a, b, self._rk_seed, y) self._update_seed(y.size) return y
Example #27
Source File: generator.py From cupy with MIT License | 5 votes |
def pareto(self, a, size=None, dtype=float): """Returns an array of samples drawn from the pareto II distribution. .. seealso:: :func:`cupy.random.pareto_kernel` for full documentation, :meth:`numpy.random.RandomState.pareto <numpy.random.mtrand.RandomState.pareto>` """ a = cupy.asarray(a) x = self._random_sample_raw(size, dtype) cupy.log(x, out=x) cupy.exp(-x/a, out=x) return x - 1
Example #28
Source File: matrix.py From cupy with MIT License | 5 votes |
def diagflat(v, k=0): """Creates a diagonal array from the flattened input. Args: v (array-like): Array or array-like object. k (int): Index of diagonals. See :func:`cupy.diag` for detail. Returns: cupy.ndarray: A 2-D diagonal array with the diagonal copied from ``v``. """ if numpy.isscalar(v): v = numpy.asarray(v) return cupy.diag(v.ravel(), k)
Example #29
Source File: type_test.py From cupy with MIT License | 5 votes |
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 #30
Source File: iterate.py From cupy with MIT License | 5 votes |
def __setitem__(self, ind, value): if ind is Ellipsis: self[:] = value return if isinstance(ind, tuple): raise IndexError('unsupported iterator index') if isinstance(ind, bool): raise IndexError('unsupported iterator index') if numpy.isscalar(ind): ind = int(ind) base = self._base size = base.size indices = [] for s in base.shape: size = size // s indices.append(ind // size) ind %= size base[tuple(indices)] = value return if isinstance(ind, slice): base = self._base s = internal.complete_slice(ind, base.size) s_start = s.start s_step = s.step size = s.stop - s.start if s_step > 0: size = (size - 1) // s_step + 1 else: size = (size + 1) // s_step + 1 value = cupy.asarray(value, dtype=base.dtype) _flatiter_setitem_slice(value, s_start, s_step, base, size=size) return raise IndexError('unsupported iterator index')