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


Python random.setstate方法代码示例

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


在下文中一共展示了random.setstate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: verify_tee

# 需要导入模块: import random [as 别名]
# 或者: from random import setstate [as 别名]
def verify_tee(n, original, seed):
    try:
        state = random.getstate()
        iterators = list(tee(original, n=n))
        results = [[] for _ in range(n)]
        exhausted = [False] * n
        while not all(exhausted):
            # Upper argument of random.randint is inclusive. Argh.
            i = random.randint(0, n - 1)
            if not exhausted[i]:
                if len(results[i]) == len(original):
                    assert_raises(StopIteration, next, iterators[i])
                    assert results[i] == original
                    exhausted[i] = True
                else:
                    if random.randint(0, 1):
                        iterators[i] = cPickle.loads(
                            cPickle.dumps(iterators[i]))
                    elem = next(iterators[i])
                    results[i].append(elem)
    finally:
        random.setstate(state) 
开发者ID:mila-iqia,项目名称:picklable-itertools,代码行数:24,代码来源:__init__.py

示例2: penis

# 需要导入模块: import random [as 别名]
# 或者: from random import setstate [as 别名]
def penis(self, ctx, *users: discord.Member):
        """Detects user's penis length

        This is 100% accurate.
        Enter multiple users for an accurate comparison!"""
        if not users:
            await self.bot.send_cmd_help(ctx)
            return

        dongs = {}
        msg = ""
        state = random.getstate()

        for user in users:
            random.seed(user.id)
            dongs[user] = "8{}D".format("=" * random.randint(0, 30))

        random.setstate(state)
        dongs = sorted(dongs.items(), key=lambda x: x[1])

        for user, dong in dongs:
            msg += "**{}'s size:**\n{}\n".format(user.display_name, dong)

        for page in pagify(msg):
            await self.bot.say(page) 
开发者ID:Twentysix26,项目名称:26-Cogs,代码行数:27,代码来源:penis.py

示例3: load_states

# 需要导入模块: import random [as 别名]
# 或者: from random import setstate [as 别名]
def load_states(self, epoch, device):
        """Loads the states from the checkpoint associated with ``epoch``.

        Args:
            epoch (int): ``--epoch`` command argument.
            device (str): ``--device`` command argument.
        """
        checkpoint_data = self.experiment.checkpoint_load(epoch, device)
        if isinstance(self.model, torch.nn.DataParallel):
            self.model.module.load_state_dict(checkpoint_data['model'])
        else:
            self.model.load_state_dict(checkpoint_data['model'])
        self.optimizer.load_state_dict(checkpoint_data['optimizer'])
        random.setstate(checkpoint_data['random_states'][0])
        np.random.set_state(checkpoint_data['random_states'][1])
        torch.set_rng_state(checkpoint_data['random_states'][2].cpu())
        if torch.cuda.is_available() and checkpoint_data['random_states'][3] is not None:
            torch.cuda.set_rng_state(checkpoint_data['random_states'][3].cpu())
        self.counters = checkpoint_data['counters']
        if 'losses' in checkpoint_data:  # Compatibility purposes until next release
            self.losses_epoch = checkpoint_data['losses']
        else:
            self.losses_epoch = checkpoint_data['losses_epoch']
            self.losses_it = checkpoint_data['losses_it']
        self.load_states_others(checkpoint_data) 
开发者ID:davidalvarezdlt,项目名称:skeltorch,代码行数:27,代码来源:runner.py

示例4: test_scramble

# 需要导入模块: import random [as 别名]
# 或者: from random import setstate [as 别名]
def test_scramble():
    """Test scramble"""

    state = random.getstate()
    random.seed(1)
    assert scramble("a") == "a"
    assert scramble("ab") == "ab"
    assert scramble("abc") == "abc"
    assert scramble("abcd") == "acbd"
    assert scramble("abcde") == "acbde"
    assert scramble("abcdef") == "aecbdf"
    assert scramble("abcde'f") == "abcd'ef"
    random.setstate(state)


# -------------------------------------------------- 
开发者ID:kyclark,项目名称:tiny_python_projects,代码行数:18,代码来源:solution.py

示例5: random_seed

