當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。