python类random()的实例源码

utils.py 文件源码 项目:elfi 作者: elfi-dev 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:experiments 作者: tencia 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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
datasets.py 文件源码 项目:tensorflow-layer-library 作者: bioinf-jku 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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)
datasets.py 文件源码 项目:tensorflow-layer-library 作者: bioinf-jku 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
sampler.py 文件源码 项目:pumpp 作者: bmcfee 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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))
pointer.py 文件源码 项目:nengo_spa 作者: nengo 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
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)
evolution_strategy.py 文件源码 项目:pycma 作者: CMA-ES 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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
random.py 文件源码 项目:NumpyDL 作者: oujago 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
random.py 文件源码 项目:NumpyDL 作者: oujago 项目源码 文件源码 阅读 45 收藏 0 点赞 0 评论 0
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
random.py 文件源码 项目:NumpyDL 作者: oujago 项目源码 文件源码 阅读 54 收藏 0 点赞 0 评论 0
def set_seed(seed):
    """Set numpy seed.

    Parameters
    ----------
    seed : int
    """
    global _rng
    _rng = np.random.RandomState(seed)
iterators.py 文件源码 项目:ml-pyxis 作者: vicolab 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
iterators.py 文件源码 项目:ml-pyxis 作者: vicolab 项目源码 文件源码 阅读 44 收藏 0 点赞 0 评论 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()
iterators.py 文件源码 项目:ml-pyxis 作者: vicolab 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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)
iterators.py 文件源码 项目:ml-pyxis 作者: vicolab 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
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()
iterators.py 文件源码 项目:ml-pyxis 作者: vicolab 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def __init__(self, db, keys, batch_size, rng=np.random):
        super(StochasticBatchThreadSafe, self).__init__(db, keys, batch_size,
                                                        rng)
_testing.py 文件源码 项目:mpnum 作者: dseuss 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
_testing.py 文件源码 项目:mpnum 作者: dseuss 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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)
factory.py 文件源码 项目:mpnum 作者: dseuss 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
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)
factory.py 文件源码 项目:mpnum 作者: dseuss 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
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)
factory.py 文件源码 项目:mpnum 作者: dseuss 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
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  #
####################################


问题


面经


文章

微信
公众号

扫码关注公众号