当前位置: 首页>>代码示例>>Python>>正文


Python random.seed方法代码示例

本文整理汇总了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() 
开发者ID:xuwd11,项目名称:cs294-112_hws,代码行数:20,代码来源:run_dqn_lander.py

示例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)) 
开发者ID:fabriziocosta,项目名称:EDeN,代码行数:21,代码来源:estimator_utils.py

示例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 
开发者ID:open-mmlab,项目名称:mmdetection,代码行数:19,代码来源:train.py

示例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]) 
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:21,代码来源:validate_submission.py

示例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) 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:26,代码来源:populationdistribution.py

示例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 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:26,代码来源:strainsimulationwrapper.py

示例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() 
开发者ID:StanfordVL,项目名称:robosuite,代码行数:18,代码来源:demo_sampler_wrapper.py

示例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) 
开发者ID:allenai,项目名称:tpu_pretrain,代码行数:24,代码来源:utils.py

示例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) 
开发者ID:xuwd11,项目名称:cs294-112_hws,代码行数:25,代码来源:run_dqn_atari.py

示例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) 
开发者ID:ManiacalLabs,项目名称:BiblioPixelAnimations,代码行数:14,代码来源:GameOfLife.py

示例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) 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:34,代码来源:run.py

示例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 
开发者ID:mme,项目名称:vergeml,代码行数:14,代码来源:random_robot.py

示例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])) 
开发者ID:mme,项目名称:vergeml,代码行数:41,代码来源:random_robot.py

示例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')) 
开发者ID:mme,项目名称:vergeml,代码行数:6,代码来源:libraries.py

示例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:] 
开发者ID:fabriziocosta,项目名称:EDeN,代码行数:11,代码来源:util.py


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