本文整理匯總了Python中numpy.generic方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.generic方法的具體用法?Python numpy.generic怎麽用?Python numpy.generic使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.generic方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_sparse_nd_setitem
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import generic [as 別名]
def test_sparse_nd_setitem():
def check_sparse_nd_setitem(stype, shape, dst):
x = mx.nd.zeros(shape=shape, stype=stype)
x[:] = dst
dst_nd = mx.nd.array(dst) if isinstance(dst, (np.ndarray, np.generic)) else dst
assert np.all(x.asnumpy() == dst_nd.asnumpy() if isinstance(dst_nd, NDArray) else dst)
shape = rand_shape_2d()
for stype in ['row_sparse', 'csr']:
# ndarray assignment
check_sparse_nd_setitem(stype, shape, rand_ndarray(shape, 'default'))
check_sparse_nd_setitem(stype, shape, rand_ndarray(shape, stype))
# numpy assignment
check_sparse_nd_setitem(stype, shape, np.ones(shape))
# scalar assigned to row_sparse NDArray
check_sparse_nd_setitem('row_sparse', shape, 2)
示例2: test_char_radd
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import generic [as 別名]
def test_char_radd(self):
# GH issue 9620, reached gentype_add and raise TypeError
np_s = np.string_('abc')
np_u = np.unicode_('abc')
s = b'def'
u = u'def'
assert_(np_s.__radd__(np_s) is NotImplemented)
assert_(np_s.__radd__(np_u) is NotImplemented)
assert_(np_s.__radd__(s) is NotImplemented)
assert_(np_s.__radd__(u) is NotImplemented)
assert_(np_u.__radd__(np_s) is NotImplemented)
assert_(np_u.__radd__(np_u) is NotImplemented)
assert_(np_u.__radd__(s) is NotImplemented)
assert_(np_u.__radd__(u) is NotImplemented)
assert_(s + np_s == b'defabc')
assert_(u + np_u == u'defabc')
class Mystr(str, np.generic):
# would segfault
pass
ret = s + Mystr('abc')
assert_(type(ret) is type(s))
示例3: normalization
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import generic [as 別名]
def normalization(s: Union[np.ndarray, np.generic],
dt: int) -> Union[np.ndarray, np.generic]:
""""
Parameters
----------
s : numpy.ndarray
Scales.
dt : int
Time step.
Returns
-------
numpy.ndarray
Normalized data.
"""
return np.sqrt((2 * np.pi * s) / dt)
示例4: _validate_date_like_dtype
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import generic [as 別名]
def _validate_date_like_dtype(dtype):
"""
Check whether the dtype is a date-like dtype. Raises an error if invalid.
Parameters
----------
dtype : dtype, type
The dtype to check.
Raises
------
TypeError : The dtype could not be casted to a date-like dtype.
ValueError : The dtype is an illegal date-like dtype (e.g. the
the frequency provided is too specific)
"""
try:
typ = np.datetime_data(dtype)[0]
except ValueError as e:
raise TypeError('{error}'.format(error=e))
if typ != 'generic' and typ != 'ns':
msg = '{name!r} is too specific of a frequency, try passing {type!r}'
raise ValueError(msg.format(name=dtype.name, type=dtype.type.__name__))
示例5: convert_input
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import generic [as 別名]
def convert_input(X, columns=None, deep=False):
"""
Unite data into a DataFrame.
Objects that do not contain column names take the names from the argument.
Optionally perform deep copy of the data.
"""
if not isinstance(X, pd.DataFrame):
if isinstance(X, pd.Series):
X = pd.DataFrame(X, copy=deep)
else:
if columns is not None and np.size(X,1) != len(columns):
raise ValueError('The count of the column names does not correspond to the count of the columns')
if isinstance(X, list):
X = pd.DataFrame(X, columns=columns, copy=deep) # lists are always copied, but for consistency, we still pass the argument
elif isinstance(X, (np.generic, np.ndarray)):
X = pd.DataFrame(X, columns=columns, copy=deep)
elif isinstance(X, csr_matrix):
X = pd.DataFrame(X.todense(), columns=columns, copy=deep)
else:
raise ValueError('Unexpected input type: %s' % (str(type(X))))
elif deep:
X = X.copy(deep=True)
return X
示例6: get_numpy_dtype
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import generic [as 別名]
def get_numpy_dtype(obj):
"""Return NumPy data type associated to obj
Return None if NumPy is not available
or if obj is not a NumPy array or scalar"""
if ndarray is not FakeObject:
# NumPy is available
import numpy as np
if isinstance(obj, np.generic) or isinstance(obj, np.ndarray):
# Numpy scalars all inherit from np.generic.
# Numpy arrays all inherit from np.ndarray.
# If we check that we are certain we have one of these
# types then we are less likely to generate an exception below.
try:
return obj.dtype.type
except (AttributeError, RuntimeError):
# AttributeError: some NumPy objects have no dtype attribute
# RuntimeError: happens with NetCDF objects (Issue 998)
return
#==============================================================================
# Pandas support
#==============================================================================
示例7: _infer_dtype
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import generic [as 別名]
def _infer_dtype(value):
"""Infer the dtype for the features.
It is required as the input is usually array of objects before padding.
"""
while isinstance(value, (list, tuple)) and len(value) > 0:
value = value[0]
if not isinstance(value, Iterable):
return np.array(value).dtype
if value is not None and len(value) > 0 and np.issubdtype(
np.array(value).dtype, np.generic):
dtype = np.array(value[0]).dtype
else:
dtype = value.dtype
# Single Precision
if dtype == np.double:
dtype = np.float32
return dtype
示例8: cast_if_numpy_array
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import generic [as 別名]
def cast_if_numpy_array(xp, array, chx_expected_dtype):
"""Casts NumPy result array to match the dtype of ChainerX's corresponding
result.
This function receives result arrays for both NumPy and ChainerX and only
converts dtype of the NumPy array.
"""
if xp is chainerx:
assert isinstance(array, chainerx.ndarray)
return array
if xp is numpy:
assert isinstance(array, (numpy.ndarray, numpy.generic))
# Dtype conversion to allow comparing the correctnesses of the values.
return array.astype(chx_expected_dtype, copy=False)
assert False
示例9: fix_by_image_dimensions
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import generic [as 別名]
def fix_by_image_dimensions(self, height, width=None):
if isinstance(height, (tuple, list)):
assert width is None
height, width = height[0], height[1]
elif isinstance(height, (np.ndarray, np.generic)):
assert width is None
height, width = height.shape[0], height.shape[1]
else:
assert width is not None
assert isinstance(height, int)
assert isinstance(width, int)
self.x1 = int(np.clip(self.x1, 0, width-1))
self.x2 = int(np.clip(self.x2, 0, width-1))
self.y1 = int(np.clip(self.y1, 0, height-1))
self.y2 = int(np.clip(self.y2, 0, height-1))
if self.x1 > self.x2:
self.x1, self.x2 = self.x2, self.x1
if self.y1 > self.y2:
self.y1, self.y2 = self.y2, self.y1
if self.x1 == self.x2:
if self.x1 > 0:
self.x1 = self.x1 - 1
else:
self.x2 = self.x2 + 1
if self.y1 == self.y2:
if self.y1 > 0:
self.y1 = self.y1 - 1
else:
self.y2 = self.y2 + 1
#self.width = self.x2 - self.x1
#self.height = self.y2 - self.y1
示例10: _bytesArrayToList
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import generic [as 別名]
def _bytesArrayToList(data):
if type(data) in (bytes, str):
is_list = False
elif isinstance(data, (np.ndarray, np.generic)):
if len(data.shape) == 0:
is_list = False
data = data.tolist() # tolist will return a scalar in this case
if type(data) in (list, tuple):
is_list = True
else:
is_list = False
else:
is_list = True
elif type(data) in (list, tuple):
is_list = True
else:
is_list = False
if is_list:
out = []
for item in data:
out.append(_bytesArrayToList(item)) # recursive call
elif type(data) is bytes:
out = data.decode("utf-8")
else:
out = data
return out
示例11: bytesArrayToList
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import generic [as 別名]
def bytesArrayToList(data):
if type(data) in (bytes, str):
is_list = False
elif isinstance(data, (np.ndarray, np.generic)):
if len(data.shape) == 0:
is_list = False
data = data.tolist() # tolist will return a scalar in this case
if type(data) in (list, tuple):
is_list = True
else:
is_list = False
else:
is_list = True
elif type(data) in (list, tuple):
is_list = True
else:
is_list = False
if is_list:
out = []
for item in data:
out.append(bytesArrayToList(item)) # recursive call
elif type(data) is bytes:
out = data.decode("utf-8")
else:
out = data
return out
示例12: test_oddfeatures_3
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import generic [as 別名]
def test_oddfeatures_3(self):
# Tests some generic features
atest = array([10], mask=True)
btest = array([20])
idx = atest.mask
atest[idx] = btest[idx]
assert_equal(atest, [20])
示例13: test_tolist_specialcase
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import generic [as 別名]
def test_tolist_specialcase(self):
# Test mvoid.tolist: make sure we return a standard Python object
a = array([(0, 1), (2, 3)], dtype=[('a', int), ('b', int)])
# w/o mask: each entry is a np.void whose elements are standard Python
for entry in a:
for item in entry.tolist():
assert_(not isinstance(item, np.generic))
# w/ mask: each entry is a ma.void whose elements should be
# standard Python
a.mask[0] = (0, 1)
for entry in a:
for item in entry.tolist():
assert_(not isinstance(item, np.generic))
示例14: test_masked_where_oddities
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import generic [as 別名]
def test_masked_where_oddities(self):
# Tests some generic features.
atest = ones((10, 10, 10), dtype=float)
btest = zeros(atest.shape, MaskType)
ctest = masked_where(btest, atest)
assert_equal(atest, ctest)
示例15: is_timedelta64_ns_dtype
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import generic [as 別名]
def is_timedelta64_ns_dtype(arr_or_dtype):
"""
Check whether the provided array or dtype is of the timedelta64[ns] dtype.
This is a very specific dtype, so generic ones like `np.timedelta64`
will return False if passed into this function.
Parameters
----------
arr_or_dtype : array-like
The array or dtype to check.
Returns
-------
boolean : Whether or not the array or dtype is of the
timedelta64[ns] dtype.
Examples
--------
>>> is_timedelta64_ns_dtype(np.dtype('m8[ns]'))
True
>>> is_timedelta64_ns_dtype(np.dtype('m8[ps]')) # Wrong frequency
False
>>> is_timedelta64_ns_dtype(np.array([1, 2], dtype='m8[ns]'))
True
>>> is_timedelta64_ns_dtype(np.array([1, 2], dtype=np.timedelta64))
False
"""
return _is_dtype(arr_or_dtype, lambda dtype: dtype == _TD_DTYPE)