當前位置: 首頁>>代碼示例>>Python>>正文


Python random.choice方法代碼示例

本文整理匯總了Python中numpy.random.choice方法的典型用法代碼示例。如果您正苦於以下問題:Python random.choice方法的具體用法?Python random.choice怎麽用?Python random.choice使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在numpy.random的用法示例。


在下文中一共展示了random.choice方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: start_new_particles

# 需要導入模塊: from numpy import random [as 別名]
# 或者: from numpy.random import choice [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 
開發者ID:ManiacalLabs,項目名稱:BiblioPixelAnimations,代碼行數:22,代碼來源:__init__.py

示例2: select_one

# 需要導入模塊: from numpy import random [as 別名]
# 或者: from numpy.random import choice [as 別名]
def select_one(self, population: Population) -> Individual:
        """Return single individual from population.

        Parameters
        ----------
        population
            A Population of Individuals.

        Returns
        -------
        Individual
            The selected Individual.

        """
        tournament = choice(population, self.tournament_size, replace=False)
        return min(tournament, key=attrgetter('total_error')) 
開發者ID:erp12,項目名稱:pyshgp,代碼行數:18,代碼來源:selection.py

示例3: _select_with_stream

# 需要導入模塊: from numpy import random [as 別名]
# 或者: from numpy.random import choice [as 別名]
def _select_with_stream(self, population: Population, cases: CaseStream) -> Individual:
        candidates = one_individual_per_error_vector(population)

        ep = self.epsilon
        if isinstance(ep, bool) and ep:
            ep = self._epsilon_from_mad(population.all_error_vectors())

        for case in cases:
            if len(candidates) <= 1:
                break

            errors_this_case = [i.error_vector[case] for i in candidates]
            best_val_for_case = min(errors_this_case)

            max_error = best_val_for_case
            if isinstance(ep, np.ndarray):
                max_error += ep[case]
            elif isinstance(ep, (float, int, np.int64, np.float64)):
                max_error += ep

            candidates = [i for i in candidates if i.error_vector[case] <= max_error]
        return choice(candidates) 
開發者ID:erp12,項目名稱:pyshgp,代碼行數:24,代碼來源:selection.py

示例4: TwoPointCrossover

# 需要導入模塊: from numpy import random [as 別名]
# 或者: from numpy.random import choice [as 別名]
def TwoPointCrossover(pop, ic, cr, rnd=rand):
	r"""Two point crossover method.

	Args:
		pop (numpy.ndarray[Individual]): Current population.
		ic (int): Index of current individual.
		cr (float): Crossover probability.
		rnd (mtrand.RandomState): Random generator.

	Returns:
		numpy.ndarray: New genotype.
	"""
	io = ic
	while io != ic: io = rnd.randint(len(pop))
	r = sort(rnd.choice(len(pop[ic]), 2))
	x = pop[ic].x
	x[r[0]:r[1]] = pop[io].x[r[0]:r[1]]
	return asarray(x) 
開發者ID:NiaOrg,項目名稱:NiaPy,代碼行數:20,代碼來源:ga.py

示例5: MultiPointCrossover

# 需要導入模塊: from numpy import random [as 別名]
# 或者: from numpy.random import choice [as 別名]
def MultiPointCrossover(pop, ic, n, rnd=rand):
	r"""Multi point crossover method.

	Args:
		pop (numpy.ndarray[Individual]): Current population.
		ic (int): Index of current individual.
		n (flat): TODO.
		rnd (mtrand.RandomState): Random generator.

	Returns:
		numpy.ndarray: New genotype.
	"""
	io = ic
	while io != ic: io = rnd.randint(len(pop))
	r, x = sort(rnd.choice(len(pop[ic]), 2 * n)), pop[ic].x
	for i in range(n): x[r[2 * i]:r[2 * i + 1]] = pop[io].x[r[2 * i]:r[2 * i + 1]]
	return asarray(x) 
開發者ID:NiaOrg,項目名稱:NiaPy,代碼行數:19,代碼來源:ga.py

示例6: sample

# 需要導入模塊: from numpy import random [as 別名]
# 或者: from numpy.random import choice [as 別名]
def sample(self, duration: float) -> VideoSegment:
        """
        Randomly samples a video segment with the specified duration.

        Parameters
        ----------
        duration
            duration of the video segment to sample
        """
        if self.time_boundaries:
            # Select a random time boundary to sample from, weighted by duration
            time_ranges = [TimeRange(*boundary) for boundary in self.time_boundaries]
            time_ranges = [time_range for time_range in time_ranges if time_range.duration >= duration]
            total_duration = sum([time_range.duration for time_range in time_ranges])
            time_range_weights = [time_range.duration / total_duration for time_range in time_ranges]
            time_range_to_sample = time_ranges[choice(len(time_ranges), p=time_range_weights)]
        else:
            time_range_to_sample = TimeRange(0, self.segment.duration)

        start_time = random.uniform(time_range_to_sample.start, time_range_to_sample.end - duration)
        sampled_clip = self.segment.subclip(start_time, start_time + duration)

        return sampled_clip 
