Python autograd.numpy.max() Examples
The following are 30
code examples of autograd.numpy.max().
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
autograd.numpy
, or try the search function
.
Example #1
Source File: truss2d.py From pymoo with Apache License 2.0 | 7 votes |
def _evaluate(self, x, out, *args, **kwargs): # variable names for convenient access x1 = x[:, 0] x2 = x[:, 1] y = x[:, 2] # first objectives f1 = x1 * anp.sqrt(16 + anp.square(y)) + x2 * anp.sqrt((1 + anp.square(y))) # measure which are needed for the second objective sigma_ac = 20 * anp.sqrt(16 + anp.square(y)) / (y * x1) sigma_bc = 80 * anp.sqrt(1 + anp.square(y)) / (y * x2) # take the max f2 = anp.max(anp.column_stack((sigma_ac, sigma_bc)), axis=1) # define a constraint g1 = f2 - self.Smax out["F"] = anp.column_stack([f1, f2]) out["G"] = g1
Example #2
Source File: util.py From kernel-gof with MIT License | 6 votes |
def bound_by_data(Z, Data): """ Determine lower and upper bound for each dimension from the Data, and project Z so that all points in Z live in the bounds. Z: m x d Data: n x d Return a projected Z of size m x d. """ n, d = Z.shape Low = np.min(Data, 0) Up = np.max(Data, 0) LowMat = np.repeat(Low[np.newaxis, :], n, axis=0) UpMat = np.repeat(Up[np.newaxis, :], n, axis=0) Z = np.maximum(LowMat, Z) Z = np.minimum(UpMat, Z) return Z
Example #3
Source File: optimize_accelerator.py From ceviche with MIT License | 6 votes |
def accel_gradient(eps_arr, mode='max'): # set the permittivity of the FDFD and solve the fields F.eps_r = eps_arr.reshape((Nx, Ny)) Ex, Ey, Hz = F.solve(source) # compute the gradient and normalize if you want G = npa.sum(Ey * eta / Ny) if mode == 'max': return -np.abs(G) / Emax(Ex, Ey, eps_r) elif mode == 'avg': return -np.abs(G) / Eavg(Ex, Ey) else: return -np.abs(G / E0) # define the gradient for autograd
Example #4
Source File: geometry.py From AeroSandbox with MIT License | 6 votes |
def get_camber_at_chord_fraction_legacy(self, chord_fraction): # Returns the (interpolated) camber at a given location(s). The location is specified by the chord fraction, as measured from the leading edge. Camber is nondimensionalized by chord (i.e. this function returns camber/c at a given x/c). chord = np.max(self.coordinates[:, 0]) - np.min( self.coordinates[:, 0]) # This should always be 1, but this is just coded for robustness. x = chord_fraction * chord + min(self.coordinates[:, 0]) upperCoors = self.upper_coordinates() lowerCoors = self.lower_coordinates() y_upper_func = sp_interp.interp1d(x=upperCoors[:, 0], y=upperCoors[:, 1], copy=False, fill_value='extrapolate') y_lower_func = sp_interp.interp1d(x=lowerCoors[:, 0], y=lowerCoors[:, 1], copy=False, fill_value='extrapolate') y_upper = y_upper_func(x) y_lower = y_lower_func(x) camber = (y_upper + y_lower) / 2 return camber
Example #5
Source File: geometry.py From AeroSandbox with MIT License | 6 votes |
def get_thickness_at_chord_fraction_legacy(self, chord_fraction): # Returns the (interpolated) camber at a given location(s). The location is specified by the chord fraction, as measured from the leading edge. Thickness is nondimensionalized by chord (i.e. this function returns t/c at a given x/c). chord = np.max(self.coordinates[:, 0]) - np.min( self.coordinates[:, 0]) # This should always be 1, but this is just coded for robustness. x = chord_fraction * chord + min(self.coordinates[:, 0]) upperCoors = self.upper_coordinates() lowerCoors = self.lower_coordinates() y_upper_func = sp_interp.interp1d(x=upperCoors[:, 0], y=upperCoors[:, 1], copy=False, fill_value='extrapolate') y_lower_func = sp_interp.interp1d(x=lowerCoors[:, 0], y=lowerCoors[:, 1], copy=False, fill_value='extrapolate') y_upper = y_upper_func(x) y_lower = y_lower_func(x) thickness = np.maximum(y_upper - y_lower, 0) return thickness
Example #6
Source File: truss2d.py From pymop with Apache License 2.0 | 6 votes |
def _evaluate(self, x, out, *args, **kwargs): # variable names for convenient access x1 = x[:, 0] x2 = x[:, 1] y = x[:, 2] # first objectives f1 = x1 * anp.sqrt(16 + anp.square(y)) + x2 * anp.sqrt((1 + anp.square(y))) # measure which are needed for the second objective sigma_ac = 20 * anp.sqrt(16 + anp.square(y)) / (y * x1) sigma_bc = 80 * anp.sqrt(1 + anp.square(y)) / (y * x2) # take the max f2 = anp.max(anp.column_stack((sigma_ac, sigma_bc)), axis=1) # define a constraint g1 = f2 - self.Smax out["F"] = anp.column_stack([f1, f2]) out["G"] = g1
Example #7
Source File: base.py From autohmm with BSD 2-Clause "Simplified" License | 6 votes |
def _decode_map(self, data): # adapted hmmlearn flp = self._compute_log_likelihood(data) flp_rep = np.zeros((flp.shape[0], self.n_components)) for u in range(self.n_unique): for c in range(self.n_chain): flp_rep[:, u*self.n_chain+c] = flp[:, u] logprob, fwdlattice = self._do_forward_pass(flp_rep) bwdlattice = self._do_backward_pass(flp_rep) gamma = fwdlattice + bwdlattice # gamma is guaranteed to be correctly normalized by logprob at # all frames, unless we do approximate inference using pruning. # So, we will normalize each frame explicitly in case we # pruned too aggressively. posteriors = np.exp(gamma.T - logsumexp(gamma, axis=1)).T posteriors += np.finfo(np.float64).eps posteriors /= np.sum(posteriors, axis=1).reshape((-1, 1)) state_sequence = np.argmax(posteriors, axis=1) map_logprob = np.max(posteriors, axis=1).sum() return map_logprob, state_sequence
Example #8
Source File: cdtlz.py From pymop with Apache License 2.0 | 5 votes |
def _calc_pareto_front(self, ref_dirs, *args, **kwargs): F = super()._calc_pareto_front(ref_dirs, *args, **kwargs) a = anp.sqrt(anp.sum(F ** 2, 1) - 3 / 4 * anp.max(F ** 2, axis=1)) a = anp.expand_dims(a, axis=1) a = anp.tile(a, [1, ref_dirs.shape[1]]) F = F / a return F
Example #9
Source File: goftest.py From kernel-gof with MIT License | 5 votes |
def optimize_auto_init(p, dat, J, **ops): """ Optimize parameters by calling optimize_locs_widths(). Automatically initialize the test locations and the Gaussian width. Return optimized locations, Gaussian width, optimization info """ assert J>0 # Use grid search to initialize the gwidth X = dat.data() n_gwidth_cand = 5 gwidth_factors = 2.0**np.linspace(-3, 3, n_gwidth_cand) med2 = util.meddistance(X, 1000)**2 k = kernel.KGauss(med2*2) # fit a Gaussian to the data and draw to initialize V0 V0 = util.fit_gaussian_draw(X, J, seed=829, reg=1e-6) list_gwidth = np.hstack( ( (med2)*gwidth_factors ) ) besti, objs = GaussFSSD.grid_search_gwidth(p, dat, V0, list_gwidth) gwidth = list_gwidth[besti] assert util.is_real_num(gwidth), 'gwidth not real. Was %s'%str(gwidth) assert gwidth > 0, 'gwidth not positive. Was %.3g'%gwidth logging.info('After grid search, gwidth=%.3g'%gwidth) V_opt, gwidth_opt, info = GaussFSSD.optimize_locs_widths(p, dat, gwidth, V0, **ops) # set the width bounds #fac_min = 5e-2 #fac_max = 5e3 #gwidth_lb = fac_min*med2 #gwidth_ub = fac_max*med2 #gwidth_opt = max(gwidth_lb, min(gwidth_opt, gwidth_ub)) return V_opt, gwidth_opt, info
Example #10
Source File: goftest.py From kernel-gof with MIT License | 5 votes |
def simulate_null_dist(eigs, J, n_simulate=2000, seed=7): """ Simulate the null distribution using the spectrums of the covariance matrix of the U-statistic. The simulated statistic is n*FSSD^2 where FSSD is an unbiased estimator. - eigs: a numpy array of estimated eigenvalues of the covariance matrix. eigs is of length d*J, where d is the input dimension, and - J: the number of test locations. Return a numpy array of simulated statistics. """ d = old_div(len(eigs),J) assert d>0 # draw at most d x J x block_size values at a time block_size = max(20, int(old_div(1000.0,(d*J)))) fssds = np.zeros(n_simulate) from_ind = 0 with util.NumpySeedContext(seed=seed): while from_ind < n_simulate: to_draw = min(block_size, n_simulate-from_ind) # draw chi^2 random variables. chi2 = np.random.randn(d*J, to_draw)**2 # an array of length to_draw sim_fssds = eigs.dot(chi2-1.0) # store end_ind = from_ind+to_draw fssds[from_ind:end_ind] = sim_fssds from_ind = end_ind return fssds
Example #11
Source File: plot.py From kernel-gof with MIT License | 5 votes |
def plot_runtime(ex, fname, func_xvalues, xlabel, func_title=None): results = glo.ex_load_result(ex, fname) value_accessor = lambda job_results: job_results['time_secs'] vf_pval = np.vectorize(value_accessor) # results['job_results'] is a dictionary: # {'test_result': (dict from running perform_test(te) '...':..., } times = vf_pval(results['job_results']) repeats, _, n_methods = results['job_results'].shape time_avg = np.mean(times, axis=0) time_std = np.std(times, axis=0) xvalues = func_xvalues(results) #ns = np.array(results[xkey]) #te_proportion = 1.0 - results['tr_proportion'] #test_sizes = ns*te_proportion line_styles = func_plot_fmt_map() method_labels = get_func2label_map() func_names = [f.__name__ for f in results['method_job_funcs'] ] for i in range(n_methods): te_proportion = 1.0 - results['tr_proportion'] fmt = line_styles[func_names[i]] #plt.errorbar(ns*te_proportion, mean_rejs[:, i], std_pvals[:, i]) method_label = method_labels[func_names[i]] plt.errorbar(xvalues, time_avg[:, i], yerr=time_std[:,i], fmt=fmt, label=method_label) ylabel = 'Time (s)' plt.ylabel(ylabel) plt.xlabel(xlabel) plt.xlim([np.min(xvalues), np.max(xvalues)]) plt.xticks( xvalues, xvalues ) plt.legend(loc='best') plt.gca().set_yscale('log') title = '%s. %d trials. '%( results['prob_label'], repeats ) if func_title is None else func_title(results) plt.title(title) #plt.grid() return results
Example #12
Source File: convnet.py From MLAlgorithms with MIT License | 5 votes |
def forward_pass(self, X): self.last_input = X out_height, out_width = pooling_shape(self.pool_shape, X.shape, self.stride) n_images, n_channels, _, _ = X.shape col = image_to_column(X, self.pool_shape, self.stride, self.padding) col = col.reshape(-1, self.pool_shape[0] * self.pool_shape[1]) arg_max = np.argmax(col, axis=1) out = np.max(col, axis=1) self.arg_max = arg_max return out.reshape(n_images, out_height, out_width, n_channels).transpose(0, 3, 1, 2)
Example #13
Source File: util.py From kernel-gof with MIT License | 5 votes |
def constrain(val, min_val, max_val): return min(max_val, max(min_val, val))
Example #14
Source File: cdtlz.py From pymoo with Apache License 2.0 | 5 votes |
def _calc_pareto_front(self, ref_dirs, *args, **kwargs): F = super()._calc_pareto_front(ref_dirs, *args, **kwargs) a = anp.sqrt(anp.sum(F ** 2, 1) - 3 / 4 * anp.max(F ** 2, axis=1)) a = anp.expand_dims(a, axis=1) a = anp.tile(a, [1, ref_dirs.shape[1]]) F = F / a return F
Example #15
Source File: optimize_accelerator.py From ceviche with MIT License | 5 votes |
def Emax(Ex, Ey, eps_r): E_mag = npa.sqrt(npa.square(npa.abs(Ex)) + npa.square(npa.abs(Ey))) material_density = (eps_r - 1) / (eps_max - 1) return npa.max(E_mag * material_density) # average electric field magnitude in the domain
Example #16
Source File: test_numpy.py From autograd with MIT License | 5 votes |
def test_max_equal_values_2d(): def fun(x): return np.max(np.array([[x, x ], [x, 0.5]]), axis=1) check_grads(fun)(1.0) check_grads(fun)(-1.0)
Example #17
Source File: test_numpy.py From autograd with MIT License | 5 votes |
def test_max_equal_values(): def fun(x): return np.max(np.array([x, x])) check_grads(fun)(1.0)
Example #18
Source File: test_numpy.py From autograd with MIT License | 5 votes |
def test_max_axis_keepdims(): def fun(x): return np.max(x, axis=1, keepdims=True) mat = npr.randn(3, 4, 5) check_grads(fun)(mat)
Example #19
Source File: test_numpy.py From autograd with MIT License | 5 votes |
def test_max_axis(): def fun(x): return np.max(x, axis=1) mat = npr.randn(3, 4, 5) check_grads(fun)(mat)
Example #20
Source File: test_numpy.py From autograd with MIT License | 5 votes |
def test_max(): def fun(x): return np.max(x) mat = npr.randn(10, 11) check_grads(fun)(mat)
Example #21
Source File: test_systematic.py From autograd with MIT License | 5 votes |
def test_max(): stat_check(np.max) # def test_all(): stat_check(np.all) # def test_any(): stat_check(np.any)
Example #22
Source File: define_gradient.py From autograd with MIT License | 5 votes |
def logsumexp(x): """Numerically stable log(sum(exp(x))), also defined in scipy.special""" max_x = np.max(x) return max_x + np.log(np.sum(np.exp(x - max_x))) # Next, we write a function that specifies the gradient with a closure. # The reason for the closure is so that the gradient can depend # on both the input to the original function (x), and the output of the # original function (ans).
Example #23
Source File: bayesian_optimization.py From autograd with MIT License | 5 votes |
def defaultmax(x, default=-np.inf): if x.size == 0: return default return np.max(x)
Example #24
Source File: convnet.py From autograd with MIT License | 5 votes |
def forward_pass(self, inputs, param_vector): new_shape = inputs.shape[:2] for i in [0, 1]: pool_width = self.pool_shape[i] img_width = inputs.shape[i + 2] new_shape += (img_width // pool_width, pool_width) result = inputs.reshape(new_shape) return np.max(np.max(result, axis=3), axis=4)
Example #25
Source File: convnet.py From autograd with MIT License | 5 votes |
def logsumexp(X, axis, keepdims=False): max_X = np.max(X) return max_X + np.log(np.sum(np.exp(X - max_X), axis=axis, keepdims=keepdims))
Example #26
Source File: geometry.py From AeroSandbox with MIT License | 5 votes |
def get_sharp_TE_airfoil(self): # Returns a version of the airfoil with a sharp trailing edge. upper_original_coors = self.upper_coordinates() # Note: includes leading edge point, be careful about duplicates lower_original_coors = self.lower_coordinates() # Note: includes leading edge point, be careful about duplicates # Find data about the TE # Get the scale factor x_mcl = self.mcl_coordinates[:, 0] x_max = np.max(x_mcl) x_min = np.min(x_mcl) scale_factor = (x_mcl - x_min) / (x_max - x_min) # linear contraction # Do the contraction upper_minus_mcl_adjusted = self.upper_minus_mcl - self.upper_minus_mcl[-1, :] * np.expand_dims(scale_factor, 1) # Recreate coordinates upper_coordinates_adjusted = np.flipud(self.mcl_coordinates + upper_minus_mcl_adjusted) lower_coordinates_adjusted = self.mcl_coordinates - upper_minus_mcl_adjusted coordinates = np.vstack(( upper_coordinates_adjusted[:-1, :], lower_coordinates_adjusted )) # Make a new airfoil with the coordinates name = self.name + ", with sharp TE" new_airfoil = Airfoil(name=name, coordinates=coordinates, repanel=False) return new_airfoil
Example #27
Source File: geometry.py From AeroSandbox with MIT License | 5 votes |
def span(self): # Returns the span (y-distance between the root of the wing and the tip). # If symmetric, this is doubled to obtain the full span. spans = [] for i in range(len(self.xsecs)): spans.append(np.abs(self.xsecs[i].xyz_le[1] - self.xsecs[0].xyz_le[1])) span = np.max(spans) if self.symmetric: span *= 2 return span
Example #28
Source File: test_inference.py From momi2 with GNU General Public License v3.0 | 5 votes |
def test_underflow_robustness(folded): num_runs = 1000 sampled_pops = (1, 2, 3) sampled_n = (5, 5, 5) n_bases = int(1e3) demo = momi.DemographicModel(1.0, .25, muts_per_gen=2.5 / n_bases) for p in sampled_pops: demo.add_leaf(p) demo.add_time_param("t0") demo.add_time_param("t1", lower_constraints=["t0"]) demo.move_lineages(1, 2, "t0") demo.move_lineages(2, 3, "t1") true_params = np.array([0.5, 0.7]) demo.set_params(true_params) data = demo.simulate_data( length=n_bases, recoms_per_gen=0.0, num_replicates=num_runs, sampled_n_dict=dict(zip(sampled_pops, sampled_n))) sfs = data.extract_sfs(1) if folded: sfs = sfs.fold() demo.set_data(sfs) demo.set_params({"t0": 0.1, "t1": 100.0}) optimize_res = demo.optimize() print(optimize_res) inferred_params = np.array(list(demo.get_params().values())) error = (true_params - inferred_params) / true_params print("# Truth:\n", true_params) print("# Inferred:\n", inferred_params) print("# Max Relative Error: %f" % max(abs(error))) print("# Relative Error:", "\n", error) assert max(abs(error)) < .1
Example #29
Source File: configurations.py From momi2 with GNU General Public License v3.0 | 5 votes |
def __init__(self, sampled_pops, conf_arr, sampled_n=None, ascertainment_pop=None): """Use build_config_list() instead of calling this constructor directly""" # If sampled_n=None, ConfigList.sampled_n will be the max number of # observed individuals/alleles per population. self.sampled_pops = tuple(sampled_pops) self.value = conf_arr if ascertainment_pop is None: ascertainment_pop = [True] * len(sampled_pops) self.ascertainment_pop = np.array(ascertainment_pop) self.ascertainment_pop.setflags(write=False) if all(not a for a in self.ascertainment_pop): raise ValueError( "At least one of the populations must be used for " "ascertainment of polymorphic sites") max_n = np.max(np.sum(self.value, axis=2), axis=0) if sampled_n is None: sampled_n = max_n sampled_n = np.array(sampled_n) if np.any(sampled_n < max_n): raise ValueError("config greater than sampled_n") self.sampled_n = sampled_n if not np.sum(sampled_n[self.ascertainment_pop]) >= 2: raise ValueError("The total sample size of the ascertainment " "populations must be >= 2") config_sampled_n = np.sum(self.value, axis=2) self.has_missing_data = np.any(config_sampled_n != self.sampled_n) if np.any(np.sum(self.value[:, self.ascertainment_pop, :], axis=1) == 0): raise ValueError("Monomorphic sites not allowed. In addition, all" " sites must be polymorphic when restricted to" " the ascertainment populations")
Example #30
Source File: geometry.py From AeroSandbox with MIT License | 4 votes |
def get_bounding_cube(self): """ Finds the axis-aligned cube that encloses the airplane with the smallest size. Useful for plotting and getting a sense for the scale of a problem. Args: self.wings (iterable): All the wings included for analysis each containing their geometry in x,y,z notation using units of m Returns: tuple: Tuple of 4 floats x, y, z, and s, where x, y, and z are the coordinates of the cube center, and s is half of the side length. """ # Get vertices to enclose vertices = None for wing in self.wings: for xsec in wing.xsecs: if vertices is None: vertices = xsec.xyz_le + wing.xyz_le else: vertices = np.vstack(( vertices, xsec.xyz_le + wing.xyz_le )) vertices = np.vstack(( vertices, xsec.xyz_te() + wing.xyz_le )) if wing.symmetric: vertices = np.vstack(( vertices, reflect_over_XZ_plane(xsec.xyz_le + wing.xyz_le) )) vertices = np.vstack(( vertices, reflect_over_XZ_plane(xsec.xyz_te() + wing.xyz_le) )) # Enclose them x_max = np.max(vertices[:, 0]) y_max = np.max(vertices[:, 1]) z_max = np.max(vertices[:, 2]) x_min = np.min(vertices[:, 0]) y_min = np.min(vertices[:, 1]) z_min = np.min(vertices[:, 2]) x = np.mean((x_max, x_min)) y = np.mean((y_max, y_min)) z = np.mean((z_max, z_min)) s = 0.5 * np.max(( x_max - x_min, y_max - y_min, z_max - z_min )) return x, y, z, s