numpy.random.get_state

Here are the examples of the python api numpy.random.get_state taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

287 Examples 7

3 Source : utils.py
with MIT License
from aaronkollasch

def temp_seed(seed):
    state = np.random.get_state()
    np.random.seed(seed)
    try:
        yield
    finally:
        np.random.set_state(state)


# https://github.com/ilkarman/DeepLearningFrameworks/blob/master/notebooks/common/utils.py
def get_gpu_name():

3 Source : model.py
with MIT License
from abrazinskas

def temp_seed(seed):
    state = np.random.get_state()
    np.random.seed(seed)
    try:
        yield
    finally:
        np.random.set_state(state)


def freeze_params(module):

3 Source : testing.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def __enter__(self):

        self.start_state = np.random.get_state()
        np.random.seed(self.seed)

    def __exit__(self, exc_type, exc_value, traceback):

3 Source : util.py
with MIT License
from afourast

def stash_seed(new_seed=0):
    """ Sets the random seed to new_seed. Returns the old seed. """
    if type(new_seed) == type(''):
        new_seed = hash(new_seed) % 2**32

    py_state = random.getstate()
    random.seed(new_seed)

    np_state = np.random.get_state()
    np.random.seed(new_seed)
    return (py_state, np_state)


class constant_seed:

3 Source : model.py
with Apache License 2.0
from alibaba-edu

    def save(self, states, name=None):
        self.saver.save(self.sess, os.path.join(self.args.summary_dir, self.prefix),
                        global_step=self.updates)
        if not name:
            name = str(self.updates)
        # noinspection PyTypeChecker
        numpy_state = list(np.random.get_state())
        numpy_state[1] = numpy_state[1].tolist()
        params = {
            'updates': self.updates,
            'args': self.args,
            'random_state': random.getstate(),
            'numpy_state': numpy_state,
        }
        params.update(states)
        with open(os.path.join(self.args.summary_dir, '{}-{}.stat'.format(self.prefix, name)), 'wb') as f:
            pickle.dump(params, f)

    @classmethod

3 Source : mcmc.py
with BSD 3-Clause "New" or "Revised" License
from andreatramacere

    def run(self):
        self.target_class.model=self.target_class.model.clone()
        self.target_class.sampler.run_mcmc(self.target_class._pos, self.target_class._npernode, rstate0=np.random.get_state(), progress=True,store = True)


class McmcSampler(object):

3 Source : util.py
with Apache License 2.0
from andrewowens

def stash_seed(new_seed = 0):
  """ Sets the random seed to new_seed. Returns the old seed. """
  if type(new_seed) == type(''):
    new_seed = hash(new_seed) % 2**32

  py_state = random.getstate()
  random.seed(new_seed)

  np_state = np.random.get_state()
  np.random.seed(new_seed)
  return (py_state, np_state)

class constant_seed:

3 Source : test_utils.py
with MIT License
from anjandeepsahni

    def test_set_random_seed(self):
        # Set new seed and verify.
        seed = _random.randint(1, 1000)
        _tu.set_random_seed(seed)
        np_new_seed = _np.random.get_state()[1][0]
        torch_new_seed = _torch.initial_seed()
        self.assertEqual(seed, np_new_seed)
        self.assertEqual(seed, torch_new_seed)
        if _torch.cuda.is_available():
            cuda_new_seed = _torch.cuda.initial_seed()
            self.assertEqual(seed, cuda_new_seed)


if __name__ == '__main__':

3 Source : utils.py
with Apache License 2.0
from Ascend

def save_ds_checkpoint(iteration, model, args):
    """Save a model checkpoint."""

    sd = {}
    sd['iteration'] = iteration
    # rng states.
    if not args.no_save_rng:
        sd['random_rng_state'] = random.getstate()
        sd['np_rng_state'] = np.random.get_state()
        sd['torch_rng_state'] = torch.get_rng_state()
        sd['cuda_rng_state'] = torch.cuda.get_rng_state()
        sd['rng_tracker_states'] = mpu.get_cuda_rng_tracker().get_states()
        
    model.save_checkpoint(args.save, iteration, client_state = sd)