開發者ID:scherroman,項目名稱:mugen,代碼行數:25,代碼來源:VideoSource.py

示例7: sample

# 需要導入模塊: from numpy import random [as 別名]
# 或者: from numpy.random import choice [as 別名]
def sample(self, duration: float) -> Segment:
        """
        Randomly samples a segment with the specified duration
        
        Parameters
        ----------
        duration
            duration of the sample

        Returns
        -------
        A randomly sampled segment with the specified duration
        """
        selected_source = choice(self.sources, p=self.sources.normalized_weights)
        sample = selected_source.sample(duration)

        return sample 
開發者ID:scherroman,項目名稱:mugen,代碼行數:19,代碼來源:SourceSampler.py

示例8: corrupt

# 需要導入模塊: from numpy import random [as 別名]
# 或者: from numpy.random import choice [as 別名]
def corrupt(self, src, rel, dst, keep_truth=True):
        n = len(src)
        prob = self.bern_prob[rel]
        selection = torch.bernoulli(prob).numpy().astype('bool')
        src_out = np.tile(src.numpy(), (self.n_sample, 1)).transpose()
        dst_out = np.tile(dst.numpy(), (self.n_sample, 1)).transpose()
        rel_out = rel.unsqueeze(1).expand(n, self.n_sample)
        if keep_truth:
            ent_random = choice(self.n_ent, (n, self.n_sample - 1))
            src_out[selection, 1:] = ent_random[selection]
            dst_out[~selection, 1:] = ent_random[~selection]
        else:
            ent_random = choice(self.n_ent, (n, self.n_sample))
            src_out[selection, :] = ent_random[selection]
            dst_out[~selection, :] = ent_random[~selection]
        return torch.from_numpy(src_out), rel_out, torch.from_numpy(dst_out) 
開發者ID:cai-lw,項目名稱:KBGAN,代碼行數:18,代碼來源:corrupter.py

示例9: _get_feature_scale

# 需要導入模塊: from numpy import random [as 別名]
# 或者: from numpy.random import choice [as 別名]
def _get_feature_scale(self, num_images=100):
        TARGET_NORM = 20.0 # Magic value from traditional R-CNN
        _t = Timer()
        roidb = self.imdb.roidb
        total_norm = 0.0
        count = 0.0
        inds = npr.choice(xrange(self.imdb.num_images), size=num_images,
                          replace=False)
        for i_, i in enumerate(inds):
            im = cv2.imread(self.imdb.image_path_at(i))
            if roidb[i]['flipped']:
                im = im[:, ::-1, :]
            _t.tic()
            scores, boxes = im_detect(self.net, im, roidb[i]['boxes'])
            _t.toc()
            feat = self.net.blobs[self.layer].data
            total_norm += np.sqrt((feat ** 2).sum(axis=1)).sum()
            count += feat.shape[0]
            print('{}/{}: avg feature norm: {:.3f}'.format(i_ + 1, num_images,
                                                           total_norm / count))

        return TARGET_NORM * 1.0 / (total_norm / count) 
開發者ID:playerkk,項目名稱:face-py-faster-rcnn,代碼行數:24,代碼來源:train_svms.py

示例10: generate_map

