def rvs(self, size=None, random_state=None):
"""Sample the joint prior."""
random_state = np.random if random_state is None else random_state
context = ComputationContext(size or 1, seed='global')
loaded_net = self.client.load_data(self._rvs_net, context, batch_index=0)
# Change to the correct random_state instance
# TODO: allow passing random_state to ComputationContext seed
loaded_net.node['_random_state'] = {'output': random_state}
batch = self.client.compute(loaded_net)
rvs = np.column_stack([batch[p] for p in self.parameter_names])
if self.dim == 1:
rvs = rvs.reshape(size or 1)
return rvs[0] if size is None else rvs
python类random()的实例源码
def raw_to_floatX(imb, pixel_shift=0.5, square=True, center=False, rng=None):
rng = rng if rng else np.random
w,h = imb.shape[2], imb.shape[3] # image size
x, y = 0,0 # offsets
if square:
if w > h:
if center:
x = (w-h)/2
else:
x = rng.randint(w-h)
w=h
elif h > w:
if center:
y = (h-w)/2
else:
y = rng.randint(h-w)
h=w
return nn.utils.floatX(imb)[:,:,x:x+w,y:y+h]/ 255. - pixel_shift
# creates and hdf5 file from a dataset given a split in the form {'train':(0,n)}, etc
# appears to save in unpredictable order, so order must be verified after creation
def batch_loader(self, rnd_gen=np.random, shuffle=True):
"""load_mbs yields a new minibatch at each iteration"""
batchsize = self.batchsize
inds = np.arange(self.n_samples)
if shuffle:
rnd_gen.shuffle(inds)
n_mbs = np.int(np.ceil(self.n_samples / batchsize))
x = np.zeros(self.X_shape, np.float32)
y = np.zeros(self.y_shape, np.float32)
ids = np.empty((batchsize,), np.object_)
for m in range(n_mbs):
start = m * batchsize
end = (m + 1) * batchsize
if end > self.n_samples:
end = self.n_samples
mb_slice = slice(start, end)
x[:end - start, :] = self.x[inds[mb_slice], :]
y[:end - start, :] = self.y[inds[mb_slice], :]
ids[:end - start] = self.ids[inds[mb_slice]]
yield dict(X=x, y=y, ID=ids)
def batch_loader(self, rnd_gen=np.random, shuffle=True):
"""load_mbs yields a new minibatch at each iteration"""
batchsize = self.batchsize
inds = np.arange(self.n_samples)
if shuffle:
rnd_gen.shuffle(inds)
n_mbs = np.int(np.ceil(self.n_samples / batchsize))
x = np.zeros(self.X_shape, np.float32)
y = np.zeros(self.y_shape, np.float32)
ids = np.empty((batchsize,), np.object_)
for m in range(n_mbs):
start = m * batchsize
end = (m + 1) * batchsize
if end > self.n_samples:
end = self.n_samples
mb_slice = slice(start, end)
x[:end - start, :] = self.x[inds[mb_slice], :]
y[:end - start, :] = self.y[inds[mb_slice], :]
ids[:end - start] = self.ids[inds[mb_slice]]
yield dict(X=x, y=y, ID=ids)
def __init__(self, n_samples, duration, *ops, **kwargs):
super(Sampler, self).__init__(*ops)
self.n_samples = n_samples
self.duration = duration
random_state = kwargs.pop('random_state', None)
if random_state is None:
self.rng = np.random
elif isinstance(random_state, int):
self.rng = np.random.RandomState(seed=random_state)
elif isinstance(random_state, np.random.RandomState):
self.rng = random_state
else:
raise ParameterError('Invalid random_state={}'.format(random_state))
def __init__(self, data, rng=None):
if rng is None:
rng = np.random
if is_integer(data):
if data < 1:
raise ValidationError("Number of dimensions must be a "
"positive int", attr='data', obj=self)
self.v = rng.randn(data)
self.v /= np.linalg.norm(self.v)
else:
self.v = np.array(data, dtype=float)
if len(self.v.shape) != 1:
raise ValidationError("'data' must be a vector", 'data', self)
self.v.setflags(write=False)
def mahalanobis_norm(self, dx):
"""return Mahalanobis norm based on the current sample
distribution.
The norm is based on Covariance matrix ``C`` times ``sigma**2``,
and includes ``sigma_vec``. The expected Mahalanobis distance to
the sample mean is about ``sqrt(dimension)``.
Argument
--------
A *genotype* difference `dx`.
Example
-------
>>> import cma, numpy
>>> es = cma.CMAEvolutionStrategy(numpy.ones(10), 1) #doctest: +ELLIPSIS
(5_w,...
>>> xx = numpy.random.randn(2, 10)
>>> d = es.mahalanobis_norm(es.gp.geno(xx[0]-xx[1]))
`d` is the distance "in" the true sample distribution,
sampled points have a typical distance of ``sqrt(2*es.N)``,
where ``es.N`` is the dimension, and an expected distance of
close to ``sqrt(N)`` to the sample mean. In the example,
`d` is the Euclidean distance, because C = I and sigma = 1.
"""
return self.sm.norm(np.asarray(dx) / self.sigma_vec.scaling) / self.sigma
def get_rng():
"""Get the package-level random number generator.
Returns
-------
:class:`numpy.random.RandomState` instance
The :class:`numpy.random.RandomState` instance passed to the most
recent call of :func:`set_rng`, or ``numpy.random`` if :func:`set_rng`
has never been called.
"""
return _rng
def set_rng(rng):
"""Set the package-level random number generator.
Parameters
----------
new_rng : ``numpy.random`` or a :class:`numpy.random.RandomState` instance
The random number generator to use.
"""
global _rng
_rng = rng
def set_seed(seed):
"""Set numpy seed.
Parameters
----------
seed : int
"""
global _rng
_rng = np.random.RandomState(seed)
def __init__(self, db, keys, rng=np.random):
super(DataIterator, self).__init__()
self.db = db
self.keys = keys
self.rng = rng
# If there is only one key, wrap it in a list
if isinstance(self.keys, str):
self.keys = [self.keys]
# Retrieve the data specification (shape & dtype) for all data objects
# Assumes that all samples have the same shape and data type
self.spec = db.get_data_specification(0)
def __init__(self, db, keys, batch_size, shuffle=False, endless=True,
rng=np.random):
super(SimpleBatch, self).__init__(db, keys, rng)
self.batch_size = batch_size
self.shuffle = shuffle
self.endless = endless
# Set up Python generator
self.gen = self.batch()
def __init__(self, db, keys, batch_size, shuffle=False, endless=True,
rng=np.random):
super(SimpleBatchThreadSafe, self).__init__(db, keys, batch_size,
shuffle, endless, rng)
def __init__(self, db, keys, batch_size, rng=np.random):
super(StochasticBatch, self).__init__(db, keys, rng)
self.batch_size = batch_size
# Set up Python generator
self.gen = self.batch()
def __init__(self, db, keys, batch_size, rng=np.random):
super(StochasticBatchThreadSafe, self).__init__(db, keys, batch_size,
rng)
def random_lowrank(rows, cols, rank, randstate=np.random, dtype=np.float_):
"""Returns a random lowrank matrix of given shape and dtype"""
if dtype == np.float_:
A = randstate.randn(rows, rank)
B = randstate.randn(cols, rank)
elif dtype == np.complex_:
A = randstate.randn(rows, rank) + 1.j * randstate.randn(rows, rank)
B = randstate.randn(cols, rank) + 1.j * randstate.randn(cols, rank)
else:
raise ValueError("{} is not a valid dtype".format(dtype))
C = A.dot(B.conj().T)
return C / np.linalg.norm(C)
def random_fullrank(rows, cols, **kwargs):
"""Returns a random matrix of given shape and dtype. Should provide
same interface as random_lowrank"""
kwargs.pop('rank', None)
return random_lowrank(rows, cols, min(rows, cols), **kwargs)
def _zrandn(shape, randstate=None):
"""Shortcut for :code:`np.random.randn(*shape) + 1.j *
np.random.randn(*shape)`
:param randstate: Instance of np.radom.RandomState or None (which yields
the default np.random) (default None)
"""
randstate = randstate if randstate is not None else np.random
return randstate.randn(*shape) + 1.j * randstate.randn(*shape)
def _randn(shape, randstate=None):
"""Shortcut for :code:`np.random.randn(*shape)`
:param randstate: Instance of np.radom.RandomState or None (which yields
the default np.random) (default None)
"""
randstate = randstate if randstate is not None else np.random
return randstate.randn(*shape)
def _random_state(sites, ldim, randstate=None):
"""Returns a random positive semidefinite operator of shape (ldim, ldim) *
sites normalized to Tr rho = 1, i.e. a mixed state with local dimension
`ldim` living on `sites` sites. Note that the returned state is positive
semidefinite only when interpreted in global form (see
:func:`tools.global_to_local`)
:param sites: Number of local sites
:param ldim: Local ldimension
:param randstate: numpy.random.RandomState instance or None
:returns: numpy.ndarray of shape (ldim, ldim) * sites
>>> from numpy.linalg import eigvalsh
>>> rho = _random_state(3, 2).reshape((2**3, 2**3))
>>> all(eigvalsh(rho) >= 0)
True
>>> np.abs(np.trace(rho) - 1) < 1e-6
True
"""
shape = (ldim**sites, ldim**sites)
mat = _zrandn(shape, randstate=randstate)
rho = np.conj(mat.T).dot(mat)
rho /= np.trace(rho)
return rho.reshape((ldim,) * 2 * sites)
####################################
# Factory functions for MPArrays #
####################################