Python numpy.random.choice() Examples
The following are 30
code examples of numpy.random.choice().
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: __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 #2
Source File: VideoSource.py From mugen with MIT License | 6 votes |
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
Example #3
Source File: SourceSampler.py From mugen with MIT License | 6 votes |
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
Example #4
Source File: selection.py From pyshgp with MIT License | 6 votes |
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'))
Example #5
Source File: selection.py From pyshgp with MIT License | 6 votes |
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)
Example #6
Source File: ga.py From NiaPy with MIT License | 6 votes |
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)
Example #7
Source File: corrupter.py From KBGAN with MIT License | 6 votes |
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)
Example #8
Source File: train_svms.py From face-py-faster-rcnn with MIT License | 6 votes |
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)
Example #9
Source File: train_svms.py From faster-rcnn-resnet with MIT License | 6 votes |
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)
Example #10
Source File: maze.py From dal with MIT License | 6 votes |
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
Example #11
Source File: maze.py From dal with MIT License | 6 votes |
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
Example #12
Source File: ga.py From NiaPy with MIT License | 6 votes |
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)
Example #13
Source File: run_cifar.py From example_forgetting with MIT License | 5 votes |
def noisy(image, noise_percentage, noise_std): row, col, ch = image.shape num_corrupt = int(np.floor(noise_percentage * row * col / 100)) # Randomly choose pixels to add noise to xy_coords = np.random.choice(row * col, num_corrupt, replace=False) chan_coords = np.random.choice(ch, num_corrupt, replace=True) xy_coords = np.unravel_index(xy_coords, (row, col)) out = np.copy(image) mean = 120 # Add randomly generated Gaussian noise to pixels for coord in range(num_corrupt): noise = np.random.normal(mean, noise_std, 1) out[xy_coords[0][coord], xy_coords[1][coord], chan_coords[coord]] += noise return out # Train model for one epoch # # example_stats: dictionary containing statistics accumulated over every presentation of example #
Example #14
Source File: hetero_secureboosting_tree_host.py From FATE with Apache License 2.0 | 5 votes |
def sample_valid_features(self): LOGGER.info("sample valid features") if self.feature_num is None: self.feature_num = self.bin_split_points.shape[0] choose_feature = random.choice(range(0, self.feature_num), \ max(1, int(self.subsample_feature_rate * self.feature_num)), replace=False) valid_features = [False for i in range(self.feature_num)] for fid in choose_feature: valid_features[fid] = True return valid_features
Example #15
Source File: homo_secureboosting_client.py From FATE with Apache License 2.0 | 5 votes |
def sample_valid_feature(self): if self.feature_num is None: self.feature_num = self.bin_split_points.shape[0] chosen_feature = random.choice(range(0, self.feature_num), \ max(1, int(self.subsample_feature_rate * self.feature_num)), replace=False) valid_features = [False for i in range(self.feature_num)] for fid in chosen_feature: valid_features[fid] = True return valid_features
Example #16
Source File: homo_secureboosting_arbiter.py From FATE with Apache License 2.0 | 5 votes |
def sample_valid_feature(self): chosen_feature = random.choice(range(0, self.feature_num), max(1, int(self.subsample_feature_rate * self.feature_num)), replace=False) valid_features = [False for i in range(self.feature_num)] for fid in chosen_feature: valid_features[fid] = True return valid_features
Example #17
Source File: ctype_util.py From phillip with GNU General Public License v3.0 | 5 votes |
def randomValue(ctype): if issubclass(ctype, IntEnum): return random.choice(list(ctype)) if issubclass(ctype, Structure): obj = ctype() for name, type_ in ctype._fields: setattr(obj, name, randomValue(type_)) return obj # TODO: handle arrays raise TypeError("Unsupported type %s" % ctype) # TODO: fill out the rest of this table
Example #18
Source File: corrupter.py From KBGAN with MIT License | 5 votes |
def corrupt(self, src, rel, dst): prob = self.bern_prob[rel] selection = torch.bernoulli(prob).numpy().astype('int64') ent_random = choice(self.n_ent, len(src)) src_out = (1 - selection) * src.numpy() + selection * ent_random dst_out = selection * dst.numpy() + (1 - selection) * ent_random return torch.from_numpy(src_out), torch.from_numpy(dst_out)
Example #19
Source File: ac.py From phillip with GNU General Public License v3.0 | 5 votes |
def act(self, policy, verbose=False): action = random.choice(self.action_set, p=policy) return action, policy[action]
Example #20
Source File: minibatch.py From dpl with MIT License | 5 votes |
def _sample_rois(roidb, num_classes): """Generate a random sample of RoIs comprising foreground and background examples. """ # label = class RoI has max overlap with labels = roidb['labels'] rois = roidb['boxes'] num_rois = len(rois) keep_inds = npr.choice(num_rois, size=num_rois, replace=False) rois = rois[keep_inds] return labels, rois
Example #21
Source File: proposal_top_layer.py From tf_ctpn with MIT License | 5 votes |
def proposal_top_layer(rpn_cls_prob, rpn_bbox_pred, im_info, 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.reshape((-1, 4)) scores = scores.reshape((-1, 1)) length = scores.shape[0] if length < rpn_top_n: # Random selection, maybe unnecessary and loses good proposals # But such case rarely happens top_inds = npr.choice(length, size=rpn_top_n, replace=True) else: top_inds = scores.argsort(0)[::-1] top_inds = top_inds[:rpn_top_n] top_inds = top_inds.reshape(rpn_top_n, ) # Do the selection here anchors = anchors[top_inds, :] rpn_bbox_pred = rpn_bbox_pred[top_inds, :] scores = scores[top_inds] # 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 = np.zeros((proposals.shape[0], 1), dtype=np.float32) blob = np.hstack((batch_inds, proposals.astype(np.float32, copy=False))) return blob, scores
Example #22
Source File: Simulator.py From cortana-intelligence-inventory-optimization with MIT License | 5 votes |
def __define_brands_products(self): # definition of brands and products self.hierarchy['Brands'] = [] for BrandID in range(1, n_brands + 1): brand_dict = {} brand_dict['BrandID'] = str(BrandID) brand_dict['BrandName'] = 'Brand ' + brand_dict['BrandID'] brand_dict['Desirability'] = uniform(min_brand_desirability, max_brand_desirability) # definition of products of the given brand in the given store department brand_dict['Products'] = [] # For the time being, only one product per brand. This will change in the future product_dict = {} product_dict['ProductID'] = brand_dict['BrandID'] + '_1' product_dict['ProductName'] = brand_dict['BrandName'] + ' Product ' + product_dict['ProductID'] product_dict['ProductVolume'] = uniform(min_product_volume, max_product_volume) product_dict['MSRP'] = 0 # will be updated later on, based on the purchase cost if BrandID <= n_brands/2 or choice([-1,1]) == 1: # first half of the brands have perishable products # some brands in the second half also have perishable products product_dict['ShelfLife'] = str(random_integers(min_shelf_life, max_shelf_life)) + ' days' else: product_dict['ShelfLife'] = '10000 days' brand_dict['Products'].append(product_dict) self.hierarchy['Brands'].append(brand_dict) # definitions of suppliers
Example #23
Source File: hetero_secureboosting_tree_guest.py From FATE with Apache License 2.0 | 5 votes |
def sample_valid_features(self): LOGGER.info("sample valid features") if self.feature_num is None: self.feature_num = self.bin_split_points.shape[0] choose_feature = random.choice(range(0, self.feature_num), \ max(1, int(self.subsample_feature_rate * self.feature_num)), replace=False) valid_features = [False for i in range(self.feature_num)] for fid in choose_feature: valid_features[fid] = True return valid_features
Example #24
Source File: proposal_top_layer.py From RGB-N with MIT License | 5 votes |
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 im_info = im_info[0] scores = rpn_cls_prob[:, :, :, num_anchors:] rpn_bbox_pred = rpn_bbox_pred.reshape((-1, 4)) scores = scores.reshape((-1, 1)) length = scores.shape[0] if length < rpn_top_n: # Random selection, maybe unnecessary and loses good proposals # But such case rarely happens top_inds = npr.choice(length, size=rpn_top_n, replace=True) else: top_inds = scores.argsort(0)[::-1] top_inds = top_inds[:rpn_top_n] top_inds = top_inds.reshape(rpn_top_n, ) # Do the selection here anchors = anchors[top_inds, :] rpn_bbox_pred = rpn_bbox_pred[top_inds, :] scores = scores[top_inds] # 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 = np.zeros((proposals.shape[0], 1), dtype=np.float32) blob = np.hstack((batch_inds, proposals.astype(np.float32, copy=False))) return blob, scores
Example #25
Source File: ccc.py From VideoDigitalWatermarking with MIT License | 5 votes |
def generateCCC(N): u"""Create CCC. @param N : CCC size @return CCC : CCC(N,N,N**2) """ #対角成分 random.seed(N) r = np.array(random.choice([1,-1],N)) if sum(r) == N or sum(r) == -N: sys.stderr.write('ERROR: invalid seed number.') sys.exit(-1) #アダマール行列を生成 H = np.array([[(-1)**bin(i&j).count('1') for i in np.arange(N)] for j in np.arange(N)]) #CCCを生成 CCC = np.empty((N,N,N*N)) A = np.dot(H,diag(r)) B = np.dot(diag(r),H) for i in np.arange(N): for j in np.arange(N): for k in np.arange(N): a = A[i,k] for l in np.arange(N): CCC[i,j,N*k+l] = a*H[k,l]*B[j,l] return CCC #test #ccc = generateCCC(2) #print(ccc)
Example #26
Source File: logo.py From viznet with MIT License | 5 votes |
def logo3(): viznet.setting.node_setting['inner_lw'] = 0 viznet.setting.node_setting['lw'] = 0 npoint = 60 nedge = 50 angle = random(npoint)*2*np.pi #r = np.exp(randn(npoint)*0.4) r = np.sqrt(randn(npoint)) xy = np.array([r*np.cos(angle), r*np.sin(angle)]).T #xy = randn(npoint, 2)*0.5 with viznet.DynamicShow(figsize=(4,4), filename='_logo3.png') as ds: #body = viznet.NodeBrush('tn.mps', size='huge', color='#AACCFF') >> (0, 0) dot = viznet.NodeBrush('tn.mps', size='tiny') node_list = [] for i, p in enumerate(xy): dot.color = random(3)*0.5+0.5 dot.zorder = 100+i*2 dot.size = 0.05+0.08*random() node_list.append(dot >> p) dis_mat = np.linalg.norm(xy-xy[:,None,:], axis=-1) tree = minimum_spanning_tree(dis_mat).tocoo() for i, j in zip(tree.row, tree.col): n1,n2=node_list[i],node_list[j] viznet.EdgeBrush(choice(['.>.', '.>.']), lw=1, color=random([3])*0.4, zorder=(n1.obj.zorder+n2.obj.zorder)/2) >> (n1,n2) #for i in range(nedge): # n1, n2 =choice(node_list),choice(node_list) # viznet.EdgeBrush(choice(['.>.', '->-']), lw=1, color=random([3])*0.4, zorder=(n1.obj.zorder+n2.obj.zorder)/2) >> (n1,n2)
Example #27
Source File: fcl.py From dimod with Apache License 2.0 | 5 votes |
def _random_cycle(adj, random_state): """Find a cycle using a random graph walk.""" # step through idx values in adj to pick a random one, random.choice does not work on dicts n = random_state.randint(len(adj)) for idx, v in enumerate(adj): if idx == n: break start = v walk = [start] visited = {start: 0} while True: if len(walk) > 1: # as long as we don't step back one we won't have any repeated edges previous = walk[-2] neighbors = [u for u in adj[walk[-1]] if u != previous] else: neighbors = list(adj[walk[-1]]) if not neighbors: # we've walked into a dead end return None # get a random neighbor u = random_state.choice(neighbors) if u in visited: # if we've seen this neighbour, then we have a cycle starting from it return walk[visited[u]:] else: # add to walk and keep moving walk.append(u) visited[u] = len(visited)
Example #28
Source File: ctype_util.py From gym-dolphin with MIT License | 5 votes |
def randomValue(ctype): if issubclass(ctype, IntEnum): return random.choice(list(ctype)) if issubclass(ctype, Structure): obj = ctype() for name, type_ in ctype._fields: setattr(obj, name, randomValue(type_)) return obj # TODO: handle arrays raise TypeError("Unsupported type %s" % ctype)
Example #29
Source File: proposal_top_layer.py From densecap-tensorflow with MIT License | 5 votes |
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.reshape((-1, 4)) scores = scores.reshape((-1, 1)) length = scores.shape[0] if length < rpn_top_n: # Random selection, maybe unnecessary and loses good proposals # But such case rarely happens top_inds = npr.choice(length, size=rpn_top_n, replace=True) else: top_inds = scores.argsort(0)[::-1] top_inds = top_inds[:rpn_top_n] top_inds = top_inds.reshape(rpn_top_n, ) # Do the selection here anchors = anchors[top_inds, :] rpn_bbox_pred = rpn_bbox_pred[top_inds, :] scores = scores[top_inds] # 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 = np.zeros((proposals.shape[0], 1), dtype=np.float32) blob = np.hstack((batch_inds, proposals.astype(np.float32, copy=False))) return blob, scores
Example #30
Source File: __init__.py From BiblioPixelAnimations with MIT License | 5 votes |
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