Python numpy 模块,RandomState() 实例源码

我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用numpy.RandomState()

项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
def randomstate_constructor(value, name=None, strict=False,
                            allow_downcast=None, borrow=False):
    """
    SharedVariable Constructor for RandomState.

    """
    if not isinstance(value, numpy.random.RandomState):
        raise TypeError
    if not borrow:
        value = copy.deepcopy(value)
    return RandomStateSharedVariable(
        type=raw_random.random_state_type,
        value=value,
        name=name,
        strict=strict,
        allow_downcast=allow_downcast)
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
def seed(self, seed=None):
        """
        Re-initialize each random stream.

        Parameters
        ----------
        seed : None or integer in range 0 to 2**30
            Each random stream will be assigned a unique state that depends
            deterministically on this value.

        Returns
        -------
        None

        """
        if seed is None:
            seed = self.default_instance_seed

        seedgen = numpy.random.RandomState(seed)
        for old_r, new_r in self.state_updates:
            old_r_seed = seedgen.randint(2 ** 30)
            old_r.set_value(numpy.random.RandomState(int(old_r_seed)),
                            borrow=True)
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
def __getitem__(self, item):
        """
        Retrieve the numpy RandomState instance associated with a particular
        stream.

        Parameters
        ----------
        item
            A variable of type RandomStateType, associated
            with this RandomStream.

        Returns
        -------
        numpy RandomState (or None, before initialize)

        Notes
        -----
        This is kept for compatibility with `tensor.randomstreams.RandomStreams`.
        The simpler syntax ``item.rng.get_value()`` is also valid.

        """
        return item.get_value(borrow=True)
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
def __setitem__(self, item, val):
        """
        Set the numpy RandomState instance associated with a particular stream.

        Parameters
        ----------
        item
            A variable of type RandomStateType, associated with this
            RandomStream.

        val : numpy RandomState
            The new value.

        Returns
        -------
        None

        Notes
        -----
        This is kept for compatibility with `tensor.randomstreams.RandomStreams`.
        The simpler syntax ``item.rng.set_value(val)`` is also valid.

        """
        item.set_value(val, borrow=True)
项目:openbadge-analysis    作者:HumanDynamics    | 项目源码 | 文件源码
def _smacof_single(dissimilarities, weights, init=None, anchors=None, n_components=2, maxitr=300, eps=1e-6, random_state=None):
    # Pre-compute the weights of the Guttman transform
    V = _gt_weights(weights)

    if random_state is None:
        random_state = np.random.RandomState()

    # Initial positions are random by default
    if init is None:
        init = random_state.randn(dissimilarities.shape[0]-anchors.shape[0], n_components)
    X = init

    Sprev = _stress(dissimilarities, weights, np.vstack([X, anchors]))  # Stress at previous iteration
    for itr in range(maxitr):
        X = _guttman_transform(dissimilarities, weights, X, anchors, V)

        S = _stress(dissimilarities, weights, np.vstack([X, anchors]))
        if np.abs(S - Sprev) < eps:
            break
        Sprev = S

    return X, Sprev
项目:elfi    作者:elfi-dev    | 项目源码 | 文件源码
def prepare_seed(*inputs, **kwinputs):
    """Update ``kwinputs`` with the seed from its value ``random_state``."""
    if 'random_state' in kwinputs:
        # Get the seed for this batch, assuming np.RandomState instance
        seed = kwinputs['random_state'].get_state()[1][0]

        # Since we may not be the first operation to use this seed, lets generate a
        # a sub seed using this seed
        sub_seed_index = kwinputs.get('index_in_batch') or 0
        kwinputs['seed'] = get_sub_seed(seed, sub_seed_index)

    return inputs, kwinputs
