本文整理汇总了Python中cupy.asnumpy方法的典型用法代码示例。如果您正苦于以下问题:Python cupy.asnumpy方法的具体用法?Python cupy.asnumpy怎么用?Python cupy.asnumpy使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cupy
的用法示例。
在下文中一共展示了cupy.asnumpy方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _non_maximum_suppression_gpu
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import asnumpy [as 别名]
def _non_maximum_suppression_gpu(bbox, thresh, score=None, limit=None):
if len(bbox) == 0:
return cp.zeros((0,), dtype=np.int32)
n_bbox = bbox.shape[0]
if score is not None:
order = score.argsort()[::-1].astype(np.int32)
else:
order = cp.arange(n_bbox, dtype=np.int32)
sorted_bbox = bbox[order, :]
selec, n_selec = _call_nms_kernel(
sorted_bbox, thresh)
selec = selec[:n_selec]
selec = order[selec]
if limit is not None:
selec = selec[:limit]
return cp.asnumpy(selec)
示例2: _suppress
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import asnumpy [as 别名]
def _suppress(self, raw_cls_bbox, raw_prob):
bbox = list()
label = list()
score = list()
# skip cls_id = 0 because it is the background class
for l in range(1, self.n_class):
cls_bbox_l = raw_cls_bbox.reshape((-1, self.n_class, 4))[:, l, :]
prob_l = raw_prob[:, l]
mask = prob_l > self.score_thresh
cls_bbox_l = cls_bbox_l[mask]
prob_l = prob_l[mask]
keep = non_maximum_suppression(
cp.array(cls_bbox_l), self.nms_thresh, prob_l)
keep = cp.asnumpy(keep)
bbox.append(cls_bbox_l[keep])
# The labels are in [0, self.n_class - 2].
label.append((l - 1) * np.ones((len(keep),)))
score.append(prob_l[keep])
bbox = np.concatenate(bbox, axis=0).astype(np.float32)
label = np.concatenate(label, axis=0).astype(np.int32)
score = np.concatenate(score, axis=0).astype(np.float32)
return bbox, label, score
示例3: test_lu_factor_reconstruction
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import asnumpy [as 别名]
def test_lu_factor_reconstruction(self, dtype):
m, n = self.shape
A = cupy.random.randn(m, n, dtype=dtype)
lu, piv = cupyx.scipy.linalg.lu_factor(A)
# extract ``L`` and ``U`` from ``lu``
L = cupy.tril(lu, k=-1)
cupy.fill_diagonal(L, 1.)
L = L[:, :m]
U = cupy.triu(lu)
U = U[:n, :]
# check output shapes
assert lu.shape == (m, n)
assert L.shape == (m, min(m, n))
assert U.shape == (min(m, n), n)
assert piv.shape == (min(m, n),)
# apply pivot (on CPU since slaswp is not available in cupy)
piv = cupy.asnumpy(piv)
rows = numpy.arange(m)
for i, row in enumerate(piv):
if i != row:
rows[i], rows[row] = rows[row], rows[i]
PA = A[rows]
# check that reconstruction is close to original
LU = L.dot(U)
cupy.testing.assert_allclose(LU, PA, atol=1e-5)
示例4: assert_allclose
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import asnumpy [as 别名]
def assert_allclose(actual, desired, rtol=1e-7, atol=0, err_msg='',
verbose=True):
"""Raises an AssertionError if objects are not equal up to desired tolerance.
Args:
actual(numpy.ndarray or cupy.ndarray): The actual object to check.
desired(numpy.ndarray or cupy.ndarray): The desired, expected object.
rtol(float): Relative tolerance.
atol(float): Absolute tolerance.
err_msg(str): The error message to be printed in case of failure.
verbose(bool): If ``True``, the conflicting
values are appended to the error message.
.. seealso:: :func:`numpy.testing.assert_allclose`
""" # NOQA
numpy.testing.assert_allclose(
cupy.asnumpy(actual), cupy.asnumpy(desired),
rtol=rtol, atol=atol, err_msg=err_msg, verbose=verbose)
示例5: assert_array_almost_equal
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import asnumpy [as 别名]
def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True):
"""Raises an AssertionError if objects are not equal up to desired precision.
Args:
x(numpy.ndarray or cupy.ndarray): The actual object to check.
y(numpy.ndarray or cupy.ndarray): The desired, expected object.
decimal(int): Desired precision.
err_msg(str): The error message to be printed in case of failure.
verbose(bool): If ``True``, the conflicting
values are appended to the error message.
.. seealso:: :func:`numpy.testing.assert_array_almost_equal`
""" # NOQA
numpy.testing.assert_array_almost_equal(
cupy.asnumpy(x), cupy.asnumpy(y), decimal=decimal,
err_msg=err_msg, verbose=verbose)
示例6: array_repr
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import asnumpy [as 别名]
def array_repr(arr, max_line_width=None, precision=None, suppress_small=None):
"""Returns the string representation of an array.
Args:
arr (array_like): Input array. It should be able to feed to
:func:`cupy.asnumpy`.
max_line_width (int): The maximum number of line lengths.
precision (int): Floating point precision. It uses the current printing
precision of NumPy.
suppress_small (bool): If ``True``, very small numbers are printed as
zeros
Returns:
str: The string representation of ``arr``.
.. seealso:: :func:`numpy.array_repr`
"""
return numpy.array_repr(cupy.asnumpy(arr), max_line_width, precision,
suppress_small)
示例7: savez
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import asnumpy [as 别名]
def savez(file, *args, **kwds):
"""Saves one or more arrays into a file in uncompressed ``.npz`` format.
Arguments without keys are treated as arguments with automatic keys named
``arr_0``, ``arr_1``, etc. corresponding to the positions in the argument
list. The keys of arguments are used as keys in the ``.npz`` file, which
are used for accessing NpzFile object when the file is read by
:func:`cupy.load` function.
Args:
file (file or str): File or filename to save.
*args: Arrays with implicit keys.
**kwds: Arrays with explicit keys.
.. seealso:: :func:`numpy.savez`
"""
args = map(cupy.asnumpy, args)
for key in kwds:
kwds[key] = cupy.asnumpy(kwds[key])
numpy.savez(file, *args, **kwds)
示例8: get_percentiles
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import asnumpy [as 别名]
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)
示例9: _percentiles
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import asnumpy [as 别名]
def _percentiles(x, sigmas):
"""Compute percentiles for the given array.
Args:
x (array): Target array for which percentiles are computed.
sigmas (iterable): Percentile sigma values.
Returns:
array: List of percentiles. The list has the same length as the given
``sigma``.
"""
def _percentiles_cpu(_x):
try:
return numpy.percentile(_x, sigmas)
except IndexError:
return numpy.array((float('NaN'),) * 7)
# TODO(hvy): Make percentile computation faster for GPUs
if isinstance(x, cupy.ndarray):
x = cupy.asnumpy(x)
return cupy.asarray(_percentiles_cpu(x))
return _percentiles_cpu(x)
示例10: as_numpy
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import asnumpy [as 别名]
def as_numpy(x):
"""Convert to `numpy.ndarray`.
Args:
x (`numpy.ndarray` or `cupy.ndarray`): Arbitrary object that can be
converted to `numpy.ndarray`.
Returns:
`numpy.ndarray`: Converted array.
"""
if isinstance(x, Variable):
x = x.data
if np.isscalar(x):
return np.array(x)
elif isinstance(x, np.ndarray):
return x
return cp.asnumpy(x)
示例11: preview_convert
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import asnumpy [as 别名]
def preview_convert(iterator_a, iterator_b, g_a, g_b, device, gla, dst):
@chainer.training.make_extension()
def make_preview(trainer):
with chainer.using_config('train', False):
with chainer.no_backprop_mode():
x_a = iterator_a.next()
x_a = convert.concat_examples(x_a, device)
x_a = chainer.Variable(x_a)
x_b = iterator_b.next()
x_b = convert.concat_examples(x_b, device)
x_b = chainer.Variable(x_b)
x_ab = g_a(x_a)
x_ba = g_b(x_b)
x_bab = g_a(x_ba)
x_aba = g_b(x_ab)
preview_dir = '{}/preview'.format(dst)
if not os.path.exists(preview_dir):
os.makedirs(preview_dir)
image_dir = '{}/image'.format(dst)
if not os.path.exists(image_dir):
os.makedirs(image_dir)
names = ['a', 'ab', 'aba', 'b', 'ba', 'bab']
images = [x_a, x_ab, x_aba, x_b, x_ba, x_bab]
for n, i in zip(names, images):
i = cp.asnumpy(i.data)[:,:,padding:-padding,:].reshape(1, -1, 128)
image.save(image_dir+'/{}{}.jpg'.format(trainer.updater.epoch,n), i)
w = np.concatenate([gla.inverse(_i) for _i in dataset.reverse(i)])
dataset.save(preview_dir+'/{}{}.wav'.format(trainer.updater.epoch,n), 16000, w)
return make_preview
示例12: inverse
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import asnumpy [as 别名]
def inverse(self, spectrum, in_phase=None):
if in_phase is None:
in_phase = self.phase
else:
in_phase = cp.array(in_phase)
spectrum = cp.array(spectrum)
self.spectrum_buffer[:, -1] = spectrum * in_phase
self.absolute_buffer[:, -1] = spectrum
for _ in range(self.loop_num):
self.overwrap_buf *= 0
waves = cp.fft.ifft(self.spectrum_buffer, axis=2).real
last = self.spectrum_buffer
for i in range(self.buffer_size):
self.overwrap_buf[:,i*self.wave_dif:i*self.wave_dif+self.wave_len] += waves[:,i]
waves = cp.stack([self.overwrap_buf[:, i*self.wave_dif:i*self.wave_dif+self.wave_len]*self.window for i in range(self.buffer_size)], axis=1)
spectrum = cp.fft.fft(waves, axis=2)
self.spectrum_buffer = self.absolute_buffer * spectrum / (cp.abs(spectrum)+1e-10)
self.spectrum_buffer += 0.5 * (self.spectrum_buffer - last)
dst = cp.asnumpy(self.spectrum_buffer[:, 0])
self.absolute_buffer = cp.roll(self.absolute_buffer, -1, axis=1)
self.spectrum_buffer = cp.roll(self.spectrum_buffer, -1, axis=1)
return dst
示例13: serialize
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import asnumpy [as 别名]
def serialize(self, serializer):
self.best_loss = serializer("best_loss", self.best_loss)
# Make sure that best_loss is at the right location.
# After deserialization, the best_loss is
# instanciated on the CPU instead of the GPU.
if self.use_chainerx:
if self.gpu is None:
if self.best_loss is not None and not isinstance(self.best_loss, chainerx.ndarray):
self.best_loss = chainerx.array(self.best_loss)
else:
if self.best_loss is not None:
if isinstance(self.best_loss, chainerx.ndarray):
self.best_loss = chainerx.array(self.best_loss, device="cuda:%i"%self.gpu)
else:
self.best_loss = chainerx.array(self.best_loss, device="cuda:%i"%self.gpu)
#if self.gpu is not None and self.best_loss is not None:
else:
if self.gpu is None:
pass # best_loss should be on the cpu memory anyway
# if isinstance(self.best_loss, cupy.core.ndarray):
# self.best_loss = cupy.asnumpy(self.best_loss)
else:
import cupy
if self.best_loss is not None and (isinstance(self.best_loss, numpy.ndarray) or self.best_loss.device.id != self.gpu):
with cupy.cuda.Device(self.gpu):
self.best_loss = cupy.array(self.best_loss)
示例14: to_cpu
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import asnumpy [as 别名]
def to_cpu(obj):
return np.asnumpy(obj)
示例15: asnumpy
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import asnumpy [as 别名]
def asnumpy(x):
if cupy is not None:
return cupy.asnumpy(x)
else:
return numpy.asarray(x)