本文整理汇总了Python中cupy.array方法的典型用法代码示例。如果您正苦于以下问题:Python cupy.array方法的具体用法?Python cupy.array怎么用?Python cupy.array使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cupy
的用法示例。
在下文中一共展示了cupy.array方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import array [as 别名]
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)
示例2: do_eval
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import array [as 别名]
def do_eval(args):
ced, charlist, chardict = load_encdec_from_config(args.config, args.model)
if args.gpu is not None:
chainer.cuda.Device(args.gpu).use()
import cupy
ced = ced.to_gpu(args.gpu)
xp = cupy
else:
xp = np
def enc(word):
w_array=xp.array([chardict[c] for c in word], dtype=xp.int32)
hx=ced.enc.compute_h((w_array,), train=False)
return hx
def dec(hx):
decoded = ced.dec.decode(hx, length = 40, train = False)
return "".join([charlist[int(idx)] for idx in decoded[0]])
IPython.embed()
示例3: generate_voc_encodings
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import array [as 别名]
def generate_voc_encodings(encoder, charlist, voc_list, mb_size=1024):
dataset = encode_voc_list(voc_list, charlist)
print "voc_size:", len(dataset)
xp = encoder.xp
encodings_list = []
cursor = 0
while cursor < len(dataset):
batch = dataset[cursor:cursor+mb_size]
if xp != np:
batch = [xp.array(bb) for bb in batch]
cursor += mb_size
encodings = encoder.compute_h(batch, train = False, use_workaround = True)
encodings_list.append(encodings.data.reshape(encodings.data.shape[1:]))
print "processed", cursor
result = np.vstack(encodings_list)
return result
示例4: to_cpu
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import array [as 别名]
def to_cpu(array, stream=None):
"""Copies the given GPU array to host CPU.
Args:
array (*array*, None, list or tuple):
Array or arrays to be sent to CPU.
stream (cupy.cuda.Stream): CUDA stream.
Returns:
numpy.ndarray, list or tuple: Array on CPU.
If some of the arrays are already on CPU, then this function just
returns those arrays without performing any copy.
If input arrays include `None`, it is returned as `None` as is.
"""
return _backend._convert_arrays(
array, lambda arr: _array_to_cpu(arr, stream))
示例5: get_array_module
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import array [as 别名]
def get_array_module(*args):
"""Gets an appropriate one from :mod:`numpy` or :mod:`cupy`.
This is almost equivalent to :func:`cupy.get_array_module`. The differences
are that this function can be used even if CUDA is not available and that
it will return their data arrays' array module for
:class:`~chainer.Variable` arguments.
.. deprecated:: v5.0.0
This API is deprecated. Please use
:func:`~chainer.backend.get_array_module` instead.
Args:
args: Values to determine whether NumPy or CuPy should be used.
Returns:
module: :mod:`cupy` or :mod:`numpy` is returned based on the types of
the arguments.
"""
return chainer.backend.get_array_module(*args)
示例6: _suppress
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import array [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
示例7: __init__
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import array [as 别名]
def __init__(self, numpy_object, cupy_object, array=None):
"""
_RecursiveAttr initializer.
Args:
numpy_object (method): NumPy method.
cupy_method (method): Corresponding CuPy method.
array (ndarray): Acts as flag to know if _RecursiveAttr object
is called from ``ndarray`` class. Also, acts as container for
modifying args in case it is called from ``ndarray``.
None otherwise.
"""
self._numpy_object = numpy_object
self._cupy_object = cupy_object
self._fallback_array = array
示例8: _update_cupy_array
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import array [as 别名]
def _update_cupy_array(self):
"""
Updates _cupy_array from _numpy_array.
To be executed before calling cupy function.
"""
base = self.base
if base is None:
if self._remember_numpy:
if self._cupy_array is None:
self._cupy_array = cp.array(self._numpy_array)
else:
self._cupy_array[:] = self._numpy_array
else:
if base._remember_numpy:
base._update_cupy_array()
示例9: get
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import array [as 别名]
def get(self, stream=None):
"""Returns a copy of the array on host memory.
Args:
stream (cupy.cuda.Stream): CUDA stream object. If it is given, the
copy runs asynchronously. Otherwise, the copy is synchronous.
Returns:
scipy.sparse.dia_matrix: Copy of the array on host memory.
"""
if not _scipy_available:
raise RuntimeError('scipy is not available')
data = self.data.get(stream)
offsets = self.offsets.get(stream)
return scipy.sparse.dia_matrix((data, offsets), shape=self._shape)
示例10: get
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import array [as 别名]
def get(self, stream=None):
"""Returns a copy of the array on host memory.
Args:
stream (cupy.cuda.Stream): CUDA stream object. If it is given, the
copy runs asynchronously. Otherwise, the copy is synchronous.
Returns:
scipy.sparse.coo_matrix: Copy of the array on host memory.
"""
if not _scipy_available:
raise RuntimeError('scipy is not available')
data = self.data.get(stream)
row = self.row.get(stream)
col = self.col.get(stream)
return scipy.sparse.coo_matrix(
(data, (row, col)), shape=self.shape)
示例11: minimum_filter1d
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import array [as 别名]
def minimum_filter1d(input, size, axis=-1, output=None, mode="reflect",
cval=0.0, origin=0):
"""Compute the minimum filter along a single axis.
Args:
input (cupy.ndarray): The input array.
size (int): Length of the minimum filter.
axis (int): The axis of input along which to calculate. Default is -1.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
origin (int): The origin parameter controls the placement of the
filter, relative to the center of the current element of the
input. Default is ``0``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.minimum_filter1d`
"""
return _min_or_max_1d(input, size, axis, output, mode, cval, origin, 'min')
示例12: _check_nd_args
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import array [as 别名]
def _check_nd_args(input, weights, mode, origins, wghts_name='filter weights'):
if input.dtype.kind == 'c':
raise TypeError('Complex type not supported')
_check_mode(mode)
# The integer type to use for indices in the input array
# The indices actually use byte positions and we can't just use
# input.nbytes since that won't tell us the number of bytes between the
# first and last elements when the array is non-contiguous
nbytes = sum((x-1)*abs(stride) for x, stride in
zip(input.shape, input.strides)) + input.dtype.itemsize
int_type = 'int' if nbytes < (1 << 31) else 'ptrdiff_t'
# However, weights must always be 2 GiB or less
if weights.nbytes > (1 << 31):
raise RuntimeError('weights must be 2 GiB or less, use FFTs instead')
weight_dims = [x for x in weights.shape if x != 0]
if len(weight_dims) != input.ndim:
raise RuntimeError('{} array has incorrect shape'.format(wghts_name))
origins = _fix_sequence_arg(origins, len(weight_dims), 'origin', int)
for origin, width in zip(origins, weight_dims):
_check_origin(origin, width)
return tuple(origins), int_type
示例13: standard_deviation
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import array [as 别名]
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))
示例14: train_gmm
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import array [as 别名]
def train_gmm(X, max_iter, tol, means, covariances):
xp = cupy.get_array_module(X)
lower_bound = -np.infty
converged = False
weights = xp.array([0.5, 0.5], dtype=np.float32)
inv_cov = 1 / xp.sqrt(covariances)
for n_iter in range(max_iter):
prev_lower_bound = lower_bound
log_prob_norm, log_resp = e_step(X, inv_cov, means, weights)
weights, means, covariances = m_step(X, xp.exp(log_resp))
inv_cov = 1 / xp.sqrt(covariances)
lower_bound = log_prob_norm
change = lower_bound - prev_lower_bound
if abs(change) < tol:
converged = True
break
if not converged:
print('Failed to converge. Increase max-iter or tol.')
return inv_cov, means, weights, covariances
示例15: inverse
# 需要导入模块: import cupy [as 别名]
# 或者: from cupy import array [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