本文整理汇总了Python中random.Random.sample方法的典型用法代码示例。如果您正苦于以下问题:Python Random.sample方法的具体用法?Python Random.sample怎么用?Python Random.sample使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类random.Random
的用法示例。
在下文中一共展示了Random.sample方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: process2
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import sample [as 别名]
def process2( i ):
imgs = []
labels = []
rand = Random(i)
xs = res[i]
ns = nss[i]
# pick pairs
for idx in xrange(0, len(xs) - 1):
(l1, i1, v1) = xs[idx]
# pick sample translations
for idx2 in rand.sample(xrange(idx, len(xs) - 1), k=1):
(l2, i2, v2) = xs[idx2]
imgs.append( np.array([ i1, i2 ]) )
labels.append( 1 )
# pick translated neighbors as well
for n in rand.sample(ns, k=1):
for idx2 in rand.sample(xrange(0, len(xs)), k=1):
(l3, i3, v3) = res[n][idx2]
imgs.append( np.array([ i1, i3 ]) )
myl = (idx == idx2) or args.pair_displaced
labels.append( int(myl) )
# pick disimilar pairs
js = rand.sample([ k for k in xrange(count) if k not in ns ], k=len(xs))
for j in js:
ys = res[j]
for idx in rand.sample(xrange(0, len(ys)), k=1):
(l1, i1, v1) = xs[idx]
(l4, i4, v4) = ys[idx]
imgs.append( np.array([ i1, i4 ]) )
labels.append( 0 )
return (i, imgs, labels)
示例2: gen_passwd
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import sample [as 别名]
def gen_passwd(pwd_len=min_allowed_pwd_len, strict_policy=0, seed=None):
"""
Generates Paswords of pwd_len, that optinally strictly follows
the Password Policy.
if pwd_len < min_possible_len then policy cannot be enforced - if this happens,
and strict_policy=1 it returns None.
If pwd_len = min_possible_pwd_len then generate 4 unique tokens from vc, 1 token from
vn and 1 token from vsc.
if pwd_len > min_possible_pwd_len, then do as in previous step and then randomize the rest of the tokens.
"""
# Basic and obvious input checking
if strict_policy:
if pwd_len < min_allowed_pwd_len:
return None
# Since we are generating passwords, we are nice to the poor
# sods having to read and type them in, so we remove some
# typcial character ambiguities. Yes, I know, this reduces the
# Password Variation Space. See if I care - you're not the one
# having to read the passwords or deal with complaints about that :-)
# So, we reduce special chars
rvs = vsc.replace(' ', '') # remove space
rvs = rvs.replace('|', '') # remove pipe
# reduce valid numbers
rvn = vn.replace('1', '') # remove nr 1
rvn = rvn.replace('0', '') # remove zero
# reduce valid chars
rvc = vc.replace('l', '') # remove lowercase L
rvc = rvc.replace('I', '') # remove uppercase I
rvc = rvc.replace('O', '') # remove uppercase O
from random import Random
if seed is None:
seed = time() * time()
gen = Random(seed)
if not strict_policy:
pl = gen.sample(rvc + rvn + rvs, pwd_len)
return ''.join(pl)
# We have a strict enforcement policy. Try for ten iterations, if not
# successfull then return None.
rl_len = pwd_len - (min_char_tokens + min_num_tokens + min_special_tokens)
for i in range(1,10):
pl = gen.sample(rvc, min_char_tokens) + \
gen.sample(rvn, min_num_tokens) + \
gen.sample(rvs, min_special_tokens) + \
gen.sample(rvc + rvn + rvs, rl_len)
gen.shuffle(pl)
pwd = ''.join(pl)
err = check_passwd(pwd)
if err == []:
return pwd
return None
示例3: __create_random_data
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import sample [as 别名]
def __create_random_data(self, app, key):
'''
Creates a tuple with database, user, password
with randomized data
'''
randGen = Random()
database_name = "".join(randGen.sample(self.__random_characters,
self.__lenght_of_database_sufix))
user_name = "".join(randGen.sample(self.__random_characters,
self.__lenght_of_user_name))
password = "".join(randGen.sample(self.__random_characters,
self.__lenght_of_password))
return database_name, user_name, password
示例4: __create_random_data
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import sample [as 别名]
def __create_random_data(self):
'''
Creates a tuple with database, user, password
with randomized data
'''
rand_gen = Random()
database_name = "".join(rand_gen.sample(string.ascii_lowercase, 1) +
rand_gen.sample(self.__random_lowercase,
self.__lenght_of_database_sufix - 1))
user_name = "".join(rand_gen.sample(string.ascii_lowercase, 1) +
rand_gen.sample(self.__random_lowercase,
self.__lenght_of_user_name - 1))
password = "".join(rand_gen.sample(self.__random_characters,
self.__lenght_of_password)).lower()
return database_name, user_name, password
示例5: sparse_random_system
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import sample [as 别名]
def sparse_random_system(ring, number_of_polynomials, variables_per_polynomial, degree, random_seed=None):
"""
generates a system, which is sparse in the sense, that each polynomial
contains only a small subset of variables. In each variable that occurrs in a polynomial it is dense in the terms up to the given degree (every term occurs with probability 1/2).
The system will be satisfiable by at least one solution.
>>> from polybori import *
>>> r=Ring(10)
>>> s=sparse_random_system(r, number_of_polynomials = 20, variables_per_polynomial = 3, degree=2, random_seed=123)
>>> [p.deg() for p in s]
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
>>> sorted(groebner_basis(s), reverse=True)
[x(0), x(1), x(2), x(3), x(4) + 1, x(5), x(6) + 1, x(7), x(8) + 1, x(9)]
"""
if random_seed is not None:
set_random_seed(random_seed)
random_generator = Random(random_seed)
solutions=[]
variables = [ring.variable(i) for i in xrange(ring.n_variables())]
for v in variables:
solutions.append(v+random_generator.randint(0,1))
solutions=ll_encode(solutions)
res = []
while len(res)<number_of_polynomials:
variables_as_monomial=Monomial(
random_generator.sample(
variables,
variables_per_polynomial)
)
p=Polynomial(random_set(variables_as_monomial, 2**(variables_per_polynomial-1)))
p=sum([p.graded_part(i) for i in xrange(degree+1)])
if p.deg()==degree:
res.append(p)
res=[p+ll_red_nf_redsb(p, solutions) for p in res]# evaluate it to guarantee a solution
return res
示例6: _graph_example
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import sample [as 别名]
def _graph_example(n=4):
from string import ascii_uppercase as labels
from random import Random
n = min(n, 26)
class Node(object):
def __init__(self, letter):
self.letter = str(letter)
self.neigh = list()
def __str__(self):
return self.letter
__repr__ = __str__
# create a reproductible random graph
nodes = [Node(x) for x in labels[:n]]
ran = Random()
ran.seed(6164554331563)
neighmax = 3
for n in nodes:
n.neigh[:] = sorted((x for x in ran.sample(nodes, neighmax)
if x is not n), key=lambda n: n.letter)
#for n in nodes:
# print(n, ":", list(n.neigh))
for path in walk(nodes[0], (lambda n: n.neigh), event(~0), tree=False):
print(list(path), "{0:<7}".format(event_repr(path.event)))
示例7: fill_just_one
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import sample [as 别名]
def fill_just_one(board, uncertainty=1):
full = set(range(1, 10))
random = Random()
boards = []
for r, row in enumerate(board):
for c, value in enumerate(row):
if value == 0:
in_row = set(v for v in row)
in_col = set(board[i, c] for i in range(board.shape()[0]))
square = board.get_square(r // 3, c // 3)
in_square = set(square[ind] for ind, n in np.ndenumerate(square))
missing = full - (in_row | in_col | in_square)
if 0 < len(missing) <= uncertainty:
take = len(missing)
for field_value in random.sample(list(missing), take):
new_board = board.copy()
new_board[r, c] = field_value
boards.append(new_board)
return boards
return []
示例8: sub_ensemble
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import sample [as 别名]
def sub_ensemble(ensemble, n_estimators, seed=None):
"""Build a new ensemble with a random subset of the sub-estimators
>>> from sklearn.datasets import load_iris
>>> from sklearn.ensemble import ExtraTreesClassifier
>>> iris = load_iris()
>>> X, y = iris.data, iris.target
>>> big = ExtraTreesClassifier(n_estimators=10).fit(X, y)
>>> small = sub_ensemble(big, 3)
>>> len(small.estimators_)
3
>>> small.n_estimators
3
>>> small.score(X, y)
1.0
"""
rng = Random(seed)
final_ensemble = copy(ensemble)
if n_estimators > len(ensemble.estimators_):
raise ValueError(
"Cannot sample %d estimators from ensemble of %d"
% (n_estimators, len(ensemble.estimators_)))
final_ensemble.estimators_ = rng.sample(
ensemble.estimators_, n_estimators)
# Required in old versions of sklearn
final_ensemble.n_estimators = len(final_ensemble.estimators_)
return final_ensemble
示例9: choose_flag
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import sample [as 别名]
def choose_flag(c_sl, ratio):
"""
随机抽取每个簇的30%的样本作为标注数据
Args
-----------------------------------
c_sl:dict
key: cluster id, value: sample list
Returns
被选定为标注数据的sample list
"""
chosen = []
total = sum(len(v) for v in c_sl.values())
print "Total:",total
a_total = ratio * total #选总数的30%
print "Flag:",a_total
for c, sl in c_sl.items():
a_num = a_total * (len(sl)*1.0/total) #根据此簇所占总样本数的比例,计算此簇应该标记的样本数量
a_num = int(a_num)
if a_num == 0:
a_num = 1 #每个簇至少标记一个样本
print "Flag",str(a_num),"in cluster",str(c)
r = Random()
chosen += r.sample(sl, a_num)
return chosen
示例10: pairing_2Dd
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import sample [as 别名]
def pairing_2Dd( i ): # for 2D contrastive loss
imgs = []
labels = []
rand = Random(i)
xs = res[i]
ns = nss[i]
(l, _, _) = xs[0] # label
yss = rand.sample(filter(lambda ys: ys[0][0] != l, res.itervalues()),
k=neighs) # dissimilar labels
for idx in xrange(0, len(xs) - 1):
(l1, i1, v1) = xs[idx]
# pick similar pairs
idx2s = filter(lambda idx2: idx2 != idx, xrange(0, len(xs) - 1))
for idx2 in idx2s:
(l2, i2, v2) = xs[idx2]
assert v1 != v2
imgs.append( np.array([ i1, i2 ]) )
labels.append( combine_label(1, 0) )
# no neighbor pairing here
# pick disimilar pairs
for ys in yss:
(l5, i5, v5) = ys[idx]
imgs.append( np.array([ i1, i5 ]) )
labels.append( combine_label(0, 1) )
idx2s = set(xrange(0, len(ys) - 1))
idx2s.remove(idx)
idx2 = rand.choice(list(idx2s))
(l4, i4, v4) = ys[idx2]
imgs.append( np.array([ i1, i4 ]) )
labels.append( combine_label(0, 0) )
return (i, imgs, labels)
示例11: pairing_1
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import sample [as 别名]
def pairing_1( i ):
imgs = []
labels = []
rand = Random(i)
xs, ys, zs = map(res.get, rand.sample(res, k=3))
idx = rand.randint(0, len(xs) - 2)
# pick a similar pair
if rand.randint(0, 1):
# either we take the same sample with two cont transfo
idxs = [idx, idx+1] # choose two transfo index
(l1, i1, v1), (l2, i2, v2) = xs[idx:idx+2]
imgs.append( np.array([ i1, i2 ]) )
labels.append( 1 )
else:
# either we take two different samples but with same transfo
# FIXME: we don't care about labels!
idxs = [idx] # choose this single transfo index
(l1, i1, v1), (l2, i2, v2) = xs[idx], zs[idx]
imgs.append( np.array([ i1, i2 ]) )
labels.append( 1 )
# pick a disimilar pair
(l3, i3, v3) = rand.choice([ y # pick a disimilar transfo
for j, y in enumerate(ys) if j not in idxs ])
imgs.append( np.array([ i1, i3 ]) )
labels.append( 0 )
return (i, imgs, labels)
示例12: pairing_2a
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import sample [as 别名]
def pairing_2a( i ):
imgs = []
labels = []
rand = Random(i)
xs = res[i]
ns = nss[i]
# pick similar pairs
for idx in xrange(0, len(xs) - 2):
# pick the sample translations
(l1, i1, v1), (l2, i2, v2) = xs[idx:idx+2]
imgs.append( np.array([ i1, i2 ]) )
labels.append( 1 )
# pick translated neighbors as well
for n in ns:
ys = res[n]
for idx2 in xrange(0, len(ys)):
(l3, i3, v3) = ys[idx2]
imgs.append( np.array([ i1, i3 ]) )
myl = (idx == idx2) or args.pair_displaced
labels.append( myl )
# pick disimilar pairs
js = rand.sample([ k for k in xrange(count) if k not in ns ], k=neighs)
for j in js:
ys = res[j]
for idx in xrange(0, len(ys) - 1):
(l1, i1, v1) = xs[idx]
(l4, i4, v4) = ys[idx]
imgs.append( np.array([ i1, i4 ]) )
labels.append( 0 )
return (i, imgs, labels)
示例13: worker
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import sample [as 别名]
def worker():
QueueManager.register(COMMAND_QUEUE)
m = QueueManager(address=('', CONTROL_PORT), authkey=CONTROL_KEY)
m.connect()
command_queue = getattr(m, COMMAND_QUEUE)()
r = Random()
r.seed(time.time())
while True:
command = command_queue.get()
mc = GetMemcacheClient(command['servers'])
location_keys = command['location_keys']
num_locations_per_mcas = command['num_locations_per_mcas']
batch_size = command['batch_size']
print('worker received command')
batch_time = time.time()
num_retries = 0
for i in range(batch_size):
op_time = time.time()
mcas_keys = r.sample(location_keys, num_locations_per_mcas)
while True:
if mcas(mc, ((item, item.value + 1)
for item in (mcas_get(mc, key) for key in mcas_keys))):
break
else:
num_retries += 1
if TARGET_RATE:
time.sleep(max(0, 1 / TARGET_RATE - (time.time() - op_time)))
print('done: %.1f operations per second, %s retries' % (
batch_size/(time.time() - batch_time), num_retries))
command_queue.task_done()
示例14: pairing_2b
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import sample [as 别名]
def pairing_2b( i ):
imgs = []
labels = []
rand = Random(i)
xs = res[i]
ns = nss[i]
(l0, i0, v0) = xs[idx_orig]
# pick pairs
for idx in xrange(0, len(xs)):
(l1, i1, v1) = xs[idx]
# pair original with its 4 translations
if idx != idx_orig:
imgs.append( np.array([ i0, i1 ]) )
labels.append( 1 )
# pair all 4 translations of 5 neighbors
for n in ns:
for idx2 in xrange(0, len(xs)):
(l2, i2, v2) = res[n][idx2]
imgs.append( np.array([ i1, i2 ]) )
myl = (idx == idx2) or args.pair_displaced
labels.append( int(myl) )
# pick lots of disimilar pairs
js = rand.sample([ k for k in xrange(count) if k not in ns ], k=100)
for j in js:
ys = res[j]
idx = rand.randint(0, len(xs) - 1)
idx2 = rand.randint(0, len(ys) - 1)
(l1, i1, v1) = xs[idx]
(l3, i3, v3) = ys[idx2]
imgs.append( np.array([ i1, i3 ]) )
labels.append( 0 )
return (i, imgs, labels)
示例15: pairing_2Da
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import sample [as 别名]
def pairing_2Da( i ): # for 2D contrastive loss
imgs = []
labels = []
rand = Random(i)
xs = res[i]
ns = nss[i]
# pick similar pairs
for idx in xrange(0, len(xs) - 1):
# pick the sample translations
(l1, i1, v1), (l2, i2, v2) = xs[idx:idx+2]
imgs.append( np.array([ i1, i2 ]) )
labels.append( combine_label(1, 0) )
# pick translated neighbors as well
for n in ns:
ys = res[n]
for idx2 in xrange(0, len(ys)):
(l3, i3, v3) = ys[idx2]
imgs.append( np.array([ i1, i3 ]) )
labels.append( combine_label(1, int(idx == idx2)) )
# pick disimilar pairs
js = rand.sample([ k for k in xrange(count) if k not in ns ], k=neighs)
for j in js:
ys = res[j]
for idx in xrange(0, len(ys)):
(l1, i1, v1) = xs[idx]
(l4, i4, v4) = ys[idx]
imgs.append( np.array([ i1, i4 ]) )
labels.append( combine_label(int(l1 == l4), 1) )
return (i, imgs, labels)