Python numpy.random.random() Examples
The following are 30
code examples of numpy.random.random().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
numpy.random
, or try the search function
.
Example #1
Source File: test_misc.py From recruit with Apache License 2.0 | 6 votes |
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())
Example #2
Source File: dsa-tuto.py From pyDcop with BSD 3-Clause "New" or "Revised" License | 6 votes |
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))
Example #3
Source File: test_fftpack.py From recruit with Apache License 2.0 | 6 votes |
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))
Example #4
Source File: test_misc.py From recruit with Apache License 2.0 | 6 votes |
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
Example #5
Source File: laplace.py From differential-privacy-library with MIT License | 6 votes |
def randomise(self, value): self.check_inputs(value) if self._scale is None: self._scale = self._find_scale() value = min(value, self._upper_bound) value = max(value, self._lower_bound) unif_rv = random() unif_rv *= self._cdf(self._upper_bound - value) - self._cdf(self._lower_bound - value) unif_rv += self._cdf(self._lower_bound - value) unif_rv -= 0.5 unif_rv = min(unif_rv, 0.5 - 1e-10) return value - self._scale * np.sign(unif_rv) * np.log(1 - 2 * np.abs(unif_rv))
Example #6
Source File: laplace.py From differential-privacy-library with MIT License | 6 votes |
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))
Example #7
Source File: gaussian.py From differential-privacy-library with MIT License | 6 votes |
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
Example #8
Source File: gaussian.py From differential-privacy-library with MIT License | 6 votes |
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
Example #9
Source File: binary.py From differential-privacy-library with MIT License | 6 votes |
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
Example #10
Source File: glyphs.py From sand-glyphs with MIT License | 6 votes |
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
Example #11
Source File: geometric.py From differential-privacy-library with MIT License | 6 votes |
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)))
Example #12
Source File: orbitals.py From orbitals with MIT License | 6 votes |
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()
Example #13
Source File: variation.py From pyshgp with MIT License | 6 votes |
def produce(self, parents: Sequence[Genome], spawner: GeneSpawner) -> 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 gene in parents[0]: if random() < self.rate: new_genome = new_genome.append(spawner.random_gene()) new_genome = new_genome.append(gene) return new_genome # Recombinations
Example #14
Source File: variation.py From pyshgp with MIT License | 6 votes |
def produce(self, parents: Sequence[Genome], spawner: GeneSpawner) -> 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 gene in parents[0]: if random() < self.rate: continue new_genome = new_genome.append(gene) return new_genome
Example #15
Source File: variation.py From pyshgp with MIT License | 6 votes |
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
Example #16
Source File: variation.py From pyshgp with MIT License | 6 votes |
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.
Example #17
Source File: selection.py From pyshgp with MIT License | 6 votes |
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]
Example #18
Source File: __init__.py From BiblioPixelAnimations with MIT License | 6 votes |
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
Example #19
Source File: utils.py From sand-glyphs with MIT License | 6 votes |
def random_points_in_circle(n,xx,yy,rr): """ get n random points in a circle. """ rnd = random(size=(n,3)) t = TWOPI*rnd[:,0] u = rnd[:,1:].sum(axis=1) r = zeros(n,'float') mask = u>1. xmask = logical_not(mask) r[mask] = 2.-u[mask] r[xmask] = u[xmask] xyp = reshape(rr*r,(n,1))*column_stack( (cos(t),sin(t)) ) dartsxy = xyp + array([xx,yy]) return dartsxy
Example #20
Source File: generate.py From metal with Apache License 2.0 | 5 votes |
def _generate_params(self, theta_range, theta_edge_range): self.theta = defaultdict(float) for i in range(self.m): t_min, t_max = min(theta_range), max(theta_range) self.theta[i] = (t_max - t_min) * random(self.k + 1) + t_min # Choose random weights for the edges te_min, te_max = min(theta_edge_range), max(theta_edge_range) for (i, j) in self.E: w_ij = (te_max - te_min) * random() + te_min self.theta[(i, j)] = w_ij self.theta[(j, i)] = w_ij
Example #21
Source File: test_fftpack.py From lambda-packs with MIT License | 5 votes |
def test_fftn(self): x = random((30, 20, 10)) + 1j*random((30, 20, 10)) assert_array_almost_equal( np.fft.fft(np.fft.fft(np.fft.fft(x, axis=2), axis=1), axis=0), np.fft.fftn(x)) assert_array_almost_equal(np.fft.fftn(x) / np.sqrt(30 * 20 * 10), np.fft.fftn(x, norm="ortho"))
Example #22
Source File: generate.py From metal with Apache License 2.0 | 5 votes |
def gaussian_bags_of_words(Y, vocab=vocab1k, sigma=1, bag_size=[25, 50], **kwargs): """ Generate Gaussian bags of words based on label assignments Args: Y: np.array of true labels sigma: (float) the standard deviation of the Gaussian distributions bag_size: (list) the min and max length of bags of words Returns: X: (Tensor) a tensor of indices representing tokens D: (list) a list of sentences (strings) The sentences are conditionally independent, given a label. Note that technically we use a half-normal distribution here because we take the absolute value of the normal distribution. Example: TBD """ def make_distribution(sigma, num_words): p = abs(np.random.normal(0, sigma, num_words)) return p / sum(p) num_words = len(vocab) word_dists = {y: make_distribution(sigma, num_words) for y in set(Y)} bag_sizes = np.random.choice(range(min(bag_size), max(bag_size)), len(Y)) X = [] items = [] for i, (y, length) in enumerate(zip(Y, bag_sizes)): x = torch.from_numpy(np.random.choice(num_words, length, p=word_dists[y])) X.append(x) items.append(" ".join(vocab[j] for j in x)) return X, items
Example #23
Source File: test_fftpack.py From lambda-packs with MIT License | 5 votes |
def test_fft(self): x = random(30) + 1j*random(30) assert_array_almost_equal(fft1(x), np.fft.fft(x)) assert_array_almost_equal(fft1(x) / np.sqrt(30), np.fft.fft(x, norm="ortho"))
Example #24
Source File: test_fftpack.py From lambda-packs with MIT License | 5 votes |
def test_ifft2(self): x = random((30, 20)) + 1j*random((30, 20)) assert_array_almost_equal(np.fft.ifft(np.fft.ifft(x, axis=1), axis=0), np.fft.ifft2(x)) assert_array_almost_equal(np.fft.ifft2(x) * np.sqrt(30 * 20), np.fft.ifft2(x, norm="ortho"))
Example #25
Source File: test_fftpack.py From lambda-packs with MIT License | 5 votes |
def test_rfftn(self): x = random((30, 20, 10)) assert_array_almost_equal(np.fft.fftn(x)[:, :, :6], np.fft.rfftn(x)) assert_array_almost_equal(np.fft.rfftn(x) / np.sqrt(30 * 20 * 10), np.fft.rfftn(x, norm="ortho"))
Example #26
Source File: test_fftpack.py From lambda-packs with MIT License | 5 votes |
def test_ifft(self): x = random(30) + 1j*random(30) assert_array_almost_equal(x, np.fft.ifft(np.fft.fft(x))) assert_array_almost_equal( x, np.fft.ifft(np.fft.fft(x, norm="ortho"), norm="ortho"))
Example #27
Source File: test_fftpack.py From lambda-packs with MIT License | 5 votes |
def test_irfft(self): x = random(30) assert_array_almost_equal(x, np.fft.irfft(np.fft.rfft(x))) assert_array_almost_equal( x, np.fft.irfft(np.fft.rfft(x, norm="ortho"), norm="ortho"))
Example #28
Source File: test_fftpack.py From lambda-packs with MIT License | 5 votes |
def test_rfft2(self): x = random((30, 20)) assert_array_almost_equal(np.fft.fft2(x)[:, :11], np.fft.rfft2(x)) assert_array_almost_equal(np.fft.rfft2(x) / np.sqrt(30 * 20), np.fft.rfft2(x, norm="ortho"))
Example #29
Source File: test_fftpack.py From lambda-packs with MIT License | 5 votes |
def test_irfft2(self): x = random((30, 20)) assert_array_almost_equal(x, np.fft.irfft2(np.fft.rfft2(x))) assert_array_almost_equal( x, np.fft.irfft2(np.fft.rfft2(x, norm="ortho"), norm="ortho"))
Example #30
Source File: test_fftpack.py From auto-alt-text-lambda-api with MIT License | 5 votes |
def test_rfft(self): x = random(30) assert_array_almost_equal(np.fft.fft(x)[:16], np.fft.rfft(x)) assert_array_almost_equal(np.fft.rfft(x) / np.sqrt(30), np.fft.rfft(x, norm="ortho"))