本文整理汇总了Python中numpy.random.randint方法的典型用法代码示例。如果您正苦于以下问题:Python random.randint方法的具体用法?Python random.randint怎么用?Python random.randint使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy.random
的用法示例。
在下文中一共展示了random.randint方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: random_select
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import randint [as 别名]
def random_select(img_scales):
"""Randomly select an img_scale from given candidates.
Args:
img_scales (list[tuple]): Images scales for selection.
Returns:
(tuple, int): Returns a tuple ``(img_scale, scale_dix)``,
where ``img_scale`` is the selected image scale and
``scale_idx`` is the selected index in the given candidates.
"""
assert mmcv.is_list_of(img_scales, tuple)
scale_idx = np.random.randint(len(img_scales))
img_scale = img_scales[scale_idx]
return img_scale, scale_idx
示例2: random_sample
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import randint [as 别名]
def random_sample(img_scales):
"""Randomly sample an img_scale when ``multiscale_mode=='range'``.
Args:
img_scales (list[tuple]): Images scale range for sampling.
There must be two tuples in img_scales, which specify the lower
and uper bound of image scales.
Returns:
(tuple, None): Returns a tuple ``(img_scale, None)``, where
``img_scale`` is sampled scale and None is just a placeholder
to be consistent with :func:`random_select`.
"""
assert mmcv.is_list_of(img_scales, tuple) and len(img_scales) == 2
img_scale_long = [max(s) for s in img_scales]
img_scale_short = [min(s) for s in img_scales]
long_edge = np.random.randint(
min(img_scale_long),
max(img_scale_long) + 1)
short_edge = np.random.randint(
min(img_scale_short),
max(img_scale_short) + 1)
img_scale = (long_edge, short_edge)
return img_scale, None
示例3: sample
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import randint [as 别名]
def sample(self, batch_size):
"""
computes (x_t,u_t,x_{t+1}) pair
returns tuple of 3 ndarrays with shape
(batch,x_dim), (batch, u_dim), (batch, x_dim)
"""
if not self.initialized:
raise ValueError("Dataset not loaded - call PlaneData.initialize() first.")
traj=randint(0,num_t,size=batch_size) # which trajectory
tt=randint(0,T-1,size=batch_size) # time step t for each batch
X0=np.zeros((batch_size,x_dim))
U0=np.zeros((batch_size,u_dim),dtype=np.int)
X1=np.zeros((batch_size,x_dim))
for i in range(batch_size):
t=tt[i]
p=self.P[traj[i], t, :]
X0[i,:]=self.getX(traj[i],t)
X1[i,:]=self.getX(traj[i],t+1)
U0[i,:]=self.U[traj[i], t, :]
return (X0,U0,X1)
示例4: test_count_nonzero_axis_consistent
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import randint [as 别名]
def test_count_nonzero_axis_consistent(self):
# Check that the axis behaviour for valid axes in
# non-special cases is consistent (and therefore
# correct) by checking it against an integer array
# that is then casted to the generic object dtype
from itertools import combinations, permutations
axis = (0, 1, 2, 3)
size = (5, 5, 5, 5)
msg = "Mismatch for axis: %s"
rng = np.random.RandomState(1234)
m = rng.randint(-100, 100, size=size)
n = m.astype(object)
for length in range(len(axis)):
for combo in combinations(axis, length):
for perm in permutations(combo):
assert_equal(
np.count_nonzero(m, axis=perm),
np.count_nonzero(n, axis=perm),
err_msg=msg % (perm,))
示例5: test_frame_negate
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import randint [as 别名]
def test_frame_negate(self):
expr = self.ex('-')
# float
lhs = DataFrame(randn(5, 2))
expect = -lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_frame_equal(expect, result)
# int
lhs = DataFrame(randint(5, size=(5, 2)))
expect = -lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_frame_equal(expect, result)
# bool doesn't work with numexpr but works elsewhere
lhs = DataFrame(rand(5, 2) > 0.5)
if self.engine == 'numexpr':
with pytest.raises(NotImplementedError):
result = pd.eval(expr, engine=self.engine, parser=self.parser)
else:
expect = -lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_frame_equal(expect, result)
示例6: test_series_negate
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import randint [as 别名]
def test_series_negate(self):
expr = self.ex('-')
# float
lhs = Series(randn(5))
expect = -lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_series_equal(expect, result)
# int
lhs = Series(randint(5, size=5))
expect = -lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_series_equal(expect, result)
# bool doesn't work with numexpr but works elsewhere
lhs = Series(rand(5) > 0.5)
if self.engine == 'numexpr':
with pytest.raises(NotImplementedError):
result = pd.eval(expr, engine=self.engine, parser=self.parser)
else:
expect = -lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_series_equal(expect, result)
示例7: test_series_pos
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import randint [as 别名]
def test_series_pos(self):
expr = self.ex('+')
# float
lhs = Series(randn(5))
expect = lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_series_equal(expect, result)
# int
lhs = Series(randint(5, size=5))
expect = lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_series_equal(expect, result)
# bool doesn't work with numexpr but works elsewhere
lhs = Series(rand(5) > 0.5)
expect = lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_series_equal(expect, result)
示例8: test_identity_module
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import randint [as 别名]
def test_identity_module(self):
""" identity module should preserve input """
with IsolatedSession() as issn:
pred_input = tf.placeholder(tf.float32, [None, None])
final_output = tf.identity(pred_input, name='output')
gfn = issn.asGraphFunction([pred_input], [final_output])
for _ in range(10):
m, n = prng.randint(10, 1000, size=2)
mat = prng.randn(m, n).astype(np.float32)
with IsolatedSession() as issn:
feeds, fetches = issn.importGraphFunction(gfn)
mat_out = issn.run(fetches[0], {feeds[0]: mat})
self.assertTrue(np.all(mat_out == mat))
示例9: _sample_indices
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import randint [as 别名]
def _sample_indices(self, record):
"""
:param record: VideoRecord
:return: list
"""
if self.dense_sample: # i3d dense sample
sample_pos = max(1, 1 + record.num_frames - 64)
t_stride = 64 // self.num_segments
start_idx = 0 if sample_pos == 1 else np.random.randint(0, sample_pos - 1)
offsets = [(idx * t_stride + start_idx) % record.num_frames for idx in range(self.num_segments)]
return np.array(offsets) + 1
else: # normal sample
average_duration = (record.num_frames - self.new_length + 1) // self.num_segments
if average_duration > 0:
offsets = np.multiply(list(range(self.num_segments)), average_duration) + randint(average_duration,
size=self.num_segments)
elif record.num_frames > self.num_segments:
offsets = np.sort(randint(record.num_frames - self.new_length + 1, size=self.num_segments))
else:
offsets = np.zeros((self.num_segments,))
return offsets + 1
示例10: resample
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import randint [as 别名]
def resample(self, size=None):
"""
Randomly sample a dataset from the estimated pdf.
Parameters
----------
size : int, optional
The number of samples to draw. If not provided, then the size is
the same as the underlying dataset.
Returns
-------
resample : (self.d, `size`) ndarray
The sampled dataset.
"""
if size is None:
size = self.n
norm = transpose(multivariate_normal(zeros((self.d,), float),
self.covariance, size=size))
indices = randint(0, self.n, size=size)
means = self.dataset[:, indices]
return means + norm
示例11: _get_glyph
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import randint [as 别名]
def _get_glyph(gnum, height, width, shift_prob, shift_size):
if isinstance(gnum, list):
n = randint(*gnum)
else:
n = gnum
glyph = random_points_in_circle(
n, 0, 0, 0.5
)*array((width, height), 'float')
_spatial_sort(glyph)
if random()<shift_prob:
shift = ((-1)**randint(0,2))*shift_size*height
glyph[:,1] += shift
if random()<0.5:
ii = randint(0,n-1,size=(1))
xy = glyph[ii,:]
glyph = row_stack((glyph, xy))
return glyph
示例12: rand_shape_2d
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import randint [as 别名]
def rand_shape_2d(dim0=10, dim1=10):
return rnd.randint(1, dim0 + 1), rnd.randint(1, dim1 + 1)
示例13: rand_shape_3d
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import randint [as 别名]
def rand_shape_3d(dim0=10, dim1=10, dim2=10):
return rnd.randint(1, dim0 + 1), rnd.randint(1, dim1 + 1), rnd.randint(1, dim2 + 1)
示例14: rand_shape_nd
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import randint [as 别名]
def rand_shape_nd(num_dim, dim=10):
return tuple(rnd.randint(1, dim+1, size=num_dim))
示例15: test_sparse_nd_slice
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import randint [as 别名]
def test_sparse_nd_slice():
shape = (rnd.randint(2, 10), rnd.randint(2, 10))
stype = 'csr'
A, _ = rand_sparse_ndarray(shape, stype)
A2 = A.asnumpy()
start = rnd.randint(0, shape[0] - 1)
end = rnd.randint(start + 1, shape[0])
assert same(A[start:end].asnumpy(), A2[start:end])
assert same(A[start - shape[0]:end].asnumpy(), A2[start:end])
assert same(A[start:].asnumpy(), A2[start:])
assert same(A[:end].asnumpy(), A2[:end])
ind = rnd.randint(-shape[0], shape[0] - 1)
assert same(A[ind].asnumpy(), A2[ind][np.newaxis, :])
start_col = rnd.randint(0, shape[1] - 1)
end_col = rnd.randint(start_col + 1, shape[1])
result = mx.nd.slice(A, begin=(start, start_col), end=(end, end_col))
result_dense = mx.nd.slice(mx.nd.array(A2), begin=(start, start_col), end=(end, end_col))
assert same(result_dense.asnumpy(), result.asnumpy())
A = mx.nd.sparse.zeros('csr', shape)
A2 = A.asnumpy()
assert same(A[start:end].asnumpy(), A2[start:end])
result = mx.nd.slice(A, begin=(start, start_col), end=(end, end_col))
result_dense = mx.nd.slice(mx.nd.array(A2), begin=(start, start_col), end=(end, end_col))
assert same(result_dense.asnumpy(), result.asnumpy())
def check_slice_nd_csr_fallback(shape):
stype = 'csr'
A, _ = rand_sparse_ndarray(shape, stype)
A2 = A.asnumpy()
start = rnd.randint(0, shape[0] - 1)
end = rnd.randint(start + 1, shape[0])
# non-trivial step should fallback to dense slice op
result = mx.nd.sparse.slice(A, begin=(start,), end=(end + 1,), step=(2,))
result_dense = mx.nd.slice(mx.nd.array(A2), begin=(start,), end=(end + 1,), step=(2,))
assert same(result_dense.asnumpy(), result.asnumpy())
shape = (rnd.randint(2, 10), rnd.randint(1, 10))
check_slice_nd_csr_fallback(shape)