def get_checkpoint_iteration(args):

3 Source : data_utils.py
with Apache License 2.0
from Ascend

def numpy_seed(seed, *addl_seeds):
    """Context manager which seeds the NumPy PRNG with the specified seed and
    restores the state afterward"""
    if seed is None:
        yield
        return
    if len(addl_seeds) > 0:
        seed = int(hash((seed, *addl_seeds)) % 1e6)
    state = np.random.get_state()
    np.random.seed(seed)
    try:
        yield
    finally:
        np.random.set_state(state)


def collect_filtered(function, iterable, filtered):

3 Source : data_utils.py
with Apache License 2.0
from Ascend

def numpy_seed(seed):
    """Context manager which seeds the NumPy PRNG with the specified seed and
    restores the state afterward"""
    if seed is None:
        yield
        return
    state = np.random.get_state()
    np.random.seed(seed)
    try:
        yield
    finally:
        np.random.set_state(state)

3 Source : utils.py
with Apache License 2.0
from atcbosselut

def temp_seed(seed):
    state = np.random.get_state()
    np.random.seed(seed)
    try:
        yield
    finally:
        np.random.set_state(state)


def flatten(outer):

3 Source : tabular_torch_dataset.py
with Apache License 2.0
from awslabs

    def build_loader(self, batch_size, num_workers, is_test=False):
        def worker_init_fn(worker_id):
            np.random.seed(np.random.get_state()[1][0] + worker_id)
        loader = torch.utils.data.DataLoader(self, batch_size=batch_size, num_workers=num_workers,
                                             shuffle=False if is_test else True,
                                             drop_last=False if is_test else True,
                                             worker_init_fn=worker_init_fn)
        return loader

3 Source : testing.py
with MIT License
from ballet

def seeded(seed):
    """Set seed, run code, then restore rng state"""
    if seed is not None:
        np_random_state = np.random.get_state()
        random_state = random.getstate()
        np.random.seed(seed)
        random.seed(seed)

    yield

    if seed is not None:
        np.random.set_state(np_random_state)
        random.setstate(random_state)


@funcy.contextmanager

3 Source : feature_sampler.py
with BSD 3-Clause "New" or "Revised" License
from BerkeleyLearnVerify

    def saveToFile(self, path):
        with open(path, 'wb') as outfile:
            randState = random.getstate()
            numpyRandState = np.random.get_state()
            allState = (randState, numpyRandState, self)
            dill.dump(allState, outfile)

    @staticmethod

3 Source : primitives.py
with GNU General Public License v3.0
from caelan

def get_random_seed():
    return np.random.get_state()[1][0]

##################################################

def apply_action(state, action):

3 Source : data_utils.py
with MIT License
from cindyxinyiwang

def numpy_seed(seed, *addl_seeds):
    """Context manager which seeds the NumPy PRNG with the specified seed and
    restores the state afterward"""
    if seed is None:
        yield
        return
    if len(addl_seeds) > 0:
        seed = int(hash((seed, *addl_seeds)) % 1e6)
    state = np.random.get_state()
    np.random.seed(seed)
    try:
        yield
    finally:
        np.random.set_state(state)


def collect_filtered(function, iterable, filtered, noskip=False):

3 Source : model_spatialCNN.py
with MIT License
from clausmichele

def shuffle_in_unison(a, b):
	rng_state = np.random.get_state()
	np.random.shuffle(a)
	np.random.set_state(rng_state)
	np.random.shuffle(b)

class denoiser(object):

3 Source : model_temp3CNN.py
with MIT License
from clausmichele

def shuffle_in_unison(a, b):
	rng_state = np.random.get_state()
	np.random.shuffle(a)
	np.random.set_state(rng_state)
	np.random.shuffle(b)

class TemporalDenoiser(object):

3 Source : seed.py
with Apache License 2.0
from cmb-chula

def get_random_state():
    return {
        'python': random.getstate(),
        'numpy': np.random.get_state(),
        'pytorch': torch.get_rng_state(),
        'pytorch_cuda': torch.cuda.get_rng_state_all(),
    }

def set_random_state(state):