# 需要导入模块: import random [as 别名]
# 或者: from random import setstate [as 别名]
def random_seed(seed=None):
    """Execute code inside this with-block using the specified seed.

    If no seed is specified, nothing happens.

    Does not affect the state of the random number generator outside this block.
    Not thread-safe.

    Args:
        seed (int): random seed
    """
    if seed is None:
        yield
    else:
        py_state = random.getstate()  # save state
        np_state = np.random.get_state()

        random.seed(seed)  # alter state
        np.random.seed(seed)
        yield

        random.setstate(py_state)  # restore state
        np.random.set_state(np_state) 
开发者ID:kelvinguu,项目名称:lang2program,代码行数:25,代码来源:utils.py

示例6: choice

# 需要导入模块: import random [as 别名]
# 或者: from random import setstate [as 别名]
def choice(population, k=1, replace=True):
    ver = platform.sys.version_info
    if replace and (ver.major,ver.minor) in [(2,7),(3,5)]: # python 2.7 or 3.5
        # slow if population is large and not a np.ndarray
        return list(np.random.choice(population, k, replace=replace))
    else:
        try:
            # save state of 'random' and set seed using 'np.random'
            state = random.getstate()
            random.seed(np.random.randint(np.iinfo(int).min, np.iinfo(int).max))
            if replace:
                # sample with replacement
                return random.choices(population, k=k)
            else:
                # sample without replacement
                return random.sample(population, k=k)
        finally:
            # restore state of 'random'
            random.setstate(state) 
开发者ID:CSBDeep,项目名称:CSBDeep,代码行数:21,代码来源:utils.py

示例7: __init__

# 需要导入模块: import random [as 别名]
# 或者: from random import setstate [as 别名]
def __init__(
            self, max_rb_size_per_task, observation_dim, action_dim,
            discrete_action_dim=False, policy_uses_pixels=False,
            policy_uses_task_params=False, concat_task_params_to_policy_obs=False,
            random_seed=2001
        ):
        prev_py_rand_state = python_random.getstate()
        python_random.seed(random_seed)
        self._py_rand_state = python_random.getstate()
        python_random.setstate(prev_py_rand_state)

        self._obs_dim = observation_dim
        self._act_dim = action_dim
        self._max_rb_size_per_task = max_rb_size_per_task
        self._disc_act_dim = discrete_action_dim
        self._policy_uses_pixels = policy_uses_pixels
        self._policy_uses_task_params = policy_uses_task_params
        self._concat_task_params_to_policy_obs = concat_task_params_to_policy_obs
        p = self._get_partial()
        self.task_replay_buffers = defaultdict(p) 
开发者ID:KamyarGh,项目名称:rl_swiss,代码行数:22,代码来源:_simple_replay_buffer_with_rand_state.py

示例8: base_test_get_batches

# 需要导入模块: import random [as 别名]
# 或者: from random import setstate [as 别名]
def base_test_get_batches(self, lp: LanguageProcessing):
		lp_cp = copy.deepcopy(lp)
		for set_name in lp.data.keys():
			#rng_state = random.getstate()
			lp_batches = iter(lp.get_batches(set_name, 3, False))
			#random.setstate(rng_state)
			lp_cp.restart(set_name, 3, False)
			while True:
				res_cp = lp_cp.get_next_batch(set_name)
				if res_cp is None:
					break
				res = next(lp_batches)
				assert sorted(res_cp.keys()) == sorted(res.keys())
				for key in res_cp.keys():
					if isinstance(res_cp[key], np.ndarray):
						assert (res_cp[key] == res[key]).all()
					else:
						assert res_cp[key] == res[key] 
开发者ID:thu-coai,项目名称:cotk,代码行数:20,代码来源:test_dataloader.py

示例9: test_download_parallel_partial_success_lock_safe

# 需要导入模块: import random [as 别名]
# 或者: from random import setstate [as 别名]
def test_download_parallel_partial_success_lock_safe(temp_cache, valid_urls, invalid_urls):
    """Check that a partially successful parallel download leaves the cache unlocked.

    This needs to be repeated many times because race conditions are what cause
    this sort of thing, especially situations where a process might be forcibly
    shut down while it holds the lock.

    """
    s = random.getstate()
    try:
        random.seed(0)
        for _ in range(N_PARALLEL_HAMMER):
            td = list(islice(valid_urls, FEW))

            u_bad = next(invalid_urls)
            urls = [u_bad] + [u for (u, c) in td]
            random.shuffle(urls)
            with pytest.raises(urllib.request.URLError):
                download_files_in_parallel(urls)
    finally:
        random.setstate(s) 