项目:sdaopt    作者:sgubianpm    | 项目源码 | 文件源码
def __init__(self, fun, x0, bounds, seed=None, minimizer_kwargs=None,
                 temperature_start=5230, qv=2.62, qa=-5.0,
                 maxfun=1e7, maxsteps=500, pure_sa=False):
        if x0 is not None and not len(x0) == len(bounds):
            raise ValueError('Bounds size does not match x0')
        lu = list(zip(*bounds))
        lower = np.array(lu[0])
        upper = np.array(lu[1])
        # Checking that bounds are consistent
        if not np.all(lower < upper):
            raise ValueError('Bounds are note consistent min < max')
        # Wrapper for the objective function and minimizer
        if minimizer_kwargs is None:
            minimizer_kwargs = dict()
        self.owf = ObjectiveFunWrapper(bounds, fun, **minimizer_kwargs)
        # Initialization of RandomState for reproducible runs if seed provided
        self.rs = check_random_state(seed)
        # Initialization of the energy state
        self.es = EnergyState(lower, upper)
        self.es.reset(self.owf, self.rs, x0)
        # Maximum number of function call that can be used a stopping criterion
        self.maxfun = maxfun
        # Maximum number of step (main iteration)  that can be used as
        # stopping criterion
        self.maxsteps = maxsteps
        # Minimum value of annealing temperature reached to perform
        # re-annealing
        self.temperature_start = temperature_start
        self.temperature_restart = 0.1
        # VisitingDistribution instance
        vd = VisitingDistribution(lower, upper, qv, self.rs)
        # Markov chain instance
        self.mc = MarkovChain(qa, vd, self.owf, self.rs, self.es)
        self.qv = qv
        self.pure_sa = pure_sa
项目:tslearn    作者:rtavenar    | 项目源码 | 文件源码
def random_walks(n_ts=100, sz=256, d=1, mu=0., std=1., random_state=None):
    """Random walk time series generator.

    Generate n_ts time series of size sz and dimensionality d.
    Generated time series follow the model:
    $$ts[t] = ts[t - 1] + a$$
    where :math:`a` is drawn from a normal distribution of mean mu and standard deviation std.

    Parameters
    ----------
    n_ts : int (default: 100)
        Number of time series.
    sz : int (default: 256)
        Length of time series (number of time instants).
    d : int (default: 1)
        Dimensionality of time series.
    mu : float (default: 0.)
        Mean of the normal distribution from which random walk steps are drawn.
    std : float (default: 1.)
        Standard deviation of the normal distribution from which random walk steps are drawn.
    random_state : integer or numpy.RandomState or None (default: None)
        Generator used to draw the time series. If an integer is given, it fixes the seed. Defaults to the global
        numpy random number generator.

    Returns
    -------
    numpy.ndarray
        A dataset of random walk time series

    Examples
    --------
    >>> random_walks(n_ts=100, sz=256, d=5, mu=0., std=1.).shape
    (100, 256, 5)
    """
    rs = check_random_state(random_state)
    ts = numpy.empty((n_ts, sz, d))
    rnd = rs.randn(n_ts, sz, d) * std + mu
    ts[:, 0, :] = rnd[:, 0, :]
    for t in range(1, sz):
        ts[:, t, :] = ts[:, t - 1, :] + rnd[:, t, :]
    return ts
项目:tslearn    作者:rtavenar    | 项目源码 | 文件源码
def gamma_soft_dtw(dataset, n_samples=100, random_state=None):
    """Compute gamma value to be used for GAK/Soft-DTW.

    This method was originally presented in [1]_.

    Parameters
    ----------
    dataset
        A dataset of time series
    n_samples : int (default: 100)
        Number of samples on which median distance should be estimated
    random_state : integer or numpy.RandomState or None (default: None)
        The generator used to draw the samples. If an integer is given, it fixes the seed. Defaults to the global
        numpy random number generator.

    Returns
    -------
    float
        Suggested :math:`\\gamma` parameter for the Soft-DTW

    Example
    -------
    >>> dataset = [[1, 2, 2, 3], [1., 2., 3., 4.]]
    >>> gamma_soft_dtw(dataset=dataset, n_samples=200, random_state=0)  # doctest: +ELLIPSIS
    8.0...

    See Also
    --------
    sigma_gak : Compute sigma parameter for Global Alignment kernel

    References
    ----------
    .. [1] M. Cuturi, "Fast global alignment kernels," ICML 2011.
    """
    return 2. * sigma_gak(dataset=dataset, n_samples=n_samples, random_state=random_state) ** 2
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
def __init__(self, seed=None):
        super(RandomStreams, self).__init__()
        # A list of pairs of the form (input_r, output_r).  This will be
        # over-ridden by the module instance to contain stream generators.
        self.state_updates = []
        # Instance variable should take None or integer value. Used to seed the
        # random number generator that provides seeds for member streams.
        self.default_instance_seed = seed
        # numpy.RandomState instance that gen() uses to seed new streams.
        self.gen_seedgen = numpy.random.RandomState(seed)
