本文整理汇总了Python中numpy.dtype方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.dtype方法的具体用法?Python numpy.dtype怎么用?Python numpy.dtype使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.dtype方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import dtype [as 别名]
def __init__(self, resolution=1024, num_channels=3, dtype='uint8', dynamic_range=[0,255], label_size=0, label_dtype='float32'):
self.resolution = resolution
self.resolution_log2 = int(np.log2(resolution))
self.shape = [num_channels, resolution, resolution]
self.dtype = dtype
self.dynamic_range = dynamic_range
self.label_size = label_size
self.label_dtype = label_dtype
self._tf_minibatch_var = None
self._tf_lod_var = None
self._tf_minibatch_np = None
self._tf_labels_np = None
assert self.resolution == 2 ** self.resolution_log2
with tf.name_scope('Dataset'):
self._tf_minibatch_var = tf.Variable(np.int32(0), name='minibatch_var')
self._tf_lod_var = tf.Variable(np.int32(0), name='lod_var')
示例2: serialize_dtype
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import dtype [as 别名]
def serialize_dtype(o):
"""
Serializes a :obj:`numpy.dtype`.
Args:
o (:obj:`numpy.dtype`): :obj:`dtype` to be serialized.
Returns:
A dictionary that can be passed to :obj:`json.dumps`.
"""
if len(o) == 0:
return dict(
_type='np.dtype',
descr=str(o))
return dict(
_type='np.dtype',
descr=o.descr)
# res = []
# for k in range(len(o)):
# res.append((o.names[k], str(o[k])))
# return dict(
# _type='np.dtype',
# desc=res)
示例3: deserialize_dtype
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import dtype [as 别名]
def deserialize_dtype(d):
"""
Deserializes a JSONified :obj:`numpy.dtype`.
Args:
d (:obj:`dict`): A dictionary representation of a :obj:`dtype` object.
Returns:
A :obj:`dtype` object.
"""
if isinstance(d['descr'], six.string_types):
return np.dtype(d['descr'])
descr = []
for col in d['descr']:
col_descr = []
for c in col:
if isinstance(c, six.string_types):
col_descr.append(str(c))
elif type(c) is list:
col_descr.append(tuple(c))
else:
col_descr.append(c)
descr.append(tuple(col_descr))
return np.dtype(descr)
示例4: serialize_ndarray_b64
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import dtype [as 别名]
def serialize_ndarray_b64(o):
"""
Serializes a :obj:`numpy.ndarray` in a format where the datatype and shape are
human-readable, but the array data itself is binary64 encoded.
Args:
o (:obj:`numpy.ndarray`): :obj:`ndarray` to be serialized.
Returns:
A dictionary that can be passed to :obj:`json.dumps`.
"""
if o.flags['C_CONTIGUOUS']:
o_data = o.data
else:
o_data = np.ascontiguousarray(o).data
data_b64 = base64.b64encode(o_data)
return dict(
_type='np.ndarray',
data=data_b64.decode('utf-8'),
dtype=o.dtype,
shape=o.shape)
示例5: deserialize_ndarray
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import dtype [as 别名]
def deserialize_ndarray(d):
"""
Deserializes a JSONified :obj:`numpy.ndarray`. Can handle arrays serialized
using any of the methods in this module: :obj:`"npy"`, :obj:`"b64"`,
:obj:`"readable"`.
Args:
d (`dict`): A dictionary representation of an :obj:`ndarray` object.
Returns:
An :obj:`ndarray` object.
"""
if 'data' in d:
x = np.fromstring(
base64.b64decode(d['data']),
dtype=d['dtype'])
x.shape = d['shape']
return x
elif 'value' in d:
return np.array(d['value'], dtype=d['dtype'])
elif 'npy' in d:
return deserialize_ndarray_npy(d)
else:
raise ValueError('Malformed np.ndarray encoding.')
示例6: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import dtype [as 别名]
def __init__(self, model, dtypestr='float32'):
"""
:param model: An instance of the cleverhans.model.Model class.
:param back: The backend to use. Inherited from AttackBase class.
:param dtypestr: datatype of the input data samples and crafted
adversarial attacks.
"""
# Validate the input arguments.
if dtypestr != 'float32' and dtypestr != 'float64':
raise ValueError("Unexpected input for argument dtypestr.")
import tensorflow as tf
tfe = tf.contrib.eager
self.tf_dtype = tf.as_dtype(dtypestr)
self.np_dtype = np.dtype(dtypestr)
if not isinstance(model, Model):
raise ValueError("The model argument should be an instance of"
" the cleverhans.model.Model class.")
# Prepare attributes
self.model = model
self.dtypestr = dtypestr
示例7: image_reslice
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import dtype [as 别名]
def image_reslice(image, spec, method=None, fill=0, dtype=None, weights=None, image_type=None):
'''
image_reslice(image, spec) yields a duplicate of the given image resliced to have the voxels
indicated by the given image spec. Note that spec may be an image itself.
Optional arguments that can be passed to image_interpolate() (asside from affine) are allowed
here and are passed through.
'''
if image_type is None and is_image(image): image_type = to_image_type(image)
spec = to_image_spec(spec)
image = to_image(image)
# we make a big mesh and interpolate at these points...
imsh = spec['image_shape']
(args, kw) = ([np.arange(n) for n in imsh[:3]], {'indexing': 'ij'})
ijk = np.asarray([u.flatten() for u in np.meshgrid(*args, **kw)])
ijk = np.dot(spec['affine'], np.vstack([ijk, np.ones([1,ijk.shape[1]])]))[:3]
# interpolate here...
u = image_interpolate(image, ijk, method=method, fill=fill, dtype=dtype, weights=weights)
return to_image((np.reshape(u, imsh), spec), image_type=image_type)
示例8: astype
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import dtype [as 别名]
def astype(self, dtype, copy=True):
"""Returns a copy of the array after casting to a specified type.
Parameters
----------
dtype : numpy.dtype or str
The type of the returned array.
copy : bool
Default `True`. By default, astype always returns a newly
allocated ndarray on the same context. If this is set to
`False`, and the dtype requested is the same as the ndarray's
dtype, the ndarray is returned instead of a copy.
Examples
--------
>>> x = mx.nd.sparse.zeros('row_sparse', (2,3), dtype='float32')
>>> y = x.astype('int32')
>>> y.dtype
<type 'numpy.int32'>
"""
if not copy and np.dtype(dtype) == self.dtype:
return self
res = zeros(shape=self.shape, ctx=self.context,
dtype=dtype, stype=self.stype)
self.copyto(res)
return res
示例9: asscipy
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import dtype [as 别名]
def asscipy(self):
"""Returns a ``scipy.sparse.csr.csr_matrix`` object with value copied from this array
Examples
--------
>>> x = mx.nd.sparse.zeros('csr', (2,3))
>>> y = x.asscipy()
>>> type(y)
<type 'scipy.sparse.csr.csr_matrix'>
>>> y
<2x3 sparse matrix of type '<type 'numpy.float32'>'
with 0 stored elements in Compressed Sparse Row format>
"""
data = self.data.asnumpy()
indices = self.indices.asnumpy()
indptr = self.indptr.asnumpy()
if not spsp:
raise ImportError("scipy is not available. \
Please check if the scipy python bindings are installed.")
return spsp.csr_matrix((data, indices, indptr), shape=self.shape, dtype=self.dtype)
# pylint: disable=abstract-method
示例10: _new_alloc_handle
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import dtype [as 别名]
def _new_alloc_handle(shape, ctx, delay_alloc, dtype=mx_real_t):
"""Return a new handle with specified shape and context.
Empty handle is only used to hold results.
Returns
-------
handle
A new empty `NDArray` handle.
"""
hdl = NDArrayHandle()
check_call(_LIB.MXNDArrayCreateEx(
c_array_buf(mx_uint, native_array('I', shape)),
mx_uint(len(shape)),
ctypes.c_int(ctx.device_typeid),
ctypes.c_int(ctx.device_id),
ctypes.c_int(int(delay_alloc)),
ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dtype).type])),
ctypes.byref(hdl)))
return hdl
示例11: _prepare_value_nd
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import dtype [as 别名]
def _prepare_value_nd(self, value, vshape):
"""Given value and vshape, create an `NDArray` from value with the same
context and dtype as the current one and broadcast it to vshape."""
if isinstance(value, numeric_types):
value_nd = full(shape=vshape, val=value, ctx=self.context, dtype=self.dtype)
elif isinstance(value, NDArray):
value_nd = value.as_in_context(self.context)
if value_nd.dtype != self.dtype:
value_nd = value_nd.astype(self.dtype)
else:
try:
value_nd = array(value, ctx=self.context, dtype=self.dtype)
except:
raise TypeError('NDArray does not support assignment with non-array-like'
' object %s of type %s' % (str(value), str(type(value))))
if value_nd.shape != vshape:
value_nd = value_nd.broadcast_to(vshape)
return value_nd
示例12: dtype
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import dtype [as 别名]
def dtype(self):
"""Data-type of the array's elements.
Returns
-------
numpy.dtype
This NDArray's data type.
Examples
--------
>>> x = mx.nd.zeros((2,3))
>>> x.dtype
<type 'numpy.float32'>
>>> y = mx.nd.zeros((2,3), dtype='int32')
>>> y.dtype
<type 'numpy.int32'>
"""
mx_dtype = ctypes.c_int()
check_call(_LIB.MXNDArrayGetDType(
self.handle, ctypes.byref(mx_dtype)))
return _DTYPE_MX_TO_NP[mx_dtype.value]
示例13: T
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import dtype [as 别名]
def T(self):
"""Returns a copy of the array with axes transposed.
Equivalent to ``mx.nd.transpose(self)`` except that
self is returned if ``self.ndim < 2``.
Unlike ``numpy.ndarray.T``, this function returns a copy
rather than a view of the array unless ``self.ndim < 2``.
Examples
--------
>>> x = mx.nd.arange(0,6).reshape((2,3))
>>> x.asnumpy()
array([[ 0., 1., 2.],
[ 3., 4., 5.]], dtype=float32)
>>> x.T.asnumpy()
array([[ 0., 3.],
[ 1., 4.],
[ 2., 5.]], dtype=float32)
"""
if len(self.shape) < 2:
return self
return op.transpose(self)
# pylint: enable= invalid-name, undefined-variable
示例14: asnumpy
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import dtype [as 别名]
def asnumpy(self):
"""Returns a ``numpy.ndarray`` object with value copied from this array.
Examples
--------
>>> x = mx.nd.ones((2,3))
>>> y = x.asnumpy()
>>> type(y)
<type 'numpy.ndarray'>
>>> y
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> z = mx.nd.ones((2,3), dtype='int32')
>>> z.asnumpy()
array([[1, 1, 1],
[1, 1, 1]], dtype=int32)
"""
data = np.empty(self.shape, dtype=self.dtype)
check_call(_LIB.MXNDArraySyncCopyToCPU(
self.handle,
data.ctypes.data_as(ctypes.c_void_p),
ctypes.c_size_t(data.size)))
return data
示例15: asscalar
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import dtype [as 别名]
def asscalar(self):
"""Returns a scalar whose value is copied from this array.
This function is equivalent to ``self.asnumpy()[0]``. This NDArray must have shape (1,).
Examples
--------
>>> x = mx.nd.ones((1,), dtype='int32')
>>> x.asscalar()
1
>>> type(x.asscalar())
<type 'numpy.int32'>
"""
if self.shape != (1,):
raise ValueError("The current array is not a scalar")
return self.asnumpy()[0]