本文整理汇总了Python中numpy.random.random方法的典型用法代码示例。如果您正苦于以下问题:Python random.random方法的具体用法?Python random.random怎么用?Python random.random使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy.random
的用法示例。
在下文中一共展示了random.random方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start_new_particles
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import random [as 别名]
def start_new_particles(self):
"""
Start some new particles from the emitters. We roll the dice
starts_at_once times, seeing if we can start each particle based
on starts_prob. If we start, the particle gets a color form
the palette and a velocity from the vel list.
"""
for e_pos, e_dir, e_vel, e_range, e_color, e_pal in self.emitters:
for roll in range(self.starts_at_once):
if random.random() < self.starts_prob: # Start one?
p_vel = self.vel[random.choice(len(self.vel))]
if e_dir < 0 or e_dir == 0 and random.random() > 0.5:
p_vel = -p_vel
self.particles.append((
p_vel, # Velocity
e_pos, # Position
int(e_range // abs(p_vel)), # steps to live
e_pal[
random.choice(len(e_pal))], # Color
255)) # Brightness
示例2: select
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import random [as 别名]
def select(self, population: Population, n: int = 1) -> Sequence[Individual]:
"""Return `n` individuals from the population.
Parameters
----------
population
A Population of Individuals.
n : int
The number of parents to select from the population. Default is 1.
Returns
-------
Sequence[Individual]
The selected Individuals.
"""
super().select(population, n)
population_total_errors = np.array([i.total_error for i in population])
sum_of_total_errors = np.sum(population_total_errors)
probabilities = 1.0 - (population_total_errors / sum_of_total_errors)
selected_ndxs = np.searchsorted(np.cumsum(probabilities), random(n))
return [population[ndx] for ndx in selected_ndxs]
示例3: _gaussian_noise_factor
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import random [as 别名]
def _gaussian_noise_factor():
"""Return Gaussian noise of mean 0, std dev 1.
Returns
--------
Float samples from Gaussian distribution.
Examples
--------
>>> gaussian_noise_factor()
1.43412557975
>>> gaussian_noise_factor()
-0.0410900866765
"""
return math.sqrt(-2.0 * math.log(random())) * math.cos(2.0 * math.pi * random())
# Mutations
# @TODO: Implement all the common literal mutations.
示例4: produce
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import random [as 别名]
def produce(self, parents: Sequence[Genome], spawner: GeneSpawner = None) -> Genome:
"""Produce a child Genome from parent Genomes and optional GenomeSpawner.
Parameters
----------
parents
A list of parent Genomes given to the operator.
spawner
A GeneSpawner that can be used to produce new genes (aka Atoms).
"""
super().produce(parents, spawner)
self.checknum_parents(parents)
new_genome = Genome()
for atom in parents[0]:
if isinstance(atom, Literal) and self.push_type == atom.push_type and random() < self.rate:
new_atom = self._mutate_literal(atom)
else:
new_atom = atom
new_genome = new_genome.append(new_atom)
return new_genome
示例5: randomise
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import random [as 别名]
def randomise(self, value):
"""Randomise `value` with the mechanism.
Parameters
----------
value : int
The value to be randomised.
Returns
-------
int
The randomised value.
"""
self.check_inputs(value)
# Need to account for overlap of 0-value between distributions of different sign
unif_rv = random() - 0.5
unif_rv *= 1 + np.exp(self._scale)
sgn = -1 if unif_rv < 0 else 1
# Use formula for geometric distribution, with ratio of exp(-epsilon/sensitivity)
return int(np.round(value + sgn * np.floor(np.log(sgn * unif_rv) / self._scale)))
示例6: randomise
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import random [as 别名]
def randomise(self, value):
"""Randomise `value` with the mechanism.
Parameters
----------
value : str
The value to be randomised.
Returns
-------
str
The randomised value.
"""
self.check_inputs(value)
indicator = 0 if value == self._value0 else 1
unif_rv = random() * (np.exp(self._epsilon) + 1)
if unif_rv > np.exp(self._epsilon) + self._delta:
indicator = 1 - indicator
return self._value0 if indicator == 0 else self._value1
示例7: randomise
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import random [as 别名]
def randomise(self, value):
self.check_inputs(value)
if self._scale == 0:
return value
tau = 1 / (1 + np.floor(self._scale))
sigma2 = self._scale ** 2
while True:
geom_x = 0
while self._bernoulli_exp(tau):
geom_x += 1
bern_b = np.random.binomial(1, 0.5)
if bern_b and not geom_x:
continue
lap_y = int((1 - 2 * bern_b) * geom_x)
bern_c = self._bernoulli_exp((abs(lap_y) - tau * sigma2) ** 2 / 2 / sigma2)
if bern_c:
return value + lap_y
示例8: _bernoulli_exp
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import random [as 别名]
def _bernoulli_exp(self, gamma):
"""Sample from Bernoulli(exp(-gamma))
Adapted from Appendix A of https://arxiv.org/pdf/2004.00010.pdf
"""
if gamma > 1:
gamma_ceil = np.ceil(gamma)
for _ in np.arange(gamma_ceil):
if not self._bernoulli_exp(gamma / gamma_ceil):
return 0
return 1
counter = 1
while np.random.binomial(1, gamma / counter):
counter += 1
return counter % 2
示例9: randomise
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import random [as 别名]
def randomise(self, value):
"""Randomise `value` with the mechanism.
Parameters
----------
value : float
The value to be randomised.
Returns
-------
float
The randomised value.
"""
self.check_inputs(value)
scale = self._sensitivity / (self._epsilon - np.log(1 - self._delta))
unif_rv = random() - 0.5
return value - scale * np.sign(unif_rv) * np.log(1 - 2 * np.abs(unif_rv))
示例10: test_all_1d_norm_preserving
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import random [as 别名]
def test_all_1d_norm_preserving(self):
# verify that round-trip transforms are norm-preserving
x = random(30)
x_norm = np.linalg.norm(x)
n = x.size * 2
func_pairs = [(np.fft.fft, np.fft.ifft),
(np.fft.rfft, np.fft.irfft),
# hfft: order so the first function takes x.size samples
# (necessary for comparison to x_norm above)
(np.fft.ihfft, np.fft.hfft),
]
for forw, back in func_pairs:
for n in [x.size, 2*x.size]:
for norm in [None, 'ortho']:
tmp = forw(x, n=n, norm=norm)
tmp = back(tmp, n=n, norm=norm)
assert_array_almost_equal(x_norm,
np.linalg.norm(tmp))
示例11: test_get_standard_colors_random_seed
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import random [as 别名]
def test_get_standard_colors_random_seed(self):
# GH17525
df = DataFrame(np.zeros((10, 10)))
# Make sure that the random seed isn't reset by _get_standard_colors
plotting.parallel_coordinates(df, 0)
rand1 = random.random()
plotting.parallel_coordinates(df, 0)
rand2 = random.random()
assert rand1 != rand2
# Make sure it produces the same colors every time it's called
from pandas.plotting._style import _get_standard_colors
color1 = _get_standard_colors(1, color_type='random')
color2 = _get_standard_colors(1, color_type='random')
assert color1 == color2
示例12: test_get_standard_colors_no_appending
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import random [as 别名]
def test_get_standard_colors_no_appending(self):
# GH20726
# Make sure not to add more colors so that matplotlib can cycle
# correctly.
from matplotlib import cm
color_before = cm.gnuplot(range(5))
color_after = plotting._style._get_standard_colors(
1, color=color_before)
assert len(color_after) == len(color_before)
df = DataFrame(np.random.randn(48, 4), columns=list("ABCD"))
color_list = cm.gnuplot(np.linspace(0, 1, 16))
p = df.A.plot.bar(figsize=(16, 7), color=color_list)
assert (p.patches[1].get_facecolor()
== p.patches[17].get_facecolor())
示例13: connections
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import random [as 别名]
def connections(self,X,Y,F,A,R):
indsx,indsy = F.nonzero()
mask = indsx >= indsy
for i,j in zip(indsx[mask],indsy[mask]):
a = A[i,j]
d = R[i,j]
scales = random(GRAINS)*d
xp = X[i] - scales*cos(a)
yp = Y[i] - scales*sin(a)
r,g,b = self.colors[ (i*NUM+j) % self.n_colors ]
self.ctx.set_source_rgba(r,g,b,ALPHA)
for x,y in zip(xp,yp):
self.ctx.rectangle(x,y,ONE,ONE)
self.ctx.fill()
示例14: evaluate_cycle
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import random [as 别名]
def evaluate_cycle(self):
self.logger.debug('Full neighbors assignment for cycle %s : %s ',
self.cycle_count, self.current_cycle)
arg_min, min_cost = self.compute_best_value()
self.current_cycle[self.variable.name] = self.current_value
current_cost = assignment_cost(self.current_cycle, self.constraints)
self.logger.debug(
"Evaluate cycle %s: current cost %s - best cost %s",
self.cycle_count, current_cost, min_cost)
if current_cost - min_cost > 0 and 0.5 > random.random():
self.value_selection(arg_min)
self.logger.debug(
"Select new value %s for better cost %s ",
self.cycle_count, min_cost)
else:
self.logger.debug(
"Do not change value %s ", self.current_value)
self.new_cycle()
self.current_cycle, self.next_cycle = self.next_cycle, {}
self.post_to_all_neighbors(DsaMessage(self.current_value))
示例15: _get_glyph
# 需要导入模块: from numpy import random [as 别名]
# 或者: from numpy.random import random [as 别名]
def _get_glyph(gnum, height, width, shift_prob, shift_size):
if isinstance(gnum, list):
n = randint(*gnum)
else:
n = gnum
glyph = random_points_in_circle(
n, 0, 0, 0.5
)*array((width, height), 'float')
_spatial_sort(glyph)
if random()<shift_prob:
shift = ((-1)**randint(0,2))*shift_size*height
glyph[:,1] += shift
if random()<0.5:
ii = randint(0,n-1,size=(1))
xy = glyph[ii,:]
glyph = row_stack((glyph, xy))
return glyph