def set_theta(self, theta):
"""
Function sets theta. Can be called from constructor or outside.
"""
if isinstance(theta, (np.ndarray, np.generic)):
self.theta = theta
elif isinstance(theta, list):
self.theta = np.array(theta)
else:
self.theta = None
self.history = self.set_list(
self.history, 0, (np.copy(self.theta), 0, None))
self.step_no = 0
python类generic()的实例源码
def filter_invalid_json_values(self, dict):
for k, v in six.iteritems(dict):
if isinstance(v, (np.ndarray, np.generic)):
dict[k] = v.tolist()
if math.isnan(v) or math.isinf(v):
dict[k] = -1
def invalid_json_values(obj):
if isinstance(obj, np.generic):
return obj.item()
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, bytes):
return obj.decode('cp437')
if isinstance(map, type) and isinstance(obj, map):
# python 3 map
return list(obj)
raise TypeError('Invalid data type passed to json encoder: ' + type(obj).__name__)
def contains(self, x):
if isinstance(x, int):
as_int = x
elif isinstance(x, (np.generic, np.ndarray)) and (x.dtype.kind in np.typecodes['AllInteger'] and x.shape == ()):
as_int = int(x)
else:
return False
return as_int >= 0 and as_int < self.n
def capture_frame(self, frame):
if not isinstance(frame, (np.ndarray, np.generic)):
raise error.InvalidFrame('Wrong type {} for {} (must be np.ndarray or np.generic)'.format(type(frame), frame))
if frame.shape != self.frame_shape:
raise error.InvalidFrame("Your frame has shape {}, but the VideoRecorder is configured for shape {}.".format(frame.shape, self.frame_shape))
if frame.dtype != np.uint8:
raise error.InvalidFrame("Your frame has data type {}, but we require uint8 (i.e. RGB values from 0-255).".format(frame.dtype))
if distutils.version.LooseVersion(np.__version__) >= distutils.version.LooseVersion('1.9.0'):
self.proc.stdin.write(frame.tobytes())
else:
self.proc.stdin.write(frame.tostring())
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])
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))
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)
def feature_names(self, names):
"Stores the text labels for features"
if len(names) != self.num_features:
raise ValueError("Number of names do not match the number of features!")
if not isinstance(names, (Sequence, np.ndarray, np.generic)):
raise ValueError("Input is not a sequence. Ensure names are in the same order and length as features.")
self.__feature_names = np.array(names)
def is_np_scalar(x):
"""
Check np types like np.int64
"""
return isinstance(x, np.generic)
def contains(self, x):
if not isinstance(x, (tuple, list, np.generic, np.ndarray)):
return False
return np.shape(x) == self.shape and np.sum(x) == 1 and np.max(x) == 1
def contains(self, x):
if isinstance(x, int):
as_int = x
elif isinstance(x, (np.generic, np.ndarray)) and (x.dtype.kind in np.typecodes['AllInteger'] and x.shape == ()):
as_int = int(x)
else:
return False
return as_int >= 0 and as_int < self.n
def __setitem__(self, in_slice, value):
"""Set ndarray value"""
if (not isinstance(in_slice, slice) or
in_slice.start is not None
or in_slice.stop is not None):
raise ValueError('Array only support set from numpy array')
if isinstance(value, NDArray):
if value.handle is not self.handle:
value.copyto(self)
elif isinstance(value, (np.ndarray, np.generic)):
self._sync_copyfrom(value)
else:
raise TypeError('type %s not supported' % str(type(value)))
common.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def _validate_date_like_dtype(dtype):
try:
typ = np.datetime_data(dtype)[0]
except ValueError as e:
raise TypeError('%s' % e)
if typ != 'generic' and typ != 'ns':
raise ValueError('%r is too specific of a frequency, try passing %r' %
(dtype.name, dtype.type.__name__))
common.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 32
收藏 0
点赞 0
评论 0
def _get_dtype_from_object(dtype):
"""Get a numpy dtype.type-style object. This handles the datetime64[ns]
and datetime64[ns, TZ] compat
Notes
-----
If nothing can be found, returns ``object``.
"""
# type object from a dtype
if isinstance(dtype, type) and issubclass(dtype, np.generic):
return dtype
elif is_categorical(dtype):
return CategoricalDtype().type
elif is_datetimetz(dtype):
return DatetimeTZDtype(dtype).type
elif isinstance(dtype, np.dtype): # dtype object
try:
_validate_date_like_dtype(dtype)
except TypeError:
# should still pass if we don't have a datelike
pass
return dtype.type
elif isinstance(dtype, compat.string_types):
if dtype == 'datetime' or dtype == 'timedelta':
dtype += '64'
try:
return _get_dtype_from_object(getattr(np, dtype))
except (AttributeError, TypeError):
# handles cases like _get_dtype(int)
# i.e., python objects that are valid dtypes (unlike user-defined
# types, in general)
# TypeError handles the float16 typecode of 'e'
# further handle internal types
pass
return _get_dtype_from_object(np.dtype(dtype))
test_core.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
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])
test_core.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
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))
def to_numpy(var):
#if ia.is_numpy_array(var):
if isinstance(var, (np.ndarray, np.generic)):
return var
else:
return var.data.cpu().numpy()
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])
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))