当前位置: 首页>>代码示例>>Python>>正文


Python numpy.random方法代码示例

本文整理汇总了Python中numpy.random方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.random方法的具体用法?Python numpy.random怎么用?Python numpy.random使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numpy的用法示例。


在下文中一共展示了numpy.random方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: partial_fit

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import random [as 别名]
def partial_fit(self, X, y, classes=None):
        if self.partial_method == "gamma":
            w_all = -np.log(self
                            .random_state
                            .random(size=(X.shape[0], self.nsamples))
                            .clip(min=1e-12, max=None))
            appear_times = None
            rng = None
        elif self.partial_method == "poisson":
            w_all = None
            appear_times = self.random_state.poisson(1, size = (X.shape[0], self.nsamples))
            rng = np.arange(X.shape[0])
        else:
            raise ValueError(_unexpected_err_msg)
        Parallel(n_jobs=self.njobs, verbose=0, require="sharedmem")\
                (delayed(self._partial_fit_single)\
                    (sample, w_all, appear_times, rng, X, y) \
                        for sample in range(self.nsamples)) 
开发者ID:david-cortes,项目名称:contextualbandits,代码行数:20,代码来源:utils.py

示例2: main

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import random [as 别名]
def main(env_id, policy_file, record, stochastic, extra_kwargs):
    import gym
    from gym import wrappers
    import tensorflow as tf
    from es_distributed.policies import MujocoPolicy
    import numpy as np

    env = gym.make(env_id)
    if record:
        import uuid
        env = wrappers.Monitor(env, '/tmp/' + str(uuid.uuid4()), force=True)

    if extra_kwargs:
        import json
        extra_kwargs = json.loads(extra_kwargs)

    with tf.Session():
        pi = MujocoPolicy.Load(policy_file, extra_kwargs=extra_kwargs)
        while True:
            rews, t = pi.rollout(env, render=True, random_stream=np.random if stochastic else None)
            print('return={:.4f} len={}'.format(rews.sum(), t))

            if record:
                env.close()
                return 
开发者ID:openai,项目名称:evolution-strategies-starter,代码行数:27,代码来源:viz.py

示例3: elastic_transform

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import random [as 别名]
def elastic_transform(image, alpha=1000, sigma=30, spline_order=1, mode='nearest', random_state=np.random):
    """Elastic deformation of image as described in [Simard2003]_.
    .. [Simard2003] Simard, Steinkraus and Platt, "Best Practices for
       Convolutional Neural Networks applied to Visual Document Analysis", in
       Proc. of the International Conference on Document Analysis and
       Recognition, 2003.
    """
    assert image.ndim == 3
    shape = image.shape[:2]

    dx = gaussian_filter((random_state.rand(*shape) * 2 - 1),
                         sigma, mode="constant", cval=0) * alpha
    dy = gaussian_filter((random_state.rand(*shape) * 2 - 1),
                         sigma, mode="constant", cval=0) * alpha

    x, y = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), indexing='ij')
    indices = [np.reshape(x + dx, (-1, 1)), np.reshape(y + dy, (-1, 1))]
    result = np.empty_like(image)
    for i in range(image.shape[2]):
        result[:, :, i] = map_coordinates(
            image[:, :, i], indices, order=spline_order, mode=mode).reshape(shape)
    return result 
开发者ID:ozan-oktay,项目名称:Attention-Gated-Networks,代码行数:24,代码来源:myImageTransformations.py

示例4: test_random_state

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import random [as 别名]
def test_random_state():
    import numpy.random as npr
    # Check with seed
    state = com.random_state(5)
    assert state.uniform() == npr.RandomState(5).uniform()

    # Check with random state object
    state2 = npr.RandomState(10)
    assert com.random_state(state2).uniform() == npr.RandomState(10).uniform()

    # check with no arg random state
    assert com.random_state() is np.random

    # Error for floats or strings
    with pytest.raises(ValueError):
        com.random_state('test')

    with pytest.raises(ValueError):
        com.random_state(5.5) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:21,代码来源:test_common.py