开发者ID:holzschu,项目名称:Carnets,代码行数:23,代码来源:test_data.py

示例10: batch_generator

# 需要导入模块: import random [as 别名]
# 或者: from random import setstate [as 别名]
def batch_generator(self, batch_size: int, data_type: str = 'train') -> Generator:
        r"""This function returns a generator, which serves for generation of raw (no preprocessing such as tokenization)
         batches
        Args:
            batch_size (int): number of samples in batch
            data_type (str): can be either 'train', 'test', or 'valid'
        Returns:
            batch_gen (Generator): a generator, that iterates through the part (defined by data_type) of the dataset
        """
        data = self.data[data_type]
        data_len = len(data)
        order = list(range(data_len))

        rs = random.getstate()
        random.setstate(self.random_state)
        random.shuffle(order)
        self.random_state = random.getstate()
        random.setstate(rs)

        for i in range((data_len - 1) // batch_size + 1):
            yield list(zip(*[data[o] for o in order[i * batch_size:(i + 1) * batch_size]])) 
开发者ID:deepmipt,项目名称:intent_classifier,代码行数:23,代码来源:dataset.py

示例11: optimize_pipeline

# 需要导入模块: import random [as 别名]
# 或者: from random import setstate [as 别名]
def optimize_pipeline(self, config, budget, config_id, random_state):
        
        random.setstate(random_state)

        if self.permutations is not None:
            current_sh_run = config_id[0]
            self.pipeline_config["dataset_order"] = self.permutations[current_sh_run%len(self.permutations)].tolist()

        try:
            self.autonet_logger.info("Fit optimization pipeline")
            return self.pipeline.fit_pipeline(hyperparameter_config=config, pipeline_config=self.pipeline_config, 
                                            X_train=self.X_train, Y_train=self.Y_train, X_valid=self.X_valid, Y_valid=self.Y_valid, 
                                            budget=budget, budget_type=self.budget_type, max_budget=self.max_budget, 
                                            config_id=config_id, working_directory=self.working_directory), random.getstate()
        except Exception as e:
            if 'use_tensorboard_logger' in self.pipeline_config and self.pipeline_config['use_tensorboard_logger']:            
                import tensorboard_logger as tl
                tl.log_value('Exceptions/' + str(e), budget, int(time.time()))
            #self.autonet_logger.exception('Exception occurred')
            raise e 
开发者ID:automl,项目名称:Auto-PyTorch,代码行数:22,代码来源:worker_no_timelimit.py

示例12: restore_checkpoint

# 需要导入模块: import random [as 别名]
# 或者: from random import setstate [as 别名]
def restore_checkpoint(filename):
        """Resumes the simulation from a previous saved point."""
        with gzip.open(filename) as f:
            generation, config, population, species_set, rndstate = pickle.load(f)
            random.setstate(rndstate)
            return Population(config, (population, species_set, generation)) 
开发者ID:CodeReclaimers,项目名称:neat-python,代码行数:8,代码来源:checkpoint.py

示例13: use_internal_state

# 需要导入模块: import random [as 别名]
# 或者: from random import setstate [as 别名]
def use_internal_state(self):
        """Use a specific RNG state."""
        old_state = random.getstate()
        random.setstate(self._random_state)
        yield
        self._random_state = random.getstate()
        random.setstate(old_state) 
开发者ID:salesforce,项目名称:decaNLP,代码行数:9,代码来源:iterator.py

示例14: tearDown

# 需要导入模块: import random [as 别名]
# 或者: from random import setstate [as 别名]
def tearDown(self):
        random.setstate(self.state) 
开发者ID:avalente,项目名称:appmetrics,代码行数:4,代码来源:test_histogram.py

示例15: load_tuning

# 需要导入模块: import random [as 别名]
# 或者: from random import setstate [as 别名]
def load_tuning():
    """ Load any previous tuning information """
    filename = tuning_filename()
    try:
        stream = open(filename, 'r')
    except IOError:
        logging.info('No previous tuning file found.')
        return {'trials': []}

    tuning = json.load(stream)
    random.setstate(pickle.loads(tuning['rng_state']))

    cleanup_trials(tuning['trials'])
    return tuning 
开发者ID:dojoteef,项目名称:glas,代码行数:16,代码来源:tune.py


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