本文整理汇总了Python中numpy.uint32方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.uint32方法的具体用法?Python numpy.uint32怎么用?Python numpy.uint32使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.uint32方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: residual_resample
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import uint32 [as 别名]
def residual_resample(weights):
n = len(weights)
indices = np.zeros(n, np.uint32)
# take int(N*w) copies of each weight
num_copies = (n * weights).astype(np.uint32)
k = 0
for i in range(n):
for _ in range(num_copies[i]): # make n copies
indices[k] = i
k += 1
# use multinormial resample on the residual to fill up the rest.
residual = weights - num_copies # get fractional part
residual /= np.sum(residual)
cumsum = np.cumsum(residual)
cumsum[-1] = 1
indices[k:n] = np.searchsorted(cumsum, np.random.uniform(0, 1, n - k))
return indices
示例2: create_indices
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import uint32 [as 别名]
def create_indices(positions, weights):
n = len(weights)
indices = np.zeros(n, np.uint32)
cumsum = np.cumsum(weights)
i, j = 0, 0
while i < n:
if positions[i] < cumsum[j]:
indices[i] = j
i += 1
else:
j += 1
return indices
### end rlabbe's resampling functions
示例3: test_can_cast
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import uint32 [as 别名]
def test_can_cast():
tests = ((np.float32, np.float32, True, True, True),
(np.float64, np.float32, True, True, True),
(np.complex128, np.float32, False, False, False),
(np.float32, np.complex128, True, True, True),
(np.float32, np.uint8, False, True, True),
(np.uint32, np.complex128, True, True, True),
(np.int64, np.float32, True, True, True),
(np.complex128, np.int16, False, False, False),
(np.float32, np.int16, False, True, True),
(np.uint8, np.int16, True, True, True),
(np.uint16, np.int16, False, True, True),
(np.int16, np.uint16, False, False, True),
(np.int8, np.uint16, False, False, True),
(np.uint16, np.uint8, False, True, True),
)
for intype, outtype, def_res, scale_res, all_res in tests:
assert_equal(def_res, can_cast(intype, outtype))
assert_equal(scale_res, can_cast(intype, outtype, False, True))
assert_equal(all_res, can_cast(intype, outtype, True, True))
示例4: stream2words
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import uint32 [as 别名]
def stream2words(stream, track=None):
"""Convert a stream of integers to uint32 header words.
Parameters
----------
stream : `~numpy.array` of int
For each int, every bit corresponds to a particular track.
track : int, array, or None, optional
The track to extract. If `None` (default), extract all tracks that
the type of int in the stream can hold.
"""
if track is None:
track = np.arange(stream.dtype.itemsize * 8, dtype=stream.dtype)
track_sel = ((stream.reshape(-1, 32, 1) >> track) & 1).astype(np.uint32)
track_sel <<= np.arange(31, -1, -1, dtype=np.uint32).reshape(-1, 1)
words = np.bitwise_or.reduce(track_sel, axis=1)
return words.squeeze()
示例5: words2stream
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import uint32 [as 别名]
def words2stream(words):
"""Convert a set of uint32 header words to a stream of integers.
Parameters
----------
words : `~numpy.array` of uint32
Returns
-------
stream : `~numpy.array` of int
For each int, every bit corresponds to a particular track.
"""
ntrack = words.shape[1]
dtype = MARK4_DTYPES[ntrack]
nbits = words.dtype.itemsize * 8
bit = np.arange(nbits - 1, -1, -1, dtype=words.dtype).reshape(-1, 1)
bit_sel = ((words[:, np.newaxis, :] >> bit) & 1).astype(dtype[1:])
bit_sel <<= np.arange(ntrack, dtype=dtype[1:])
words = np.empty(bit_sel.shape[:2], dtype)
words = np.bitwise_or.reduce(bit_sel, axis=2, out=words)
return words.ravel()
示例6: __yield_buffer
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import uint32 [as 别名]
def __yield_buffer(self, path, feat_mapper, defaults, buffer_size=int(1e5)):
item_idx = 0
buffer = list()
with open(path) as f:
f.readline()
pbar = tqdm(f, mininterval=1, smoothing=0.1)
pbar.set_description('Create avazu dataset cache: setup lmdb')
for line in pbar:
values = line.rstrip('\n').split(',')
if len(values) != self.NUM_FEATS + 2:
continue
np_array = np.zeros(self.NUM_FEATS + 1, dtype=np.uint32)
np_array[0] = int(values[1])
for i in range(1, self.NUM_FEATS + 1):
np_array[i] = feat_mapper[i].get(values[i+1], defaults[i])
buffer.append((struct.pack('>I', item_idx), np_array.tobytes()))
item_idx += 1
if item_idx % buffer_size == 0:
yield buffer
buffer.clear()
yield buffer
示例7: __yield_buffer
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import uint32 [as 别名]
def __yield_buffer(self, path, feat_mapper, defaults, buffer_size=int(1e5)):
item_idx = 0
buffer = list()
with open(path) as f:
pbar = tqdm(f, mininterval=1, smoothing=0.1)
pbar.set_description('Create criteo dataset cache: setup lmdb')
for line in pbar:
values = line.rstrip('\n').split('\t')
if len(values) != self.NUM_FEATS + 1:
continue
np_array = np.zeros(self.NUM_FEATS + 1, dtype=np.uint32)
np_array[0] = int(values[0])
for i in range(1, self.NUM_INT_FEATS + 1):
np_array[i] = feat_mapper[i].get(convert_numeric_feature(values[i]), defaults[i])
for i in range(self.NUM_INT_FEATS + 1, self.NUM_FEATS + 1):
np_array[i] = feat_mapper[i].get(values[i], defaults[i])
buffer.append((struct.pack('>I', item_idx), np_array.tobytes()))
item_idx += 1
if item_idx % buffer_size == 0:
yield buffer
buffer.clear()
yield buffer
示例8: _predict_spatial
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import uint32 [as 别名]
def _predict_spatial(self, earray, stim):
"""Predicts the brightness at specific times ``t``"""
# This does the expansion of a compact stimulus and a list of
# electrodes to activation values at X,Y grid locations:
assert isinstance(earray, ElectrodeArray)
assert isinstance(stim, Stimulus)
return fast_axon_map(stim.data,
np.array([earray[e].x for e in stim.electrodes],
dtype=np.float32),
np.array([earray[e].y for e in stim.electrodes],
dtype=np.float32),
self.axon_contrib,
self.axon_idx_start.astype(np.uint32),
self.axon_idx_end.astype(np.uint32),
self.rho,
self.thresh_percept)
示例9: _predict_temporal
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import uint32 [as 别名]
def _predict_temporal(self, stim, t_percept):
"""Predict the temporal response"""
# Pass the stimulus as a 2D NumPy array to the fast Cython function:
stim_data = stim.data.reshape((-1, len(stim.time)))
# Calculate at which simulation time steps we need to output a percept.
# This is basically t_percept/self.dt, but we need to beware of
# floating point rounding errors! 29.999 will be rounded down to 29 by
# np.uint32, so we need to np.round it first:
idx_percept = np.uint32(np.round(t_percept / self.dt))
if np.unique(idx_percept).size < t_percept.size:
raise ValueError("All times 't_percept' must be distinct multiples "
"of `dt`=%.2e" % self.dt)
# Cython returns a 2D (space x time) NumPy array:
return temporal_fast(stim_data.astype(np.float32),
stim.time.astype(np.float32),
idx_percept,
self.dt, self.tau1, self.tau2, self.tau3,
self.eps, self.beta, self.thresh_percept)
示例10: _predict_temporal
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import uint32 [as 别名]
def _predict_temporal(self, stim, t_percept):
"""Predict the temporal response"""
# Pass the stimulus as a 2D NumPy array to the fast Cython function:
stim_data = stim.data.reshape((-1, len(stim.time)))
# Calculate at which simulation time steps we need to output a percept.
# This is basically t_percept/self.dt, but we need to beware of
# floating point rounding errors! 29.999 will be rounded down to 29 by
# np.uint32, so we need to np.round it first:
idx_percept = np.uint32(np.round(t_percept / self.dt))
if np.unique(idx_percept).size < t_percept.size:
raise ValueError("All times 't_percept' must be distinct multiples "
"of `dt`=%.2e" % self.dt)
# Cython returns a 2D (space x time) NumPy array:
return temporal_fast(stim_data.astype(np.float32),
stim.time.astype(np.float32),
idx_percept,
self.dt, self.tau1, self.tau2, self.tau3,
self.asymptote, self.shift, self.slope, self.eps,
self.thresh_percept)
示例11: squeeze_bits
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import uint32 [as 别名]
def squeeze_bits(arr: numpy.ndarray) -> numpy.ndarray:
"""Return a copy of an integer numpy array with the minimum bitness."""
assert arr.dtype.kind in ("i", "u")
if arr.size == 0:
return arr
if arr.dtype.kind == "i":
assert arr.min() >= 0
mlbl = int(arr.max()).bit_length()
if mlbl <= 8:
dtype = numpy.uint8
elif mlbl <= 16:
dtype = numpy.uint16
elif mlbl <= 32:
dtype = numpy.uint32
else:
dtype = numpy.uint64
return arr.astype(dtype)
示例12: test_padded_union
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import uint32 [as 别名]
def test_padded_union(self):
dt = np.dtype(dict(
names=['a', 'b'],
offsets=[0, 0],
formats=[np.uint16, np.uint32],
itemsize=5,
))
ct = np.ctypeslib.as_ctypes_type(dt)
assert_(issubclass(ct, ctypes.Union))
assert_equal(ctypes.sizeof(ct), dt.itemsize)
assert_equal(ct._fields_, [
('a', ctypes.c_uint16),
('b', ctypes.c_uint32),
('', ctypes.c_char * 5), # padding
])
示例13: test_basic
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import uint32 [as 别名]
def test_basic(self):
ba = [1, 2, 10, 11, 6, 5, 4]
ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
for ctype in [np.int16, np.uint16, np.int32, np.uint32,
np.float32, np.float64, np.complex64, np.complex128]:
a = np.array(ba, ctype)
a2 = np.array(ba2, ctype)
if ctype in ['1', 'b']:
assert_raises(ArithmeticError, np.prod, a)
assert_raises(ArithmeticError, np.prod, a2, 1)
else:
assert_equal(a.prod(axis=0), 26400)
assert_array_equal(a2.prod(axis=0),
np.array([50, 36, 84, 180], ctype))
assert_array_equal(a2.prod(axis=-1),
np.array([24, 1890, 600], ctype))
示例14: test_setdiff1d
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import uint32 [as 别名]
def test_setdiff1d(self):
a = np.array([6, 5, 4, 7, 1, 2, 7, 4])
b = np.array([2, 4, 3, 3, 2, 1, 5])
ec = np.array([6, 7])
c = setdiff1d(a, b)
assert_array_equal(c, ec)
a = np.arange(21)
b = np.arange(19)
ec = np.array([19, 20])
c = setdiff1d(a, b)
assert_array_equal(c, ec)
assert_array_equal([], setdiff1d([], []))
a = np.array((), np.uint32)
assert_equal(setdiff1d(a, []).dtype, np.uint32)
示例15: test_union_with_struct_packed
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import uint32 [as 别名]
def test_union_with_struct_packed(self):
class Struct(ctypes.Structure):
_pack_ = 1
_fields_ = [
('one', ctypes.c_uint8),
('two', ctypes.c_uint32)
]
class Union(ctypes.Union):
_fields_ = [
('a', ctypes.c_uint8),
('b', ctypes.c_uint16),
('c', ctypes.c_uint32),
('d', Struct),
]
expected = np.dtype(dict(
names=['a', 'b', 'c', 'd'],
formats=['u1', np.uint16, np.uint32, [('one', 'u1'), ('two', np.uint32)]],
offsets=[0, 0, 0, 0],
itemsize=ctypes.sizeof(Union)
))
self.check(Union, expected)