示例5: _create_missing_idx

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import random [as 别名]
def _create_missing_idx(nrows, ncols, density, random_state=None):
    if random_state is None:
        random_state = np.random
    else:
        random_state = np.random.RandomState(random_state)

    # below is cribbed from scipy.sparse
    size = int(np.round((1 - density) * nrows * ncols))
    # generate a few more to ensure unique values
    min_rows = 5
    fac = 1.02
    extra_size = min(size + min_rows, fac * size)

    def _gen_unique_rand(rng, _extra_size):
        ind = rng.rand(int(_extra_size))
        return np.unique(np.floor(ind * nrows * ncols))[:size]

    ind = _gen_unique_rand(random_state, extra_size)
    while ind.size < size:
        extra_size *= 1.05
        ind = _gen_unique_rand(random_state, extra_size)

    j = np.floor(ind * 1. / nrows).astype(int)
    i = (ind - j * nrows).astype(int)
    return i.tolist(), j.tolist() 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:27,代码来源:testing.py

示例6: _check_random_state

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import random [as 别名]
def _check_random_state(seed):
        """
        Turn seed into a np.random.RandomState instance (took for sklearn)

        Parameters
        ----------
        seed : None | int | instance of RandomState
            If seed is None, return the RandomState singleton used by np.random.
            If seed is an int, return a new RandomState instance seeded with it.
            If seed is already a RandomState instance, return it.
            Otherwise raise ValueError.
        """
        if seed is None or seed is np.random:
            return np.random.mtrand._rand
        if isinstance(seed, (numbers.Integral, np.integer)):
            return np.random.RandomState(seed)
        if isinstance(seed, np.random.RandomState):
            return seed
        raise ValueError('%r cannot be used to seed a numpy.random.RandomState'
                         ' instance' % seed) 
开发者ID:hpclab,项目名称:rankeval,代码行数:22,代码来源:dataset.py

示例7: check_random_state

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import random [as 别名]
def check_random_state(seed):
    """
    Turn seed into a mt.random.RandomState instance

    :param seed:
        If seed is None, return the RandomState singleton used by mt.random.
        If seed is an int, return a new RandomState instance seeded with seed.
        If seed is already a RandomState instance, return it.
        Otherwise raise ValueError.
    :return:
    """
    from . import random as mtrand
    from numpy import random as np_mtrand

    if seed is None or seed is mtrand or seed is np_mtrand:
        return mtrand._random_state
    if isinstance(seed, (Integral, np.integer)):
        return mtrand.RandomState(seed)
    if isinstance(seed, np.random.RandomState):
        return mtrand.RandomState.from_numpy(seed)
    if isinstance(seed, mtrand.RandomState):
        return seed
    raise ValueError('%r cannot be used to seed a mt.random.RandomState'
                     ' instance' % seed) 
开发者ID:mars-project,项目名称:mars,代码行数:26,代码来源:utils.py

示例8: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import random [as 别名]
def __init__(self, image_folder, max_images=False, image_size=(512, 512), add_random_masks=False):
        super(ImageInpaintingData, self).__init__()

        if isinstance(image_folder, str):
            self.images = glob.glob(os.path.join(image_folder, "clean/*"))
        else:
            self.images = list(chain.from_iterable([glob.glob(os.path.join(i, "clean/*")) for i in image_folder]))
        assert len(self.images) > 0

        if max_images:
            self.images = random.choices(self.images, k=max_images)
        print(f"Find {len(self.images)} images.")

        self.img_size = image_size

        self.transformer = Compose([RandomGrayscale(p=0.4),
                                    # ColorJitter(brightness=0.2, contrast=0.2, saturation=0, hue=0),
                                    ToTensor(),
                                    # Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
                                    ])
        self.add_random_masks = add_random_masks 