项目:tslearn    作者:rtavenar    | 项目源码 | 文件源码
def random_walk_blobs(n_ts_per_blob=100, sz=256, d=1, n_blobs=2, noise_level=1., random_state=None):
    """Blob-based random walk time series generator.

    Generate n_ts_per_blobs * n_blobs time series of size sz and dimensionality d.
    Generated time series follow the model:
    $$ts[t] = ts[t - 1] + a$$
    where :math:`a` is drawn from a normal distribution of mean mu and standard deviation std.

    Each blob contains time series derived from a same seed time series with added white noise.

    Parameters
    ----------
    n_ts_per_blob : int (default: 100)
        Number of time series in each blob
    sz : int (default: 256)
        Length of time series (number of time instants)
    d : int (default: 1)
        Dimensionality of time series
    n_blobs : int (default: 2)
        Number of blobs
    noise_level : float (default: 1.)
        Standard deviation of white noise added to time series in each blob
    random_state : integer or numpy.RandomState or None (default: None)
        Generator used to draw the time series. If an integer is given, it fixes the seed. Defaults to the global
        numpy random number generator.

    Returns
    -------
    numpy.ndarray
        A dataset of random walk time series

    Examples
    --------
    >>> X, y = random_walk_blobs(n_ts_per_blob=100, sz=256, d=5, n_blobs=3)
    >>> X.shape
    (300, 256, 5)
    >>> y.shape
    (300,)
    """
    rs = check_random_state(random_state)
    base_ts = random_walks(n_ts=n_blobs, sz=sz, d=d, std=1.0, random_state=rs)
    rnd = rs.randn(n_ts_per_blob * n_blobs, sz, d) * noise_level
    ts = numpy.repeat(base_ts, repeats=n_ts_per_blob, axis=0)
    y = numpy.repeat(range(n_blobs), repeats=n_ts_per_blob)
    return ts + rnd, y
项目:tslearn    作者:rtavenar    | 项目源码 | 文件源码
def sigma_gak(dataset, n_samples=100, random_state=None):
    """Compute sigma value to be used for GAK.

    This method was originally presented in [1]_.

    Parameters
    ----------
    dataset
        A dataset of time series
    n_samples : int (default: 100)
        Number of samples on which median distance should be estimated
    random_state : integer or numpy.RandomState or None (default: None)
        The generator used to draw the samples. If an integer is given, it fixes the seed. Defaults to the global
        numpy random number generator.

    Returns
    -------
    float
        Suggested bandwidth (:math:`\\sigma`) for the Global Alignment kernel

    Example
    -------
    >>> dataset = [[1, 2, 2, 3], [1., 2., 3., 4.]]
    >>> sigma_gak(dataset=dataset, n_samples=200, random_state=0)  # doctest: +ELLIPSIS
    2.0...

    See Also
    --------
    gak : Compute Global Alignment kernel
    cdist_gak : Compute cross-similarity matrix using Global Alignment kernel

    References
    ----------
    .. [1] M. Cuturi, "Fast global alignment kernels," ICML 2011.
    """
    random_state = check_random_state(random_state)
    dataset = to_time_series_dataset(dataset)
    n_ts, sz, d = dataset.shape
    if n_ts * sz < n_samples:
        replace = True
    else:
        replace = False
    sample_indices = random_state.choice(n_ts * sz, size=n_samples, replace=replace)
    dists = pdist(dataset.reshape((-1, d))[sample_indices], metric="euclidean")
    return numpy.median(dists) * numpy.sqrt(sz)