python random randint_Python random.randint方法代码示例[通俗易懂]

2022-07-25 13:40:57 浏览数 (1)

大家好,又见面了,我是你们的朋友全栈君。

本文整理汇总了Python中numpy.random.randint方法的典型用法代码示例。如果您正苦于以下问题:Python random.randint方法的具体用法?Python random.randint怎么用?Python random.randint使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块numpy.random的用法示例。

在下文中一共展示了random.randint方法的24个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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

开发者ID:open-mmlab,项目名称:mmdetection,代码行数:18,

示例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

开发者ID:open-mmlab,项目名称:mmdetection,代码行数:27,

示例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)

开发者ID:ericjang,项目名称:e2c,代码行数:22,

示例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,))

开发者ID:Frank-qlu,项目名称:recruit,代码行数:24,

示例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)

开发者ID:Frank-qlu,项目名称:recruit,代码行数:26,

示例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)

开发者ID:Frank-qlu,项目名称:recruit,代码行数:26,

示例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)

开发者ID:Frank-qlu,项目名称:recruit,代码行数:22,

示例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))

开发者ID:databricks,项目名称:spark-deep-learning,代码行数:18,

示例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

开发者ID:CMU-CREATE-Lab,项目名称:deep-smoke-machine,代码行数:24,

示例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

开发者ID:ryfeus,项目名称:lambda-packs,代码行数:27,

示例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 = ((-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

开发者ID:inconvergent,项目名称:sand-glyphs,代码行数:23,

示例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)

开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:4,

示例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)

开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:4,

示例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))

开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:4,

示例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)

开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:43,

示例16: test_sparse_nd_concat

# 需要导入模块: from numpy import random [as 别名]

# 或者: from numpy.random import randint [as 别名]

def test_sparse_nd_concat():

def check_concat(arrays):

ret = np.concatenate([arr.asnumpy() for arr in arrays], axis=0)

same(mx.nd.concat(*arrays, dim=0).asnumpy(), ret)

nds = []

zero_nds = []

ncols = rnd.randint(2, 10)

for i in range(3):

shape = (rnd.randint(2, 10), ncols)

A, _ = rand_sparse_ndarray(shape, ‘csr’)

nds.append(A)

zero_nds.append(mx.nd.zeros(shape).tostype(‘csr’))

check_concat(nds)

check_concat(zero_nds)

开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:16,

示例17: test_sparse_nd_binary_scalar_op

# 需要导入模块: from numpy import random [as 别名]

# 或者: from numpy.random import randint [as 别名]

def test_sparse_nd_binary_scalar_op():

N = 3

def check(fn, stype, out_stype=None):

for _ in range(N):

ndim = 2

shape = np.random.randint(1, 6, size=(ndim,))

npy = np.random.normal(0, 1, size=shape)

nd = mx.nd.array(npy).tostype(stype)

if out_stype is not None:

assert(nd.stype == out_stype)

assert_allclose(fn(npy), fn(nd).asnumpy(), rtol=1e-4, atol=1e-4)

stypes = [‘row_sparse’, ‘csr’]

for stype in stypes:

check(lambda x: 1 x, stype)

check(lambda x: 1 – x, stype)

check(lambda x: 1 * x, stype)

check(lambda x: 1 / x, stype)

check(lambda x: 2 ** x, stype)

check(lambda x: 1 > x, stype)

check(lambda x: 0.5 > x, stype)

check(lambda x: 0.5 < x, stype)

check(lambda x: 0.5 >= x, stype)

check(lambda x: 0.5 <= x, stype)

check(lambda x: 0.5 == x, stype)

check(lambda x: x / 2, stype, out_stype=stype)

check(lambda x: x 0, stype, out_stype=stype)

check(lambda x: x – 0, stype, out_stype=stype)

开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:30,

示例18: test_sparse_nd_binary_iop

# 需要导入模块: from numpy import random [as 别名]

# 或者: from numpy.random import randint [as 别名]

def test_sparse_nd_binary_iop():

N = 3

def check_binary(fn, stype):

for _ in range(N):

ndim = 2

oshape = np.random.randint(1, 6, size=(ndim,))

lshape = list(oshape)

rshape = list(oshape)

lhs = np.random.uniform(0, 1, size=lshape)

rhs = np.random.uniform(0, 1, size=rshape)

lhs_nd = mx.nd.array(lhs).tostype(stype)

rhs_nd = mx.nd.array(rhs).tostype(stype)

assert_allclose(fn(lhs, rhs),

fn(lhs_nd, rhs_nd).asnumpy(),

rtol=1e-4, atol=1e-4)

def inplace_add(x, y):

x = y

return x

def inplace_mul(x, y):

x *= y

return x

stypes = [‘csr’, ‘row_sparse’]

fns = [inplace_add, inplace_mul]

for stype in stypes:

for fn in fns:

check_binary(fn, stype)

开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:29,

示例19: test_sparse_nd_save_load

# 需要导入模块: from numpy import random [as 别名]

# 或者: from numpy.random import randint [as 别名]

def test_sparse_nd_save_load():

repeat = 1

stypes = [‘default’, ‘row_sparse’, ‘csr’]

stype_dict = {‘default’: NDArray, ‘row_sparse’: RowSparseNDArray, ‘csr’: CSRNDArray}

num_data = 20

densities = [0, 0.5]

fname = ‘tmp_list.bin’

for _ in range(repeat):

data_list1 = []

for i in range(num_data):

stype = stypes[np.random.randint(0, len(stypes))]

shape = rand_shape_2d(dim0=40, dim1=40)