开发者ID:yu45020,项目名称:Text_Segmentation_Image_Inpainting,代码行数:23,代码来源:Dataloader.py

示例9: random_masks

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import random [as 别名]
def random_masks(pil_img, size=512, offset=10):
    draw = ImageDraw.Draw(pil_img)
    # draw liens
    # can't use np.random because its not forkable under PyTorch's dataloader with multiprocessing
    reps = random.randint(1, 5)

    for i in range(reps):
        cords = np.array(random.choices(range(offset, size), k=4)).reshape(2, 2)
        cords[1] = np.clip(cords[1], a_min=cords[0] - 75, a_max=cords[0] + 75)

        width = random.randint(15, 20)
        draw.line(cords.reshape(-1).tolist(), width=width, fill=255)
    # # draw circles
    reps = random.randint(1, 5)
    for i in range(reps):
        cords = np.array(random.choices(range(offset, size - offset), k=2))
        cords.sort()
        ex = np.array(random.choices(range(20, 70), k=2)) + cords
        ex = np.clip(ex, a_min=offset, a_max=size - offset)
        draw.ellipse(np.concatenate([cords, ex]).tolist(), fill=255)
    return pil_img 
开发者ID:yu45020,项目名称:Text_Segmentation_Image_Inpainting,代码行数:23,代码来源:Dataloader.py

示例10: repair

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import random [as 别名]
def repair(self, x, rnd=rand):
        r"""Repair solution and put the solution in the random position inside of the bounds of problem.

        Arguments:
                x (numpy.ndarray): Solution to check and repair if needed.
                rnd (mtrand.RandomState): Random number generator.

        Returns:
                numpy.ndarray: Fixed solution.

        See Also:
                * :func:`NiaPy.util.limitRepair`
                * :func:`NiaPy.util.limitInversRepair`
                * :func:`NiaPy.util.wangRepair`
                * :func:`NiaPy.util.randRepair`
                * :func:`NiaPy.util.reflectRepair`

        """

        return self.frepair(x, self.Lower, self.Upper, rnd=rnd) 
开发者ID:NiaOrg,项目名称:NiaPy,代码行数:22,代码来源:task.py

示例11: Neighborhood

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import random [as 别名]
def Neighborhood(x, delta, task, rnd=rand):
	r"""Get neighbours of point.

	Args:
		x numpy.ndarray: Point.
		delta (float): Standard deviation.
		task (Task): Optimization task.
		rnd (Optional[mtrand.RandomState]): Random generator.

	Returns:
		Tuple[numpy.ndarray, float]:
			1. New solution.
			2. New solutions function/fitness value.
	"""
	X = x + rnd.normal(0, delta, task.D)
	X = task.repair(X, rnd)
	Xfit = task.eval(X)
	return X, Xfit 
开发者ID:NiaOrg,项目名称:NiaPy,代码行数:20,代码来源:hc.py

示例12: Elitism

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import random [as 别名]
def Elitism(x, xpb, xb, xr, MP_c, MP_s, MP_p, F, CR, task, rnd=rand):
	r"""Select the best of all three strategies.

	Args:
		x (numpy.ndarray): individual position.
		xpb (numpy.ndarray): individuals best position.
		xb (numpy.ndarray): current best position.
		xr (numpy.ndarray): random individual.
		MP_c (float): Fickleness index value.
		MP_s (float): External irregularity index value.
		MP_p (float): Internal irregularity index value.
		F (float): scale factor.
		CR (float): crossover factor.
		task (Task): optimization task.
		rnd (mtrand.randomstate): random number generator.

	Returns:
		Tuple[numpy.ndarray, float]:
			1. New position of individual
			2. New positions fitness/function value
	"""
	xn = [task.repair(MP_C(x, F, CR, MP_c, rnd), rnd=rnd), task.repair(MP_S(x, xr, xb, CR, MP_s, rnd), rnd=rnd), task.repair(MP_P(x, xpb, CR, MP_p, rnd), rnd=rnd)]
	xn_f = apply_along_axis(task.eval, 1, xn)
	ib = argmin(xn_f)
	return xn[ib], xn_f[ib] 