# 需要導入模塊: from numpy import random [as 別名]
# 或者: from numpy.random import choice [as 別名]
def generate_map(map_size, num_cells_togo, save_boundary=True, min_blocks = 10):
    
    maze=generate_maze(map_size)

    if save_boundary:
        maze = maze[1:-1, 1:-1]
        map_size -= 2

    index_ones = np.arange(map_size*map_size)[maze.flatten()==1]

    reserve = min(index_ones.size, min_blocks)    
    num_cells_togo = min(num_cells_togo, index_ones.size-reserve)

    if num_cells_togo > 0:
        blocks_remove=npr.choice(index_ones, num_cells_togo, replace = False)
        maze[blocks_remove//map_size, blocks_remove%map_size] = 0

    if save_boundary:
        map_size+=2
        maze2 = np.ones((map_size,map_size))
        maze2[1:-1,1:-1] = maze
        return maze2
    else:
        return maze 
開發者ID:montrealrobotics,項目名稱:dal,代碼行數:26,代碼來源:maze.py

示例11: proposal_top_layer

# 需要導入模塊: from numpy import random [as 別名]
# 或者: from numpy.random import choice [as 別名]
def proposal_top_layer(rpn_cls_prob, rpn_bbox_pred, im_info, _feat_stride, anchors, num_anchors):
  """A layer that just selects the top region proposals
     without using non-maximal suppression,
     For details please see the technical report
  """
  rpn_top_n = cfg.TEST.RPN_TOP_N

  scores = rpn_cls_prob[:, :, :, num_anchors:]

  rpn_bbox_pred = rpn_bbox_pred.view(-1, 4)
  scores = scores.contiguous().view(-1, 1)

  length = scores.size(0)
  if length < rpn_top_n:
    # Random selection, maybe unnecessary and loses good proposals
    # But such case rarely happens
    top_inds = torch.from_numpy(npr.choice(length, size=rpn_top_n, replace=True)).long().cuda()
  else:
    top_inds = scores.sort(0, descending=True)[1]
    top_inds = top_inds[:rpn_top_n]
    top_inds = top_inds.view(rpn_top_n)

  # Do the selection here
  anchors = anchors[top_inds, :].contiguous()
  rpn_bbox_pred = rpn_bbox_pred[top_inds, :].contiguous()
  scores = scores[top_inds].contiguous()

  # Convert anchors into proposals via bbox transformations
  proposals = bbox_transform_inv(anchors, rpn_bbox_pred)

  # Clip predicted boxes to image
  proposals = clip_boxes(proposals, im_info[:2])

  # Output rois blob
  # Our RPN implementation only supports a single input image, so all
  # batch inds are 0
  batch_inds = proposals.data.new(proposals.size(0), 1).zero_()
  blob = torch.cat([batch_inds, proposals], 1)
  return blob, scores 
開發者ID:Sunarker,項目名稱:Collaborative-Learning-for-Weakly-Supervised-Object-Detection,代碼行數:41,代碼來源:proposal_top_layer.py

示例12: move_particles

# 需要導入模塊: from numpy import random [as 別名]
# 或者: from numpy.random import choice [as 別名]
def move_particles(self):
        """
        Move each particle by it's velocity, adjusting brightness as we go.
        Particles that have moved beyond their range (steps to live), and
        those that move off the ends and are not wrapped get sacked.
        Particles can stay between _end and up to but not including _end+1
        No particles can exitst before start without wrapping.
        """
        moved_particles = []
        for vel, pos, stl, color, bright in self.particles:

            stl -= 1    # steps to live
            if stl > 0:

                pos = pos + vel
                if vel > 0:
                    if pos >= (self._end + 1):
                        if self.wrap:
                            pos = pos - (self._end + 1) + self._start
                        else:
                            continue  # Sacked
                else:
                    if pos < self._start:
                        if self.wrap:
                            pos = pos + self._end + 1 + self._start
                        else:
                            continue  # Sacked

                if random.random() < self.step_flare_prob:
                    bright = 255
                else:
                    bright = bright + random.choice(self.bd)
                    if bright > 255:
                        bright = 255
                    # Zombie particles with bright<=0 walk, don't -overflow
                    if bright < -10000:
                        bright = -10000

                moved_particles.append((vel, pos, stl, color, bright))

        self.particles = moved_particles 
開發者ID:ManiacalLabs,項目名稱:BiblioPixelAnimations,代碼行數:43,代碼來源:__init__.py

示例13: fill_up_genomes

# 需要導入模塊: from numpy import random [as 別名]
# 或者: from numpy.random import choice [as 別名]
def fill_up_genomes(otu_genome_map, unmatched_otus, per_rank_map, tax_profile, debug):
    genomes = {}
    added_genomes = set()
    for rank in per_rank_map:
        for taxid in per_rank_map[rank]:
            genomes[taxid] = []
            for path, genome_id in per_rank_map[rank][taxid]:
                if path not in added_genomes:
                    genomes[taxid].append((path, genome_id))
                    added_genomes.add(path)
    otu_indices = np_rand.choice(len(unmatched_otus),len(unmatched_otus),replace=False)
    i = 0
    set_all = False
    for tax_id in genomes:
        for path, genome_id in genomes[tax_id]:
            curr_otu = unmatched_otus[otu_indices[i]] #so we choose a random genome
            lineage, abundances = tax_profile[curr_otu]
            lin = transform_lineage(lineage, RANKS, MAX_RANK)
            otu_genome_map[curr_otu] = (tax_id, genome_id, path, abundances)
            if debug:
                _log.warning("Filling up OTU %s (mapped tax id: %s) to genome with tax id %s" % (curr_otu, lin[0], tax_id))
            i += 1
            if (i >= len(unmatched_otus) or i >= len(added_genomes)):
                set_all = True
                break
        if (set_all):
            break
    return otu_genome_map 
開發者ID:CAMI-challenge,項目名稱:CAMISIM,代碼行數:30,代碼來源:get_genomes.py

示例14: _compute_vectorized

# 需要導入模塊: from numpy import random [as 別名]
# 或者: from numpy.random import choice [as 別名]
def _compute_vectorized(self, args, y):

        random_values = choice(self.a, args.index.shape[0])
        random_values = random_values.astype(self.dtype)

        return random_values 
開發者ID:J535D165,項目名稱:recordlinkage,代碼行數:8,代碼來源:random.py

示例15: random_value_selection

# 需要導入模塊: from numpy import random [as 別名]
# 或者: from numpy.random import choice [as 別名]
def random_value_selection(self):
        """
        Select a random value from the domain of the variable of the
        VariableComputation.

        """
        value = random.choice(self.variable.domain)
        self.value_selection(value) 
開發者ID:Orange-OpenSource,項目名稱:pyDcop,代碼行數:10,代碼來源:computations.py


注:本文中的numpy.random.choice方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。