本文整理匯總了Python中random.seed方法的典型用法代碼示例。如果您正苦於以下問題:Python random.seed方法的具體用法?Python random.seed怎麽用?Python random.seed使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類random
的用法示例。
在下文中一共展示了random.seed方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: lander_learn
# 需要導入模塊: import random [as 別名]
# 或者: from random import seed [as 別名]
def lander_learn(env,
session,
num_timesteps,
seed):
optimizer = lander_optimizer()
stopping_criterion = lander_stopping_criterion(num_timesteps)
exploration_schedule = lander_exploration_schedule(num_timesteps)
dqn.learn(
env=env,
session=session,
exploration=lander_exploration_schedule(num_timesteps),
stopping_criterion=lander_stopping_criterion(num_timesteps),
double_q=True,
**lander_kwargs()
)
env.close()
示例2: make_train_test_sets
# 需要導入模塊: import random [as 別名]
# 或者: from random import seed [as 別名]
def make_train_test_sets(pos_graphs, neg_graphs,
test_proportion=.3, random_state=2):
"""make_train_test_sets."""
random.seed(random_state)
random.shuffle(pos_graphs)
random.shuffle(neg_graphs)
pos_dim = len(pos_graphs)
neg_dim = len(neg_graphs)
tr_pos_graphs = pos_graphs[:-int(pos_dim * test_proportion)]
te_pos_graphs = pos_graphs[-int(pos_dim * test_proportion):]
tr_neg_graphs = neg_graphs[:-int(neg_dim * test_proportion)]
te_neg_graphs = neg_graphs[-int(neg_dim * test_proportion):]
tr_graphs = tr_pos_graphs + tr_neg_graphs
te_graphs = te_pos_graphs + te_neg_graphs
tr_targets = [1] * len(tr_pos_graphs) + [0] * len(tr_neg_graphs)
te_targets = [1] * len(te_pos_graphs) + [0] * len(te_neg_graphs)
tr_graphs, tr_targets = paired_shuffle(tr_graphs, tr_targets)
te_graphs, te_targets = paired_shuffle(te_graphs, te_targets)
return (tr_graphs, np.array(tr_targets)), (te_graphs, np.array(te_targets))
示例3: set_random_seed
# 需要導入模塊: import random [as 別名]
# 或者: from random import seed [as 別名]
def set_random_seed(seed, deterministic=False):
"""Set random seed.
Args:
seed (int): Seed to be used.
deterministic (bool): Whether to set the deterministic option for
CUDNN backend, i.e., set `torch.backends.cudnn.deterministic`
to True and `torch.backends.cudnn.benchmark` to False.
Default: False.
"""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
if deterministic:
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
示例4: main
# 需要導入模塊: import random [as 別名]
# 或者: from random import seed [as 別名]
def main(args):
print_in_box('Validating submission ' + args.submission_filename)
random.seed()
temp_dir = args.temp_dir
delete_temp_dir = False
if not temp_dir:
temp_dir = tempfile.mkdtemp()
logging.info('Created temporary directory: %s', temp_dir)
delete_temp_dir = True
validator = validate_submission_lib.SubmissionValidator(temp_dir,
args.use_gpu)
if validator.validate_submission(args.submission_filename,
args.submission_type):
print_in_box('Submission is VALID!')
else:
print_in_box('Submission is INVALID, see log messages for details')
if delete_temp_dir:
logging.info('Deleting temporary directory: %s', temp_dir)
subprocess.call(['rm', '-rf', temp_dir])
示例5: __init__
# 需要導入模塊: import random [as 別名]
# 或者: from random import seed [as 別名]
def __init__(self, logfile=None, verbose=True, debug=False, seed=None):
"""
Initialize instance with seed
@attention:
@param logfile: file handler or file path to a log file
@type logfile: basestring | file | io.FileIO | StringIO.StringIO
@param verbose: Not verbose means that only warnings and errors will be past to stream
@type verbose: bool
@param debug: If True logger will output DEBUG messages
@type debug: bool
@param seed: The seed used for initiation of the 'random' module
@type seed: long | int | float | str | unicode
@return: None
@rtype: None
"""
assert isinstance(verbose, bool)
assert isinstance(debug, bool)
super(PopulationDistribution, self).__init__(logfile, verbose, debug)
if seed is not None:
random.seed(seed)
示例6: _get_simulate_cmd
# 需要導入模塊: import random [as 別名]
# 或者: from random import seed [as 別名]
def _get_simulate_cmd(self, directory_strains, filepath_genome, filepath_gff):
"""
Get system command to start simulation. Change directory to the strain directory and start simulating strains.
@param directory_strains: Directory for the simulated strains
@type directory_strains: str | unicode
@param filepath_genome: Genome to get simulated strains of
@type filepath_genome: str | unicode
@param filepath_gff: gff file with gene annotations
@type filepath_gff: str | unicode
@return: System command line
@rtype: str
"""
cmd_run_simujobrun = "cd {dir}; {executable} {filepath_genome} {filepath_gff} {seed}" + " >> {log}"
cmd = cmd_run_simujobrun.format(
dir=directory_strains,
executable=self._executable_sim,
filepath_genome=filepath_genome,
filepath_gff=filepath_gff,
seed=self._get_seed(),
log=os.path.join(directory_strains, os.path.basename(filepath_genome) + ".sim.log")
)
return cmd
示例7: sample
# 需要導入模塊: import random [as 別名]
# 或者: from random import seed [as 別名]
def sample(self):
"""
This is the core sampling method. Samples a state from a
demonstration, in accordance with the configuration.
"""
# chooses a sampling scheme randomly based on the mixing ratios
seed = random.uniform(0, 1)
ratio = np.cumsum(self.scheme_ratios)
ratio = ratio > seed
for i, v in enumerate(ratio):
if v:
break
sample_method = getattr(self, self.sample_method_dict[self.sampling_schemes[i]])
return sample_method()
示例8: init
# 需要導入模塊: import random [as 別名]
# 或者: from random import seed [as 別名]
def init(args):
# init logger
log_format = '%(asctime)-10s: %(message)s'
if args.log_file is not None and args.log_file != "":
Path(args.log_file).parent.mkdir(parents=True, exist_ok=True)
logging.basicConfig(level=logging.INFO, filename=args.log_file, filemode='w', format=log_format)
logging.warning(f'This will get logged to file: {args.log_file}')
else:
logging.basicConfig(level=logging.INFO, format=log_format)
# create output dir
if args.output_dir.is_dir() and list(args.output_dir.iterdir()):
logging.warning(f"Output directory ({args.output_dir}) already exists and is not empty!")
assert 'bert' in args.output_dir.name, \
'''Output dir name has to contain `bert` or `roberta` for AutoModel.from_pretrained to correctly infer the model type'''
args.output_dir.mkdir(parents=True, exist_ok=True)
# set random seeds
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
示例9: main
# 需要導入模塊: import random [as 別名]
# 或者: from random import seed [as 別名]
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('exp_name', type=str)
parser.add_argument('--gamma', type=float, default=0.99)
parser.add_argument('--double_q', action='store_true')
parser.add_argument('--gpu', type=int, default=0)
args = parser.parse_args()
os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu)
if not(os.path.exists('data')):
os.makedirs('data')
# Get Atari games.
task = gym.make('PongNoFrameskip-v4')
# Run training
seed = random.randint(0, 9999)
print('random seed = %d' % seed)
env = get_env(task, seed)
session = get_session()
atari_learn(env, session, args, num_timesteps=5e7)
示例10: genNewTable
# 需要導入模塊: import random [as 別名]
# 或者: from random import seed [as 別名]
def genNewTable(self):
self.table = []
random.seed(time.time())
for y in range(0, self.height):
self.table.append([])
for x in range(0, self.width):
rand = random.randint(0, self._rand_max)
if rand == 0:
self.table[y].append(1)
else:
self.table[y].append(0)
示例11: get_sample
# 需要導入模塊: import random [as 別名]
# 或者: from random import seed [as 別名]
def get_sample(ggrp: GenomeGroup, ignore_coverage: bool) -> List[GenomeGroupTarget]:
"""Get the sample space for the mutation trials.
This will attempt to use covered-targets as the default unless ``ignore_coverage`` is set
to True. If the set .coverage file is not found then the total targets are returned instead.
Args:
ggrp: the Genome Group to generate the sample space of targets
ignore_coverage: flag to ignore coverage if present
Returns:
Sorted list of Path-LocIndex pairs as complete sample space from the ``GenomeGroup``.
"""
if ignore_coverage:
LOGGER.info("Ignoring coverage file for sample space creation.")
try:
sample = ggrp.targets if ignore_coverage else ggrp.covered_targets
except FileNotFoundError:
LOGGER.info("Coverage file does not exist, proceeding to sample from all targets.")
sample = ggrp.targets
# sorted list used for repeat trials using random seed instead of set
sort_by_keys = attrgetter(
"source_path",
"loc_idx.lineno",
"loc_idx.col_offset",
"loc_idx.end_lineno",
"loc_idx.end_col_offset",
)
return sorted(sample, key=sort_by_keys)
示例12: random_robot_name
# 需要導入模塊: import random [as 別名]
# 或者: from random import seed [as 別名]
def random_robot_name(moment_of_birth, dest=None):
"""Construct a random robot name.
"""
random.seed(moment_of_birth)
adj = random.choice(_ADJ)
noun = random.choice(_NOUN)
name = "{}-{}".format(adj, noun).lower()
if dest and os.path.exists(os.path.join(dest, name)):
return random_robot_name(datetime.now(), dest)
return name
示例13: ascii_robot
# 需要導入模塊: import random [as 別名]
# 或者: from random import seed [as 別名]
def ascii_robot(moment_of_birth, name, include_phrase=True):
"""Generate random robot ascii art.
"""
random.seed(moment_of_birth)
def paste(cur, *lines):
cur = list(cur)
for line in lines:
if len(line) > len(cur):
cur += [' '] * (len(line) - len(cur))
for i, char in enumerate(line):
if char != " ":
cur[i] = char
return "".join(cur)
if random.choice([2, 3]) == 2:
top = random.choice(ANTENNA)
head = paste(random.choice(EYES), random.choice(EARS))
body = paste("", random.choice(ARMS), random.choice(SIDES), random.choice(CENTER))
bottom = random.choice(FEET)
else:
top = random.choice(ANTENNA_3)
head = paste(random.choice(EYES_3), random.choice(EARS_3))
if random.choice(["thin", "thick"]) == "thick":
body = paste("", random.choice(ARMS_3_THICK),
random.choice(SIDES_3_THICK), random.choice(CENTER_3_THICK))
else:
body = paste("", random.choice(ARMS_3_THIN), random.choice(SIDES_3_THIN),
random.choice(CENTER_3_THIN))
bottom = random.choice(FEET3)
if include_phrase:
phrase = random_phrase(name)
bottom = paste(bottom, ' - {}'.format(phrase))
return "\n".join(map(lambda part: " " + part, [top, head, body, bottom]))
示例14: setup
# 需要導入模塊: import random [as 別名]
# 或者: from random import seed [as 別名]
def setup(env):
import tensorflow # pylint: disable=E0401
tensorflow.logging.set_verbosity(tensorflow.logging.ERROR)
tensorflow.set_random_seed(env.get('random-seed'))
示例15: random_bipartition
# 需要導入模塊: import random [as 別名]
# 或者: from random import seed [as 別名]
def random_bipartition(int_range, relative_size=.7, random_state=None):
"""random_bipartition."""
if not random_state:
random_state = random.random()
random.seed(random_state)
ids = list(range(int_range))
random.shuffle(ids)
split_point = int(int_range * relative_size)
return ids[:split_point], ids[split_point:]