Python numpy.amin() Examples
The following are 30
code examples of numpy.amin().
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
, or try the search function
.
Example #1
Source File: utils.py From tf2-yolo3 with Apache License 2.0 | 8 votes |
def draw_outputs(img, outputs, class_names=None): boxes, objectness, classes = outputs #boxes, objectness, classes = boxes[0], objectness[0], classes[0] wh = np.flip(img.shape[0:2]) if img.ndim == 2 or img.shape[2] == 1: img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) min_wh = np.amin(wh) if min_wh <= 100: font_size = 0.5 else: font_size = 1 for i in range(classes.shape[0]): x1y1 = tuple((np.array(boxes[i][0:2]) * wh).astype(np.int32)) x2y2 = tuple((np.array(boxes[i][2:4]) * wh).astype(np.int32)) img = cv2.rectangle(img, x1y1, x2y2, (255, 0, 0), 1) img = cv2.putText(img, '{}'.format(int(classes[i])), x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, font_size, (0, 0, 255), 1) return img
Example #2
Source File: utils.py From tf2-yolo3 with Apache License 2.0 | 8 votes |
def draw_labels(x, y, class_names=None): img = x.numpy() if img.ndim == 2 or img.shape[2] == 1: img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) boxes, classes = tf.split(y, (4, 1), axis=-1) classes = classes[..., 0] wh = np.flip(img.shape[0:2]) min_wh = np.amin(wh) if min_wh <= 100: font_size = 0.5 else: font_size = 1 for i in range(len(boxes)): x1y1 = tuple((np.array(boxes[i][0:2]) * wh).astype(np.int32)) x2y2 = tuple((np.array(boxes[i][2:4]) * wh).astype(np.int32)) img = cv2.rectangle(img, x1y1, x2y2, (255, 0, 0), 1) if class_names: img = cv2.putText(img, class_names[classes[i]], x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, font_size, (0, 0, 255), 1) else: img = cv2.putText(img, str(classes[i]), x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1) return img
Example #3
Source File: benchmark_functions.py From phoenics with Apache License 2.0 | 6 votes |
def discrete_michalewicz(vector): vector = np.array(vector) vector = 100 * vector - 40 bounds = [1.0, 2.0, 3.0, 4.0, 5.0] bounds = np.array(bounds)**2 result = 5 for bound in bounds[::-1]: if np.amax(np.abs(vector)) < bound: result -= 1 bounds = [1.25, 2.0, 2.5, 3.0] bounds = np.array(bounds)**2 new_res = 5 for bound in bounds[::-1]: if np.amin(np.abs(vector)) < bound: new_res -= 1 result = np.amin([result, new_res, 4]) return result
Example #4
Source File: gather_encoder_test.py From model-optimization with Apache License 2.0 | 6 votes |
def test_state_aggregation_modes(self): """Tests that all state updates tensors can be aggregated.""" x_fn = lambda: tf.random.uniform((5,)) encoder = gather_encoder.GatherEncoder.from_encoder( core_encoder.EncoderComposer( test_utils.StateUpdateTensorsEncodingStage()).make(), tf.TensorSpec.from_tensor(x_fn())) iteration = _make_iteration_function(encoder, x_fn, 3) data = self.evaluate(iteration(encoder.initial_state())) expected_sum = np.sum(data.x) expected_min = np.amin(data.x) expected_max = np.amax(data.x) expected_stack_values = 15 # 3 values of shape 5. expected_state = [ expected_sum, expected_min, expected_max, expected_stack_values ] # We are not in control of ordering of the elements in state tuple. self.assertAllClose(sorted(expected_state), sorted(data.updated_state))
Example #5
Source File: hierarchies.py From phoenics with Apache License 2.0 | 6 votes |
def rescale_losses(self, losses): for index in range(losses.shape[1]): min_loss, max_loss = np.amin(losses[:, index]), np.amax(losses[:, index]) losses[:, index] = (losses[:, index] - min_loss) / (max_loss - min_loss) losses = np.where(np.isnan(losses), 0., losses) # print(losses.shape) # quit() self.unscaled_losses = losses.transpose() self._build_tolerances() self._construct_objective() return self.loss.transpose() #========================================================================
Example #6
Source File: multigoal_env.py From pytorchrl with MIT License | 6 votes |
def step(self, action): action = action.ravel() a_lb, a_ub = self.action_space.bounds action = np.clip(action, a_lb, a_ub).ravel() next_obs = self.dynamics.forward(self.observation, action) o_lb, o_ub = self.observation_space.bounds next_obs = np.clip(next_obs, o_lb, o_ub) reward = self.compute_reward(self.observation, action) cur_position = self.observation dist_to_goal = np.amin([ np.linalg.norm(cur_position - goal_position) for goal_position in self.goal_positions ]) done = dist_to_goal < self.goal_threshold if done: reward += self.goal_reward self.observation = np.copy(next_obs) return next_obs, reward, done, {'pos': next_obs}
Example #7
Source File: multigoal_env.py From pytorchrl with MIT License | 6 votes |
def compute_reward(self, observation, action): # penalize the L2 norm of acceleration # noinspection PyTypeChecker action_cost = np.sum(action ** 2) * self.action_cost_coeff # penalize squared dist to goal cur_position = observation # noinspection PyTypeChecker goal_cost = np.amin([ np.sum((cur_position - goal_position) ** 2) for goal_position in self.goal_positions ]) # penalize staying with the log barriers costs = [action_cost, goal_cost] reward = -np.sum(costs) return reward
Example #8
Source File: multigoal_env.py From pytorchrl with MIT License | 6 votes |
def plot_position_cost(self, ax): delta = 0.01 x_min, x_max = tuple(1.1 * np.array(self.xlim)) y_min, y_max = tuple(1.1 * np.array(self.ylim)) X, Y = np.meshgrid( np.arange(x_min, x_max, delta), np.arange(y_min, y_max, delta) ) goal_costs = np.amin([ (X - goal_x) ** 2 + (Y - goal_y) ** 2 for goal_x, goal_y in self.goal_positions ], axis=0) costs = goal_costs contours = ax.contour(X, Y, costs, 20) ax.clabel(contours, inline=1, fontsize=10, fmt='%.0f') ax.set_xlim([x_min, x_max]) ax.set_ylim([y_min, y_max]) goal = ax.plot(self.goal_positions[:, 0], self.goal_positions[:, 1], 'ro') return [contours, goal]
Example #9
Source File: sanity_check.py From pytim with GNU General Public License v3.0 | 6 votes |
def assign_mesh(self, mesh): interface = self.interface box = interface.universe.dimensions[:3] interface.target_mesh = mesh if not isinstance(interface.target_mesh, (int, float)): raise TypeError(messages.MESH_NAN) if interface.target_mesh <= 0: raise ValueError(messages.MESH_NEGATIVE) if interface.target_mesh >= np.amin(box) / 2.: raise ValueError(messages.MESH_LARGE) try: np.arange(int(self.interface.alpha / self.interface.target_mesh)) except BaseException: print(("Error while initializing ITIM: alpha ({0:f}) too large or\ mesh ({1:f}) too small".format(self.interface.alpha, self.interface.target_mesh))) raise ValueError
Example #10
Source File: utilities.py From pytim with GNU General Public License v3.0 | 6 votes |
def guess_normal(universe, group): """ Guess the normal of a liquid slab """ universe.atoms.pack_into_box() dim = universe.coord.dimensions delta = [] for direction in range(0, 3): histo, _ = np.histogram( group.positions[:, direction], bins=5, range=(0, dim[direction]), density=True) max_val = np.amax(histo) min_val = np.amin(histo) delta.append(np.sqrt((max_val - min_val)**2)) if np.max(delta) / np.min(delta) < 5.0: print("Warning: the result of the automatic normal detection (", np.argmax(delta), ") is not reliable") return np.argmax(delta)
Example #11
Source File: test_io.py From snowy with MIT License | 6 votes |
def test_range(): source = path('../docs/ground.jpg') ground = snowy.load(source) assert np.amin(ground) >= 0 and np.amax(ground) <= 1 with tempfile.NamedTemporaryFile() as fp: target = fp.name + '.png' snowy.export(ground, target) show_filename(target) show_filename(source) show_array(ground, True) blurred = snowy.blur(ground, radius=10) snowy.show(blurred)
Example #12
Source File: phoenics.py From phoenics with Apache License 2.0 | 6 votes |
def _generate_sampled(self, num_samples, observ_dict): # clean observations obs_params, obs_losses = self.observation_parser.parse(observ_dict) lowest_loss = np.amin(obs_losses) lowest_params = obs_params[np.argmin(obs_losses)] self.obs_params, self.obs_losses = self.observation_parser._raw_obs_params, self.observation_parser._raw_obs_losses self._compute_characteristic_distances() # create and sample the model print('# running density estimation') self.network = BayesianNeuralNetwork(self.var_dicts, obs_params, obs_losses, self.param_dict['general']['batch_size'], backend = self.param_dict['general']['backend']) self.network.create_model() self.network.sample() self.network.build_penalties() # sample the acquisition function print('# proposing new samples') self.proposed_samples = self.acq_func_sampler.sample(lowest_params, self.network.penalty_contributions, self.network.lambda_values, parallel = self.param_dict['general']['parallel_evaluations'])
Example #13
Source File: util.py From DeepFloorplan with GNU General Public License v3.0 | 6 votes |
def refine_room_region(cw_mask, rm_ind): label_rm, num_label = ndimage.label((1-cw_mask)) new_rm_ind = np.zeros(rm_ind.shape) for j in xrange(1, num_label+1): mask = (label_rm == j).astype(np.uint8) ys, xs = np.where(mask!=0) area = (np.amax(xs)-np.amin(xs))*(np.amax(ys)-np.amin(ys)) if area < 100: continue else: room_types, type_counts = np.unique(mask*rm_ind, return_counts=True) if len(room_types) > 1: room_types = room_types[1:] # ignore background type which is zero type_counts = type_counts[1:] # ignore background count new_rm_ind += mask*room_types[np.argmax(type_counts)] return new_rm_ind
Example #14
Source File: benchmark_functions.py From phoenics with Apache License 2.0 | 6 votes |
def discrete_ackley(vector): # takes k-dimensional vector vector = np.array(vector) vector = 100 * vector - 50 bounds = [1.0, 2.0, 3.0, 4.0, 5.0] bounds = np.array(bounds)**2 result = 5 for bound in bounds[::-1]: if np.amax(np.abs(vector)) < bound: result -= 1 bounds = [1.25, 2.0, 2.5] bounds = np.array(bounds)**2 domain = np.linspace(-50, 50, 10) dx = domain[1] - domain[0] imaged = np.array([np.amin(np.abs(element - domain)) for element in vector]) new_res = 5 for bound in bounds[::-1]: if np.amax(np.abs(imaged)) < bound: new_res -= 1 result = np.amin([result, new_res]) result = np.amin([4, result]) return result
Example #15
Source File: gw.py From pyscf with Apache License 2.0 | 6 votes |
def get_wmin_wmax_tmax_ia_def(self, tol): from numpy import log, exp, sqrt, where, amin, amax """ This is a default choice of the wmin and wmax parameters for a log grid along imaginary axis. The default choice is based on the eigenvalues. """ E = self.ksn2e[0,0,:] E_fermi = self.fermi_energy E_homo = amax(E[where(E<=E_fermi)]) E_gap = amin(E[where(E>E_fermi)]) - E_homo E_maxdiff = amax(E) - amin(E) d = amin(abs(E_homo-E)[where(abs(E_homo-E)>1e-4)]) wmin_def = sqrt(tol * (d**3) * (E_gap**3)/(d**2+E_gap**2)) wmax_def = (E_maxdiff**2/tol)**(0.250) tmax_def = -log(tol)/ (E_gap) tmin_def = -100*log(1.0-tol)/E_maxdiff return wmin_def, wmax_def, tmin_def,tmax_def
Example #16
Source File: detection.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def _check_satisfy_constraints(self, label, xmin, ymin, xmax, ymax, width, height): """Check if constrains are satisfied""" if (xmax - xmin) * (ymax - ymin) < 2: return False # only 1 pixel x1 = float(xmin) / width y1 = float(ymin) / height x2 = float(xmax) / width y2 = float(ymax) / height object_areas = self._calculate_areas(label[:, 1:]) valid_objects = np.where(object_areas * width * height > 2)[0] if valid_objects.size < 1: return False intersects = self._intersect(label[valid_objects, 1:], x1, y1, x2, y2) coverages = self._calculate_areas(intersects) / object_areas[valid_objects] coverages = coverages[np.where(coverages > 0)[0]] return coverages.size > 0 and np.amin(coverages) > self.min_object_covered
Example #17
Source File: hierarchies.py From phoenics with Apache License 2.0 | 5 votes |
def _build_tolerances(self): shapes = self.unscaled_losses.shape scaled_losses = np.zeros((shapes[0] + 1, shapes[1])) mins, maxs, tols = [], [], [] domain = np.arange(shapes[1]) shift = 0 for obj_index in range(len(self.unscaled_losses)): loss = self.unscaled_losses[obj_index] minimum = np.amin(loss[domain]) maximum = np.amax(loss[domain]) mins.append(minimum) maxs.append(maximum) tolerance = minimum + self.loss_tolerances[obj_index] * (maximum - minimum) # now shrink the region of interest interest = np.where(loss[domain] < tolerance)[0] if len(interest) > 0: domain = domain[interest] tols.append(tolerance + shift) scaled_losses[obj_index] = self.unscaled_losses[obj_index] + shift if obj_index < len(self.unscaled_losses) - 1: shift -= np.amax(self.unscaled_losses[obj_index + 1][domain]) - tolerance else: shift -= np.amax(self.unscaled_losses[0][domain]) - tolerance scaled_losses[obj_index + 1] = self.unscaled_losses[0] + shift self.tols = np.array(tols) self.scaled_losses = scaled_losses
Example #18
Source File: dataset.py From calamari with Apache License 2.0 | 5 votes |
def is_sample_valid(self, sample, line, text): if self.mode == DataSetMode.PREDICT or self.mode == DataSetMode.TRAIN or self.mode == DataSetMode.PRED_AND_EVAL: # skip invalid imanges (e. g. corrupted or empty files) if line is None or (line.size == 0 or np.amax(line) == np.amin(line)): return False return True
Example #19
Source File: degrade.py From calamari with Apache License 2.0 | 5 votes |
def autoinvert(image): assert amin(image) >= 0 assert amax(image) <= 1 if np.sum(image > 0.9) > np.sum(image < 0.1): return 1 - image else: return image # # random geometric transformations #
Example #20
Source File: degrade.py From calamari with Apache License 2.0 | 5 votes |
def bounded_gaussian_noise(shape, sigma, maxdelta): n, m = shape deltas = np.random.rand(2, n, m) deltas = ndi.gaussian_filter(deltas, (0, sigma, sigma)) deltas -= np.amin(deltas) deltas /= np.amax(deltas) deltas = (2*deltas-1) * maxdelta return deltas
Example #21
Source File: clipping_test.py From model-optimization with Apache License 2.0 | 5 votes |
def test_different_shapes(self, shape): stage = clipping.ClipByValueEncodingStage(-1.0, 1.0) test_data = self.run_one_to_many_encode_decode( stage, lambda: tf.random.normal(shape)) self.common_asserts_for_test_data(test_data) self.assertGreaterEqual(1.0, np.amax(test_data.decoded_x)) self.assertLessEqual(-1.0, np.amin(test_data.decoded_x))
Example #22
Source File: test_function_base.py From auto-alt-text-lambda-api with MIT License | 5 votes |
def test_basic(self): a = [3, 4, 5, 10, -3, -5, 6.0] assert_equal(np.amin(a), -5.0) b = [[3, 6.0, 9.0], [4, 10.0, 5.0], [8, 3.0, 2.0]] assert_equal(np.amin(b, axis=0), [3.0, 3.0, 2.0]) assert_equal(np.amin(b, axis=1), [3.0, 4.0, 2.0])
Example #23
Source File: chimera.py From phoenics with Apache License 2.0 | 5 votes |
def scalarize_objectives(self, losses): for index in range(losses.shape[1]): min_loss, max_loss = np.amin(losses[:, index]), np.amax(losses[:, index]) losses[:, index] = (losses[:, index] - min_loss) / (max_loss - min_loss) losses = np.where(np.isnan(losses), 0., losses) self.unscaled_losses = losses.transpose() self._build_tolerances() self._construct_objective() return self.loss.transpose() #========================================================================
Example #24
Source File: chimera.py From phoenics with Apache License 2.0 | 5 votes |
def _build_tolerances(self): shapes = self.unscaled_losses.shape scaled_losses = np.zeros((shapes[0] + 1, shapes[1])) mins, maxs, tols = [], [], [] domain = np.arange(shapes[1]) shift = 0 for obj_index in range(len(self.unscaled_losses)): loss = self.unscaled_losses[obj_index] minimum = np.amin(loss[domain]) maximum = np.amax(loss[domain]) mins.append(minimum) maxs.append(maximum) tolerance = minimum + self.loss_tolerances[obj_index] * (maximum - minimum) # now shrink the region of interest interest = np.where(loss[domain] < tolerance)[0] if len(interest) > 0: domain = domain[interest] tols.append(tolerance + shift) scaled_losses[obj_index] = self.unscaled_losses[obj_index] + shift if obj_index < len(self.unscaled_losses) - 1: shift -= np.amax(self.unscaled_losses[obj_index + 1][domain]) - tolerance else: shift -= np.amax(self.unscaled_losses[0][domain]) - tolerance scaled_losses[obj_index + 1] = self.unscaled_losses[0] + shift self.tols = np.array(tols) self.scaled_losses = scaled_losses
Example #25
Source File: kdtree.py From lambda-packs with MIT License | 5 votes |
def __init__(self, data, leafsize=10): self.data = np.asarray(data) self.n, self.m = np.shape(self.data) self.leafsize = int(leafsize) if self.leafsize < 1: raise ValueError("leafsize must be at least 1") self.maxes = np.amax(self.data,axis=0) self.mins = np.amin(self.data,axis=0) self.tree = self.__build(np.arange(self.n), self.maxes, self.mins)
Example #26
Source File: observation_parser.py From phoenics with Apache License 2.0 | 5 votes |
def _rescale_losses(self, losses): hier_losses = self.loss_shaper.rescale_losses(losses) if np.amin(hier_losses) != np.amax(hier_losses): hier_losses = (hier_losses - np.amin(hier_losses)) / (np.amax(hier_losses) - np.amin(hier_losses)) hier_losses = np.sqrt(hier_losses) else: hier_losses -= np.amin(hier_losses) return hier_losses # return losses[:, 0]
Example #27
Source File: benchmark_functions.py From phoenics with Apache License 2.0 | 5 votes |
def narrow_funnel(vector): # takes k-dimensional vector vector = np.array(vector) vector = 100 * vector - 50 bounds = [1.0, 2.0, 3.0, 4.0, 5.0] bounds = np.array(bounds)**2 result = 5 for bound in bounds[::-1]: if np.amax(np.abs(vector)) < bound: result -= 1 result = np.amin([4, result]) return result
Example #28
Source File: benchmark_functions.py From phoenics with Apache License 2.0 | 5 votes |
def linear_funnel(vector): # takes k-dimensional vector vector = np.array(vector) vector = 10 * vector - 5 bounds = [0.5, 1.5, 2.5, 3.5, 4.5] result = 5 for bound in bounds[::-1]: if np.amax(np.abs(vector)) < bound: result -= 1 result = np.amin([4, result]) return result
Example #29
Source File: model.py From phoenics with Apache License 2.0 | 5 votes |
def _assemble_training_sets(self): params = self.dataset['parameters'] areas = self.dataset['peak_area'] times = self.dataset['execution_time'] self.features = params[self.work_indices] self.targets = np.array([areas[self.work_indices], times[self.work_indices]]).transpose() self.test_features = params[self.test_indices] self.test_targets = np.array([areas[self.test_indices], times[self.test_indices]]).transpose() max_features = np.amax(np.amax(self.features, axis = 0), axis = 0) min_features = np.amin(np.amin(self.features, axis = 0), axis = 0) mean_features = np.mean(np.mean(self.features, axis = 0), axis = 0) std_features = np.std(np.std(self.features, axis = 0), axis = 0) max_targets = np.amax(self.targets, axis = 0) min_targets = np.amin(self.targets, axis = 0) mean_targets = np.mean(self.targets, axis = 0) details_dict = {'min_features': min_features, 'max_features': max_features, 'mean_features': mean_features, 'std_features': std_features, 'min_targets': min_targets, 'max_targets': max_targets, 'mean_targets': mean_targets, 'features_shape': self.features.shape, 'targets_shape': self.targets.shape} pickle.dump(details_dict, open('dataset_details.pkl', 'wb')) self.dataset_details = 'dataset_details.pkl' self.train_features, self.train_targets = [], [] self.valid_features, self.valid_targets = [], [] for index in range(NUM_FOLDS): train_features = params[self.train_indices[index]] valid_features = params[self.valid_indices[index]] train_targets = np.array([areas[self.train_indices[index]], times[self.train_indices[index]]]).transpose() valid_targets = np.array([areas[self.valid_indices[index]], times[self.valid_indices[index]]]).transpose() self.train_features.append(train_features) self.train_targets.append(train_targets) self.valid_features.append(np.concatenate([valid_features for i in range(len(train_features) // len(valid_features))])) self.valid_targets.append(np.concatenate([valid_targets for i in range(len(train_targets) // len(valid_targets))]))
Example #30
Source File: minimize.py From kernel_tuner with Apache License 2.0 | 5 votes |
def get_bounds_x0_eps(tuning_options): """compute bounds, x0 (the initial guess), and eps""" values = tuning_options.tune_params.values() if tuning_options.scaling: #bounds = [(0, 1) for _ in values] #x0 = [0.5 for _ in bounds] eps = numpy.amin([1.0/len(v) for v in values]) #reducing interval from [0, 1] to [0, eps*len(v)] bounds = [(0, eps*len(v)) for v in values] x0 = [0.5*eps*len(v) for v in values] else: bounds = get_bounds(tuning_options.tune_params) x0 = [(min_v+max_v)/2.0 for (min_v, max_v) in bounds] eps = 1e9 for v_list in values: vals = numpy.sort(v_list) eps = min(eps, numpy.amin(numpy.gradient(vals))) tuning_options["eps"] = eps logging.debug('get_bounds_x0_eps called') logging.debug('bounds ' + str(bounds)) logging.debug('x0 ' + str(x0)) logging.debug('eps ' + str(eps)) return bounds, x0, eps