本文整理汇总了Python中cupy.empty方法的典型用法代码示例。如果您正苦于以下问题:Python cupy.empty方法的具体用法?Python cupy.empty怎么用?Python cupy.empty使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cupy
的用法示例。
在下文中一共展示了cupy.empty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: use_single_gpu
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import empty [as 别名]
def use_single_gpu():
""" Use single GPU device.
If CUDA_VISIBLE_DEVICES is set, select a device from the variable.
Otherwise, get a free GPU device and use it.
Returns:
assigned GPU id.
"""
cvd = os.environ.get('CUDA_VISIBLE_DEVICES')
if cvd is None:
# no GPUs are researved
cvd = get_free_gpus()[0]
elif ',' in cvd:
# multiple GPUs are researved
cvd = int(cvd.split(',')[0])
else:
# single GPU is reserved
cvd = int(cvd)
# Use the GPU immediately
chainer.cuda.get_device_from_id(cvd).use()
cupy.empty((1,), dtype=cupy.float32)
return cvd
示例2: convolve2d
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import empty [as 别名]
def convolve2d(in1, in2, mode='full'):
"""
note only support H * W * N * 1 convolve 2d
"""
in1 = in1.transpose(2, 3, 0, 1) # to N * C * H * W
in2 = in2.transpose(2, 3, 0, 1)
out_c, _, kh, kw = in2.shape
n, _, h, w = in1.shape
if mode == 'full':
ph, pw = kh-1, kw-1
out_h, out_w = h-kh+1+ph*2, w-kw+1+pw*2# TODO
elif mode == 'valid':
ph, pw = 0, 0
out_h, out_w = h-kh+1, w-kw+1 # TODO
else:
raise NotImplementedError
y = cp.empty((n, out_c, out_h, out_w), dtype=in1.dtype)
col = im2col_gpu(in1, kh, kw, 1, 1, ph, pw)
y = cp.tensordot(
col, in2, ((1, 2, 3), (1, 2, 3))).astype(in1.dtype, copy=False)
y = cp.rollaxis(y, 3, 1)
return y.transpose(2, 3, 0, 1)
示例3: diagonal
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import empty [as 别名]
def diagonal(self, k=0):
"""Returns the k-th diagonal of the matrix.
Args:
k (int, optional): Which diagonal to get, corresponding to elements
a[i, i+k]. Default: 0 (the main diagonal).
Returns:
cupy.ndarray : The k-th diagonal.
"""
rows, cols = self.shape
if k <= -rows or k >= cols:
return cupy.empty(0, dtype=self.data.dtype)
idx, = cupy.nonzero(self.offsets == k)
first_col, last_col = max(0, k), min(rows + k, cols)
if idx.size == 0:
return cupy.zeros(last_col - first_col, dtype=self.data.dtype)
return self.data[idx[0], first_col:last_col]
示例4: _label
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import empty [as 别名]
def _label(x, structure, y):
elems = numpy.where(structure != 0)
vecs = [elems[dm] - 1 for dm in range(x.ndim)]
offset = vecs[0]
for dm in range(1, x.ndim):
offset = offset * 3 + vecs[dm]
indxs = numpy.where(offset < 0)[0]
dirs = [[vecs[dm][dr] for dm in range(x.ndim)] for dr in indxs]
dirs = cupy.array(dirs, dtype=numpy.int32)
ndirs = indxs.shape[0]
y_shape = cupy.array(y.shape, dtype=numpy.int32)
count = cupy.zeros(2, dtype=numpy.int32)
_kernel_init()(x, y)
_kernel_connect()(y_shape, dirs, ndirs, x.ndim, y, size=y.size)
_kernel_count()(y, count, size=y.size)
maxlabel = int(count[0])
labels = cupy.empty(maxlabel, dtype=numpy.int32)
_kernel_labels()(y, count, labels, size=y.size)
_kernel_finalize()(maxlabel, cupy.sort(labels), y, size=y.size)
return maxlabel
示例5: test_cub_argmin
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import empty [as 别名]
def test_cub_argmin(self, xp, dtype):
assert cupy.cuda.cub_enabled
a = testing.shaped_random(self.shape, xp, dtype)
if self.order == 'C':
a = xp.ascontiguousarray(a)
else:
a = xp.asfortranarray(a)
if xp is numpy:
return a.argmin()
# xp is cupy, first ensure we really use CUB
ret = cupy.empty(()) # Cython checks return type, need to fool it
func = 'cupy.core._routines_statistics.cub.device_reduce'
with testing.AssertFunctionIsCalled(func, return_value=ret):
a.argmin()
# ...then perform the actual computation
return a.argmin()
示例6: test_cub_sum
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import empty [as 别名]
def test_cub_sum(self, xp, dtype, axis):
assert cupy.cuda.cub_enabled
a = testing.shaped_random(self.shape, xp, dtype)
if self.order in ('c', 'C'):
a = xp.ascontiguousarray(a)
elif self.order in ('f', 'F'):
a = xp.asfortranarray(a)
if xp is numpy:
return a.sum(axis=axis)
# xp is cupy, first ensure we really use CUB
ret = cupy.empty(()) # Cython checks return type, need to fool it
if len(axis) == len(self.shape):
func = 'cupy.core._routines_math.cub.device_reduce'
else:
func = 'cupy.core._routines_math.cub.device_segmented_reduce'
with testing.AssertFunctionIsCalled(func, return_value=ret):
a.sum(axis=axis)
# ...then perform the actual computation
return a.sum(axis=axis)
示例7: test_cub_prod
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import empty [as 别名]
def test_cub_prod(self, xp, dtype, axis):
assert cupy.cuda.cub_enabled
a = testing.shaped_random(self.shape, xp, dtype)
if self.order in ('c', 'C'):
a = xp.ascontiguousarray(a)
elif self.order in ('f', 'F'):
a = xp.asfortranarray(a)
if xp is numpy:
return a.prod(axis=axis)
# xp is cupy, first ensure we really use CUB
ret = cupy.empty(()) # Cython checks return type, need to fool it
if len(axis) == len(self.shape):
func = 'cupy.core._routines_math.cub.device_reduce'
else:
func = 'cupy.core._routines_math.cub.device_segmented_reduce'
with testing.AssertFunctionIsCalled(func, return_value=ret):
a.prod(axis=axis)
# ...then perform the actual computation
return a.prod(axis=axis)
# TODO(leofang): test axis after support is added
# don't test float16 as it's not as accurate?
示例8: test_cub_cumsum
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import empty [as 别名]
def test_cub_cumsum(self, xp, dtype):
assert cupy.cuda.cub_enabled
a = testing.shaped_random(self.shape, xp, dtype)
if self.order in ('c', 'C'):
a = xp.ascontiguousarray(a)
elif self.order in ('f', 'F'):
a = xp.asfortranarray(a)
if xp is numpy:
return a.cumsum()
# xp is cupy, first ensure we really use CUB
ret = cupy.empty(()) # Cython checks return type, need to fool it
func = 'cupy.core._routines_math.cub.device_scan'
with testing.AssertFunctionIsCalled(func, return_value=ret):
a.cumsum()
# ...then perform the actual computation
return a.cumsum()
# TODO(leofang): test axis after support is added
# don't test float16 as it's not as accurate?
示例9: test_cub_min
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import empty [as 别名]
def test_cub_min(self, xp, dtype, axis):
assert cupy.cuda.cub_enabled
a = testing.shaped_random(self.shape, xp, dtype)
if self.order in ('c', 'C'):
a = xp.ascontiguousarray(a)
elif self.order in ('f', 'F'):
a = xp.asfortranarray(a)
if xp is numpy:
return a.min(axis=axis)
# xp is cupy, first ensure we really use CUB
ret = cupy.empty(()) # Cython checks return type, need to fool it
if len(axis) == len(self.shape):
func = 'cupy.core._routines_statistics.cub.device_reduce'
else:
func = 'cupy.core._routines_statistics.cub.device_segmented_reduce'
with testing.AssertFunctionIsCalled(func, return_value=ret):
a.min(axis=axis)
# ...then perform the actual computation
return a.min(axis=axis)
示例10: test_cub_max
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import empty [as 别名]
def test_cub_max(self, xp, dtype, axis):
assert cupy.cuda.cub_enabled
a = testing.shaped_random(self.shape, xp, dtype)
if self.order in ('c', 'C'):
a = xp.ascontiguousarray(a)
elif self.order in ('f', 'F'):
a = xp.asfortranarray(a)
if xp is numpy:
return a.max(axis=axis)
# xp is cupy, first ensure we really use CUB
ret = cupy.empty(()) # Cython checks return type, need to fool it
if len(axis) == len(self.shape):
func = 'cupy.core._routines_statistics.cub.device_reduce'
else:
func = 'cupy.core._routines_statistics.cub.device_segmented_reduce'
with testing.AssertFunctionIsCalled(func, return_value=ret):
a.max(axis=axis)
# ...then perform the actual computation
return a.max(axis=axis)
示例11: tri
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import empty [as 别名]
def tri(N, M=None, k=0, dtype=float):
"""Creates an array with ones at and below the given diagonal.
Args:
N (int): Number of rows.
M (int): Number of columns. M == N by default.
k (int): The sub-diagonal at and below which the array is filled. Zero
is the main diagonal, a positive value is above it, and a negative
value is below.
dtype: Data type specifier.
Returns:
cupy.ndarray: An array with ones at and below the given diagonal.
.. seealso:: :func:`numpy.tri`
"""
if M is None:
M = N
out = cupy.empty((N, M), dtype=dtype)
return _tri_kernel(M, k, out)
示例12: empty
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import empty [as 别名]
def empty(shape, dtype=float, order='C'):
"""Returns an array without initializing the elements.
Args:
shape (int or tuple of ints): Dimensionalities of the array.
dtype: Data type specifier.
order ({'C', 'F'}): Row-major (C-style) or column-major
(Fortran-style) order.
Returns:
cupy.ndarray: A new array with elements not initialized.
.. seealso:: :func:`numpy.empty`
"""
return cupy.ndarray(shape, dtype, order=order)
示例13: csr2coo
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import empty [as 别名]
def csr2coo(x, data, indices):
"""Converts a CSR-matrix to COO format.
Args:
x (cupyx.scipy.sparse.csr_matrix): A matrix to be converted.
data (cupy.ndarray): A data array for converted data.
indices (cupy.ndarray): An index array for converted data.
Returns:
cupyx.scipy.sparse.coo_matrix: A converted matrix.
"""
if not check_availability('csr2coo'):
raise RuntimeError('csr2coo is not available.')
handle = device.get_cusparse_handle()
m = x.shape[0]
nnz = len(x.data)
row = cupy.empty(nnz, 'i')
cusparse.xcsr2coo(
handle, x.indptr.data.ptr, nnz, m, row.data.ptr,
cusparse.CUSPARSE_INDEX_BASE_ZERO)
# data and indices did not need to be copied already
return cupyx.scipy.sparse.coo_matrix(
(data, (row, indices)), shape=x.shape)
示例14: col2im_gpu
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import empty [as 别名]
def col2im_gpu(col, sy, sx, ph, pw, h, w, dy=1, dx=1):
n, c, kh, kw, out_h, out_w = col.shape
img = cp.empty((n, c, h, w), dtype=col.dtype)
cp.ElementwiseKernel(
'raw T col, int32 h, int32 w, int32 out_h, int32 out_w,'
'int32 kh, int32 kw, int32 sy, int32 sx, int32 ph, int32 pw,'
'int32 dx, int32 dy',
'T img',
'''
int c0 = i / (h * w);
int y = i / w % h;
int x = i % w;
T val = 0;
for (int ky = 0; ky < kh; ++ky) {
int out_y = (y + ph - ky * dy);
if (0 > out_y || out_y >= out_h * sy) continue;
if (out_y % sy != 0) continue;
out_y /= sy;
for (int kx = 0; kx < kw; ++kx) {
int out_x = (x + pw - kx * dx);
if (0 > out_x || out_x >= out_w * sx) continue;
if (out_x % sx != 0) continue;
out_x /= sx;
int k = out_y + out_h * (kx + kw * (ky + kh * c0));
val = val + col[out_x + out_w * k];
}
}
img = val;
''',
'col2im')(col.reduced_view(),
h, w, out_h, out_w, kh, kw, sy, sx, ph, pw, dx, dy, img)
return img
示例15: _compressed_sparse_stack
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import empty [as 别名]
def _compressed_sparse_stack(blocks, axis):
"""Fast path for stacking CSR/CSC matrices
(i) vstack for CSR, (ii) hstack for CSC.
"""
other_axis = 1 if axis == 0 else 0
data = cupy.concatenate([b.data for b in blocks])
constant_dim = blocks[0].shape[other_axis]
idx_dtype = sputils.get_index_dtype(arrays=[b.indptr for b in blocks],
maxval=max(data.size, constant_dim))
indices = cupy.empty(data.size, dtype=idx_dtype)
indptr = cupy.empty(sum(b.shape[axis]
for b in blocks) + 1, dtype=idx_dtype)
last_indptr = idx_dtype(0)
sum_dim = 0
sum_indices = 0
for b in blocks:
if b.shape[other_axis] != constant_dim:
raise ValueError(
'incompatible dimensions for axis %d' % other_axis)
indices[sum_indices:sum_indices+b.indices.size] = b.indices
sum_indices += b.indices.size
idxs = slice(sum_dim, sum_dim + b.shape[axis])
indptr[idxs] = b.indptr[:-1]
indptr[idxs] += last_indptr
sum_dim += b.shape[axis]
last_indptr += b.indptr[-1]
indptr[-1] = last_indptr
if axis == 0:
return csr.csr_matrix((data, indices, indptr),
shape=(sum_dim, constant_dim))
else:
return csc.csc_matrix((data, indices, indptr),
shape=(constant_dim, sum_dim))