density = densities[np.random.randint(0, len(densities))]

data_list1.append(rand_ndarray(shape, stype, density))

assert isinstance(data_list1[-1], stype_dict[stype])

mx.nd.save(fname, data_list1)

data_list2 = mx.nd.load(fname)

assert len(data_list1) == len(data_list2)

for x, y in zip(data_list1, data_list2):

assert same(x.asnumpy(), y.asnumpy())

data_map1 = {‘ndarray xx %s’ % i: x for i, x in enumerate(data_list1)}

mx.nd.save(fname, data_map1)

data_map2 = mx.nd.load(fname)

assert len(data_map1) == len(data_map2)

for k, x in data_map1.items():

y = data_map2[k]

assert same(x.asnumpy(), y.asnumpy())

os.remove(fname)

开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:32,

示例20: get_minibatch

# 需要导入模块: from numpy import random [as 别名]

# 或者: from numpy.random import randint [as 别名]

def get_minibatch(roidb, num_classes):

“””Given a roidb, construct a minibatch sampled from it.”””

num_images = len(roidb)

# Sample random scales to use for each image in this batch

random_scale_inds = npr.randint(0, high=len(cfg.TRAIN.SCALES),

size=num_images)

assert(cfg.TRAIN.BATCH_SIZE % num_images == 0),

‘num_images ({}) must divide BATCH_SIZE ({})’.

format(num_images, cfg.TRAIN.BATCH_SIZE)

# Get the input image blob, formatted for caffe

im_blob, im_scales = _get_image_blob(roidb, random_scale_inds)

blobs = {‘data’: im_blob}

assert len(im_scales) == 1, “Single batch only”

assert len(roidb) == 1, “Single batch only”

# gt boxes: (x1, y1, x2, y2, cls)

if cfg.TRAIN.USE_ALL_GT:

# Include all ground truth boxes

gt_inds = np.where(roidb[0][‘gt_classes’] != 0)[0]

else:

# For the COCO ground truth boxes, exclude the ones that are ”iscrowd”

gt_inds = np.where(roidb[0][‘gt_classes’] != 0 & np.all(roidb[0][‘gt_overlaps’].toarray() > -1.0, axis=1))[0]

gt_boxes = np.empty((len(gt_inds), 5), dtype=np.float32)

gt_boxes[:, 0:4] = roidb[0][‘boxes’][gt_inds, :] * im_scales[0]

gt_boxes[:, 4] = roidb[0][‘gt_classes’][gt_inds]

blobs[‘gt_boxes’] = gt_boxes

blobs[‘im_info’] = np.array(

[[im_blob.shape[1], im_blob.shape[2], im_scales[0]]],

dtype=np.float32)

blobs[‘img_id’] = roidb[0][‘img_id’]

return blobs

开发者ID:guoruoqian,项目名称:cascade-rcnn_Pytorch,代码行数:38,

示例21: _sample_indices

# 需要导入模块: from numpy import random [as 别名]

# 或者: from numpy.random import randint [as 别名]

def _sample_indices(self, record):

“””

:param record: VideoRecord

:return: list

“””

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

开发者ID:yjxiong,项目名称:tsn-pytorch,代码行数:17,

示例22: __call__

# 需要导入模块: from numpy import random [as 别名]

# 或者: from numpy.random import randint [as 别名]

def __call__(self, image, boxes=None, labels=None):

if random.randint(2):

image[:, :, 1] *= random.uniform(self.lower, self.upper)

return image, boxes, labels

开发者ID:soo89,项目名称:CSD-SSD,代码行数:7,

示例23: compute_traj

# 需要导入模块: from numpy import random [as 别名]

# 或者: from numpy.random import randint [as 别名]

def compute_traj(self, max_dist=1):

# computes P,U data for single trajectory

# all P,U share the same environment obstacles.png

P=np.zeros((T,2),dtype=np.int) # r,c position

U=np.zeros((T,u_dim),dtype=np.int)

P[0,:]=[rw,randint(rw,w-rw)] # initial location

for t in range(1,T):

p=np.copy(P[t-1,:])

# dr direction

d=randint(-1,2) # direction

nsteps=randint(max_dist 1)

dr=d*nsteps # applied control

for i in range(nsteps):

p[0] =d

if self.is_colliding(p):

p[0]-=d

break

# dc direction

d=randint(-1,2) # direction

nsteps=randint(max_dist 1)

dc=d*nsteps # applied control

for i in range(nsteps):

p[1] =d

if self.is_colliding(p):

p[1]-=d # step back

break

P[t,:]=p

U[t,:]=[dr,dc]

return P,U

开发者ID:ericjang,项目名称:e2c,代码行数:31,

示例24: __call__

# 需要导入模块: from numpy import random [as 别名]

# 或者: from numpy.random import randint [as 别名]

def __call__(self, img, boxes, labels):

if random.randint(2):

return img, boxes, labels

h, w, c = img.shape

ratio = random.uniform(self.min_ratio, self.max_ratio)

expand_img = np.full((int(h * ratio), int(w * ratio), c),

self.mean).astype(img.dtype)

left = int(random.uniform(0, w * ratio – w))

top = int(random.uniform(0, h * ratio – h))

expand_img[top:top h, left:left w] = img

img = expand_img

boxes = np.tile((left, top), 2)

return img, boxes, labels

开发者ID:dingjiansw101,项目名称:AerialDetection,代码行数:16,

注:本文中的numpy.random.randint方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/127638.html原文链接:https://javaforall.cn

0 人点赞