开发者ID:NiaOrg,项目名称:NiaPy,代码行数:27,代码来源:aso.py

示例13: Sequential

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import random [as 别名]
def Sequential(x, xpb, xb, xr, MP_c, MP_s, MP_p, F, CR, task, rnd=rand):
	r"""Sequentialy combines all three strategies.

	Args:
		x (numpy.ndarray): individual position.
		xpb (numpy.ndarray): individuals best position.
		xb (numpy.ndarray): current best position.
		xr (numpy.ndarray): random individual.
		MP_c (float): Fickleness index value.
		MP_s (float): External irregularity index value.
		MP_p (float): Internal irregularity index value.
		F (float): scale factor.
		CR (float): crossover factor.
		task (Task): optimization task.
		rnd (mtrand.randomstate): random number generator.

	Returns:
		tuple[numpy.ndarray, float]:
			1. new position
			2. new positions function/fitness value
	"""
	xn = task.repair(MP_S(MP_P(MP_C(x, F, CR, MP_c, rnd), xpb, CR, MP_p, rnd), xr, xb, CR, MP_s, rnd), rnd=rnd)
	return xn, task.eval(xn) 
开发者ID:NiaOrg,项目名称:NiaPy,代码行数:25,代码来源:aso.py

示例14: Crossover

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import random [as 别名]
def Crossover(x, xpb, xb, xr, MP_c, MP_s, MP_p, F, CR, task, rnd=rand):
	r"""Create a crossover over all three strategies.

	Args:
		x (numpy.ndarray): individual position.
		xpb (numpy.ndarray): individuals best position.
		xb (numpy.ndarray): current best position.
		xr (numpy.ndarray): random individual.
		MP_c (float): Fickleness index value.
		MP_s (float): External irregularity index value.
		MP_p (float): Internal irregularity index value.
		F (float): scale factor.
		CR (float): crossover factor.
		task (Task): optimization task.
		rnd (mtrand.randomstate): random number generator.

	Returns:
		Tuple[numpy.ndarray, float]:
			1. new position
			2. new positions function/fitness value
	"""
	xns = [task.repair(MP_C(x, F, CR, MP_c, rnd), rnd=rnd), task.repair(MP_S(x, xr, xb, CR, MP_s, rnd), rnd=rnd), task.repair(MP_P(x, xpb, CR, MP_p, rnd), rnd=rnd)]
	x = asarray([xns[rnd.randint(len(xns))][i] if rnd.rand() < CR else x[i] for i in range(len(x))])
	return x, task.eval(x) 
开发者ID:NiaOrg,项目名称:NiaPy,代码行数:26,代码来源:aso.py

示例15: MP_C

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import random [as 别名]
def MP_C(x, F, CR, MP, rnd=rand):
	r"""Get bew position based on fickleness.

	Args:
		x (numpy.ndarray): Current individuals position.
		F (float): Scale factor.
		CR (float): Crossover probability.
		MP (float): Fickleness index value
		rnd (mtrand.RandomState): Random number generator

	Returns:
		numpy.ndarray: New position
	"""
	if MP < 0.5:
		b = sort(rnd.choice(len(x), 2, replace=False))
		x[b[0]:b[1]] = x[b[0]:b[1]] + F * rnd.normal(0, 1, b[1] - b[0])
		return x
	return asarray([x[i] + F * rnd.normal(0, 1) if rnd.rand() < CR else x[i] for i in range(len(x))]) 
开发者ID:NiaOrg,项目名称:NiaPy,代码行数:20,代码来源:aso.py


注:本文中的numpy.random方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。