3 Source : pybullet_env.py
with GNU General Public License v3.0
from ColinKohler

  def getStateDict(self):
    self.robot.saveState()
    state = {'current_episode_steps': copy.deepcopy(self.current_episode_steps),
             'objects': copy.deepcopy(self.objects),
             'object_types': copy.deepcopy(self.object_types),
             'heightmap': copy.deepcopy(self.heightmap),
             'robot_state': copy.deepcopy(self.robot.state),
             'random_state': np.random.get_state(),
             'last_action': self.last_action,
             'last_obj': self.last_obj
             }
    return state

  def restoreStateDict(self, state):

3 Source : random.py
with GNU General Public License v3.0
from ComputationalCryoEM

    def __enter__(self):
        if self.seed is not None:
            # Push current state on stack
            random_states.append(np.random.get_state())

            seed = self.seed
            # 5489 is the default seed used by MATLAB for seed 0 !
            if seed == 0:
                seed = 5489

            new_state = np.random.RandomState(seed)
            np.random.set_state(new_state.get_state())

    def __exit__(self, *args):

3 Source : main.py
with MIT License
from CompVis

def worker_init_fn(_):
    worker_info = torch.utils.data.get_worker_info()

    dataset = worker_info.dataset
    worker_id = worker_info.id

    if isinstance(dataset, Txt2ImgIterableBaseDataset):
        split_size = dataset.num_records // worker_info.num_workers
        # reset num_records to the true number to retain reliable length information
        dataset.sample_ids = dataset.valid_ids[worker_id * split_size:(worker_id + 1) * split_size]
        current_id = np.random.choice(len(np.random.get_state()[1]), 1)
        return np.random.seed(np.random.get_state()[1][current_id] + worker_id)
    else:
        return np.random.seed(np.random.get_state()[1][0] + worker_id)


class DataModuleFromConfig(pl.LightningDataModule):

3 Source : utils.py
with MIT License
from danielegrattarola

def shuffle_inplace(*args):
    rng_state = np.random.get_state()
    for a in args:
        np.random.set_state(rng_state)
        np.random.shuffle(a)


def get_spec(x):

3 Source : utils.py
with MIT License
from daniellevy

def subsample_arrays(arrays, n, seed=0):
    rng_state = np.random.get_state()
    np.random.seed(seed)
    take_inds = np.random.choice(len(arrays[0]),
                                 n, replace=False)
    np.random.set_state(rng_state)

    return [a[take_inds] for a in arrays]


def get_weights_norm(model):

3 Source : gridworld.py
with MIT License
from david-lindner

    def _get_random_initial_position(self, seed: Optional[int]) -> Tuple[int, int]:
        """
        Return a random valid initial position.

        The `seed` can be used for reproducibility. It does not affect the
        numpy random state (which is saved initially and then restored after
        generating the environment).
        """
        assert self.tiles is not None
        initial_random_state = np.random.get_state()
        np.random.seed(seed)
        xpos, ypos = self._get_random_empty_tile(self.tiles)
        np.random.set_state(initial_random_state)
        return xpos, ypos

    def _get_random_walls(

3 Source : model.py
with MIT License
from DeepGraphLearning

    def shuffle_in_unison_scary(self, a, b, c):
        rng_state = np.random.get_state()
        np.random.shuffle(a)
        np.random.set_state(rng_state)
        np.random.shuffle(b)
        np.random.set_state(rng_state)
        np.random.shuffle(c)


    def fit_on_batch(self, Xi, Xv, y):

3 Source : model.py
with MIT License
from DeepGraphLearning

    def shuffle_in_unison_scary(self, a, b, c, d, e):
        rng_state = np.random.get_state()
        np.random.shuffle(a)
        np.random.set_state(rng_state)
        np.random.shuffle(b)
        np.random.set_state(rng_state)
        np.random.shuffle(c)
        np.random.set_state(rng_state)
        np.random.shuffle(d)
        np.random.set_state(rng_state)
        np.random.shuffle(e)                


    def fit_on_batch(self, Xi, Xv, Xi_genre, Xv_genre, y):

3 Source : progress.py
with MIT License
from DeepLearnXMU

    def __getstate__(self):
        d = self.__dict__.copy()
        d['random_state'] = (ops.random.get_state(), numpy.random.get_state())
        del d['serializer']

        return d

    def __setstate__(self, state):

3 Source : replay_buffer.py
with MIT License
from denisyarats

def _worker_init_fn(worker_id):
    seed = np.random.get_state()[1][0] + worker_id
    np.random.seed(seed)
    random.seed(seed)


def make_replay_loader(env, replay_dir, max_size, batch_size, num_workers,

3 Source : DeepFM.py
with MIT License
from DinLei

    def shuffle_in_unison_scary(self, a, b, c):
        rng_state = np.random.get_state()
        np.random.shuffle(a)
        np.random.set_state(rng_state)
        np.random.shuffle(b)
        np.random.set_state(rng_state)
        np.random.shuffle(c)

    def fit_on_batch(self, Xi, Xv, y, train_phase=True):

3 Source : cifar10.py
with GNU General Public License v3.0
from dnn-security

def temp_seed(seed):
    state = np.random.get_state()
    np.random.seed(seed)
    try:
        yield
    finally:
        np.random.set_state(state)


class CIFAR10ShuffledSubset(data.Dataset):

3 Source : imagenet.py
with GNU General Public License v3.0
from dnn-security

def temp_seed(seed):
    state = np.random.get_state()
    np.random.seed(seed)
    try:
        yield
    finally:
        np.random.set_state(state)


class ImageNetSingleClassShuffledSubset(datasets.ImageFolder):

3 Source : omniglot.py
with GNU General Public License v3.0
from dnn-security

def temp_seed(seed):
    state = np.random.get_state()
    np.random.seed(seed)
    try:
        yield
    finally:
        np.random.set_state(state)


class OmniglotShuffledSubset(data.Dataset):

3 Source : layer.py
with MIT License
from endernewton

  def _shuffle_roidb_inds(self):
    """Randomly permute the training roidb."""
    # If the random flag is set, 
    # then the database is shuffled according to system time
    # Useful for the validation set
    if self._random:
      st0 = np.random.get_state()
      millis = int(round(time.time() * 1000)) % 4294967295
      np.random.seed(millis)
    
    self._perm = np.random.permutation(np.arange(len(self._roidb)))
    # Restore the random state
    if self._random:
      np.random.set_state(st0)
      
    self._cur = 0

  def _get_next_minibatch_inds(self):

3 Source : data_loader.py
with MIT License
from fishbotics

def worker_init_fn(worker_id):
    """ Use this to bypass issue with PyTorch dataloaders using deterministic RNG for Numpy
        https://github.com/pytorch/pytorch/issues/5059
    """
    np.random.seed(np.random.get_state()[1][0] + worker_id)

def distribute_dataloader(dl, num_replicas, rank):

3 Source : crazyflie_gcg_inference.py
with MIT License
from gkahn13

    def _split_rollouts(self, filenames):
        ### ensure that the training and holdout sets are always split the same
        np_random_state = np.random.get_state()
        np.random.seed(0)

        train_rollouts = []
        holdout_rollouts = []
        for fname in filenames:
            if np.random.random() > self._train_holdout_pct:
                train_rollouts.append(fname)
            else:
                holdout_rollouts.append(fname)

        np.random.set_state(np_random_state)

        return sorted(train_rollouts), sorted(holdout_rollouts)

    def _add_rosbags(self, sampler, rosbag_filenames):

3 Source : utils.py
with MIT License
from HannesStark

def get_random_indices(length, seed=123):
    st0 = np.random.get_state()
    np.random.seed(seed)
    random_indices = np.random.permutation(length)
    np.random.set_state(st0)
    return random_indices

edges_dic = {}

3 Source : __init__.py
with Apache License 2.0
from haven-ai

def random_seed(seed):
    """[summary]

    Parameters
    ----------
    seed : [type]
        [description]
    """
    state = np.random.get_state()
    np.random.seed(seed)
    try:
        yield
    finally:
        np.random.set_state(state)


def is_subset(d1, d2, strict=False):

3 Source : random_state.py
with Apache License 2.0
from Hazoom

    def __init__(self):
        self.random_mod_state = random.getstate()
        self.np_state = np.random.get_state()
        self.torch_cpu_state = torch.get_rng_state()
        self.torch_gpu_states = [
            torch.cuda.get_rng_state(d)
            for d in range(torch.cuda.device_count())
        ]

    def restore(self):

3 Source : misc.py
with BSD 3-Clause "New" or "Revised" License
from holzschu

    def __enter__(self):
        from numpy import random

        self.startstate = random.get_state()
        random.seed(self.seed)

    def __exit__(self, exc_type, exc_value, traceback):

3 Source : classify.py
with MIT License
from houchengbin

    def split_train_evaluate(self, X, Y, train_precent, seed=0):
        state = np.random.get_state()
        training_size = int(train_precent * len(X))
        #np.random.seed(seed) 
        shuffle_indices = np.random.permutation(np.arange(len(X)))
        X_train = [X[shuffle_indices[i]] for i in range(training_size)]
        Y_train = [Y[shuffle_indices[i]] for i in range(training_size)]
        X_test = [X[shuffle_indices[i]] for i in range(training_size, len(X))]
        Y_test = [Y[shuffle_indices[i]] for i in range(training_size, len(X))]

        self.train(X_train, Y_train, Y)
        np.random.set_state(state)  #why??? for binarizer.transform?? 
        return self.evaluate(X_test, Y_test)

    def train(self, X, Y, Y_all):

3 Source : downstream.py
with MIT License
from houchengbin

    def split_train_evaluate(self, X, Y, train_precent, seed=0):
        state = np.random.get_state()
        training_size = int(train_precent * len(X))
        shuffle_indices = np.random.permutation(np.arange(len(X)))
        X_train = [X[shuffle_indices[i]] for i in range(training_size)]
        Y_train = [Y[shuffle_indices[i]] for i in range(training_size)]
        X_test = [X[shuffle_indices[i]] for i in range(training_size, len(X))]
        Y_test = [Y[shuffle_indices[i]] for i in range(training_size, len(X))]

        self.train(X_train, Y_train, Y)
        np.random.set_state(state)
        return self.evaluate(X_test, Y_test)

    def train(self, X, Y, Y_all):

3 Source : transforms.py
with MIT License
from HypoX64

def shuffledata(data,target):
    state = np.random.get_state()
    np.random.shuffle(data)
    np.random.set_state(state)
    np.random.shuffle(target)

def k_fold_generator(length,fold_num,fold_index = 'auto'):

3 Source : data.py
with GNU General Public License v3.0
from HypoX64

def shuffledata(data,target):
    state = np.random.get_state()
    np.random.shuffle(data)
    np.random.set_state(state)
    np.random.shuffle(target)

def random_transform_single_mask(img,out_shape):

3 Source : personalization.py
with Apache License 2.0
from iPERDance

def worker_init_fn(worker_id):
    worker_seed = np.random.get_state()[1][0] + worker_id
    np.random.seed(worker_seed)


class PersonalizerProcess(Process):

3 Source : train.py
with Apache License 2.0
from iPERDance

def worker_init_fn(worker_id):
    worker_seed = np.random.get_state()[1][0] + worker_id
    np.random.seed(worker_seed)


class Train(object):

3 Source : np_utils.py
with MIT License
from Jiayuan-Gu

    def __enter__(self):
        self.state = np.random.get_state()
        np.random.seed(self.seed)
        return self.state

    def __exit__(self, exc_type, exc_val, exc_tb):

3 Source : sychronized_augment.py
with MIT License
from jizongFox

    def __init__(self, random_seed: int = 0):
        self.random_seed = random_seed
        self.randombackup = random.getstate()
        self.npbackup = np.random.get_state()

    def __enter__(self):

3 Source : utils.py
with MIT License
from joeybose

def random_seed(seed):
    state = np.random.get_state()
    np.random.seed(seed)
    try:
        yield
    finally:
        np.random.set_state(state)

@contextlib.contextmanager

See More Examples