本文整理汇总了Python中numpy.argmin方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.argmin方法的具体用法?Python numpy.argmin怎么用?Python numpy.argmin使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.argmin方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: find_match
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import argmin [as 别名]
def find_match(self, pred, gt):
'''
Match component to balls.
'''
batch_size, n_frames_input, n_components, _ = pred.shape
diff = pred.reshape(batch_size, n_frames_input, n_components, 1, 2) - \
gt.reshape(batch_size, n_frames_input, 1, n_components, 2)
diff = np.sum(np.sum(diff ** 2, axis=-1), axis=1)
# Direct indices
indices = np.argmin(diff, axis=2)
ambiguous = np.zeros(batch_size, dtype=np.int8)
for i in range(batch_size):
_, counts = np.unique(indices[i], return_counts=True)
if not np.all(counts == 1):
ambiguous[i] = 1
return indices, ambiguous
示例2: _extract
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import argmin [as 别名]
def _extract(self, intervals, out, **kwargs):
def find_closest(ldm, interval, use_strand=True):
"""Uses
"""
# subset the positions to the appropriate strand
# and extract the positions
ldm_positions = ldm.loc[interval.chrom]
if use_strand and interval.strand != ".":
ldm_positions = ldm_positions.loc[interval.strand]
ldm_positions = ldm_positions.position.values
int_midpoint = (interval.end + interval.start) // 2
dist = (ldm_positions - 1) - int_midpoint # -1 for 0, 1 indexed positions
if use_strand and interval.strand == "-":
dist = - dist
return dist[np.argmin(np.abs(dist))]
out[:] = np.array([[find_closest(self.landmarks[ldm_name], interval, self.use_strand)
for ldm_name in self.columns]
for interval in intervals], dtype=float)
return out
示例3: whichTimeComesNext
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import argmin [as 别名]
def whichTimeComesNext(self, absTs):
""" Determine which absolute time comes next from current time
Specifically designed to determine when the next local zodiacal light event occurs form fZQuads
Args:
absTs (list) - the absolute times of different events (list of absolute times)
Return:
absT (astropy time quantity) - the absolute time which occurs next
"""
TK = self.TimeKeeping
#Convert Abs Times to norm Time
tabsTs = list()
for i in np.arange(len(absTs)):
tabsTs.append((absTs[i] - TK.missionStart).value) # all should be in first year
tSinceStartOfThisYear = TK.currentTimeNorm.copy().value%365.25
if len(tabsTs) == len(np.where(tSinceStartOfThisYear < np.asarray(tabsTs))[0]): # time strictly less than all absTs
absT = absTs[np.argmin(tabsTs)]
elif len(tabsTs) == len(np.where(tSinceStartOfThisYear > np.asarray(tabsTs))[0]):
absT = absTs[np.argmin(tabsTs)]
else: #Some are above and some are below
tmptabsTsInds = np.where(tSinceStartOfThisYear < np.asarray(tabsTs))[0]
absT = absTs[np.argmin(np.asarray(tabsTs)[tmptabsTsInds])] # of times greater than current time, returns smallest
return absT
示例4: run
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import argmin [as 别名]
def run(self):
variables = self.init_variables
for i in range(self.epochs):
grads = gradients(self.func,variables)
if self.func_type == gradients_config.func_type_min:
variables -= self.lr*grads
else:
variables += self.lr*grads
self.generations_points.append(variables)
self.generations_targets.append(self.func(variables))
if self.func_type == gradients_config.func_type_min:
self.global_best_target = np.min(np.array(self.generations_targets))
self.global_best_index = np.argmin(np.array(self.generations_targets))
self.global_best_point = self.generations_points[int(self.global_best_index)]
else:
self.global_best_target = np.max(np.array(self.generations_targets))
self.global_best_index = np.argmax(np.array(self.generations_targets))
self.global_best_point = self.generations_points[int(self.global_best_index)]
示例5: _do
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import argmin [as 别名]
def _do(self, F, return_pseudo_weights=False, **kwargs):
# here the normalized values are ignored but the ideal and nadir points are estimated to calculate trade-off
_, norm, ideal_point, nadir_point = normalize(F, self.ideal_point, self.nadir_point,
estimate_bounds_if_none=True, return_bounds=True)
# normalized distance to the worst solution
pseudo_weights = ((nadir_point - F) / norm)
# normalize weights to sum up to one
pseudo_weights = pseudo_weights / np.sum(pseudo_weights, axis=1)[:, None]
# search for the closest individual having this pseudo weights
I = np.argmin(np.sum(np.abs(pseudo_weights - self.weights), axis=1))
if return_pseudo_weights:
return I, pseudo_weights
else:
return I
示例6: get_extreme_points_c
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import argmin [as 别名]
def get_extreme_points_c(F, ideal_point, extreme_points=None):
# calculate the asf which is used for the extreme point decomposition
weights = np.eye(F.shape[1])
weights[weights == 0] = 1e6
# add the old extreme points to never loose them for normalization
_F = F
if extreme_points is not None:
_F = np.concatenate([extreme_points, _F], axis=0)
# use __F because we substitute small values to be 0
__F = _F - ideal_point
__F[__F < 1e-3] = 0
# update the extreme points for the normalization having the highest asf value each
F_asf = np.max(__F * weights[:, None, :], axis=2)
I = np.argmin(F_asf, axis=1)
extreme_points = _F[I, :]
return extreme_points
示例7: work_balanced_partition
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import argmin [as 别名]
def work_balanced_partition(tasks, costs=None):
if costs is None:
costs = numpy.ones(tasks)
if rank == 0:
segsize = float(sum(costs)) / pool.size
loads = []
cum_costs = numpy.cumsum(costs)
start_id = 0
for k in range(pool.size):
stop_id = numpy.argmin(abs(cum_costs - (k+1)*segsize)) + 1
stop_id = max(stop_id, start_id+1)
loads.append([start_id,stop_id])
start_id = stop_id
comm.bcast(loads)
else:
loads = comm.bcast()
if rank < len(loads):
start, stop = loads[rank]
return tasks[start:stop]
else:
return tasks[:0]
示例8: ghf_stability
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import argmin [as 别名]
def ghf_stability(mf, verbose=None):
log = logger.new_logger(mf, verbose)
with_symmetry = True
g, hop, hdiag = newton_ah.gen_g_hop_ghf(mf, mf.mo_coeff, mf.mo_occ,
with_symmetry=with_symmetry)
hdiag *= 2
def precond(dx, e, x0):
hdiagd = hdiag - e
hdiagd[abs(hdiagd)<1e-8] = 1e-8
return dx/hdiagd
def hessian_x(x): # See comments in function rhf_internal
return hop(x).real * 2
x0 = numpy.zeros_like(g)
x0[g!=0] = 1. / hdiag[g!=0]
if not with_symmetry: # allow to break point group symmetry
x0[numpy.argmin(hdiag)] = 1
e, v = lib.davidson(hessian_x, x0, precond, tol=1e-4, verbose=log)
if e < -1e-5:
log.note('GHF wavefunction has an internal instability')
mo = _rotate_mo(mf.mo_coeff, mf.mo_occ, v)
else:
log.note('GHF wavefunction is stable in the internal stability analysis')
mo = mf.mo_coeff
return mo
示例9: rohf_internal
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import argmin [as 别名]
def rohf_internal(mf, with_symmetry=True, verbose=None):
log = logger.new_logger(mf, verbose)
g, hop, hdiag = newton_ah.gen_g_hop_rohf(mf, mf.mo_coeff, mf.mo_occ,
with_symmetry=with_symmetry)
hdiag *= 2
def precond(dx, e, x0):
hdiagd = hdiag - e
hdiagd[abs(hdiagd)<1e-8] = 1e-8
return dx/hdiagd
def hessian_x(x): # See comments in function rhf_internal
return hop(x).real * 2
x0 = numpy.zeros_like(g)
x0[g!=0] = 1. / hdiag[g!=0]
if not with_symmetry: # allow to break point group symmetry
x0[numpy.argmin(hdiag)] = 1
e, v = lib.davidson(hessian_x, x0, precond, tol=1e-4, verbose=log)
if e < -1e-5:
log.note('ROHF wavefunction has an internal instability.')
mo = _rotate_mo(mf.mo_coeff, mf.mo_occ, v)
else:
log.note('ROHF wavefunction is stable in the internal stability analysis')
mo = mf.mo_coeff
return mo
示例10: hard_negative_multilabel
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import argmin [as 别名]
def hard_negative_multilabel(self):
"""Hard Negative Sampling based on multilabel assumption
Search the negative sample with largest distance (smallest sim)
with the anchor within self._k negative samplels
"""
# During early iterations of sampling, use random sampling instead
if self._iteration <= self._n:
return self.random_multilabel()
anchor_class_id, negative_class_id = np.random.choice(
self._index.keys(), 2)
anchor_id, positive_id = np.random.choice(
self._index[anchor_class_id], 2)
negative_ids = np.random.choice(
self._index[negative_class_id], self._k)
# calcualte the smallest simlarity one with negatives
anchor_label = parse_label(self._labels[anchor_id])
positive_label = parse_label(self._labels[positive_id])
negative_labels = [parse_label(self._labels[negative_id]) for
negative_id in negative_ids]
p_sim = intersect_sim(anchor_label, positive_label)
n_sims = np.array(
[intersect_sim(anchor_label, negative_label) for
negative_label in negative_labels])
min_sim_id = np.argmin(n_sims)
negative_id = negative_ids[min_sim_id]
n_sim = n_sims[min_sim_id]
margin = p_sim - n_sim
return (anchor_id, positive_id, negative_id, margin)
示例11: find_medioid
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import argmin [as 别名]
def find_medioid(self, X, Y):
"""
Find point with minimal distance to all other points.
Parameters
----------
X : array
data set, with N samples x D features.
Y : array
labels to select for which samples to compute distances.
Returns
-------
x : array
medioid
ix : int
index of medioid
"""
# Initiate an array with infinities
A = np.full((X.shape[0],), np.inf)
# Insert sum of distances to other points
A[Y] = np.sum(squareform(pdist(X[Y, :])), axis=1)
# Find the index of the point with the smallest distance
ix = np.argmin(A)
return X[ix, :], ix
示例12: polar_distance
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import argmin [as 别名]
def polar_distance(x1, x2):
"""
Given two arrays of numbers x1 and x2, pairs the cells that are the
closest and provides the pairing matrix index: x1(index(1,:)) should be as
close as possible to x2(index(2,:)). The function outputs the average of
the absolute value of the differences abs(x1(index(1,:))-x2(index(2,:))).
:param x1: vector 1
:param x2: vector 2
:return: d: minimum distance between d
index: the permutation matrix
"""
x1 = np.reshape(x1, (1, -1), order='F')
x2 = np.reshape(x2, (1, -1), order='F')
N1 = x1.size
N2 = x2.size
diffmat = np.arccos(np.cos(x1 - np.reshape(x2, (-1, 1), order='F')))
min_N1_N2 = np.min([N1, N2])
index = np.zeros((min_N1_N2, 2), dtype=int)
if min_N1_N2 > 1:
for k in range(min_N1_N2):
d2 = np.min(diffmat, axis=0)
index2 = np.argmin(diffmat, axis=0)
index1 = np.argmin(d2)
index2 = index2[index1]
index[k, :] = [index1, index2]
diffmat[index2, :] = float('inf')
diffmat[:, index1] = float('inf')
d = np.mean(np.arccos(np.cos(x1[:, index[:, 0]] - x2[:, index[:, 1]])))
else:
d = np.min(diffmat)
index = np.argmin(diffmat)
if N1 == 1:
index = np.array([1, index])
else:
index = np.array([index, 1])
return d, index
示例13: _calc_min
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import argmin [as 别名]
def _calc_min(self) -> float:
return self._values[np.argmin(self._values)]
示例14: _calc_around_min
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import argmin [as 别名]
def _calc_around_min(self, num_around: int) -> float:
min_idx = np.argmin(self._values)
num_back = min_idx - num_around
if num_back < 0:
num_back = 0
num_forward = min_idx + num_around
if num_forward > len(self._values) - 1:
num_forward = len(self._values) - 1
return np.mean(self._values[num_back: num_forward])
示例15: curve_intersection
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import argmin [as 别名]
def curve_intersection(c1, c2, grid=16):
'''
curve_intersect(c1, c2) yields the parametric distances (t1, t2) such that c1(t1) == c2(t2).
The optional parameter grid may specify the number of grid-points
to use in the initial search for a start-point (default: 16).
'''
from scipy.optimize import minimize
from neuropythy.geometry import segment_intersection_2D
if c1.coordinates.shape[1] > c2.coordinates.shape[1]:
(t1,t2) = curve_intersection(c2, c1, grid=grid)
return (t2,t1)
# before doing a search, see if there are literal exact intersections of the segments
x1s = c1.coordinates.T
x2s = c2.coordinates
for (ts,te,xs,xe) in zip(c1.t[:-1], c1.t[1:], x1s[:-1], x1s[1:]):
pts = segment_intersection_2D((xs,xe), (x2s[:,:-1], x2s[:,1:]))
ii = np.where(np.isfinite(pts[0]))[0]
if len(ii) > 0:
ii = ii[0]
def f(t): return np.sum((c1(t[0]) - c2(t[1]))**2)
t01 = 0.5*(ts + te)
t02 = 0.5*(c2.t[ii] + c2.t[ii+1])
(t1,t2) = minimize(f, (t01, t02)).x
return (t1,t2)
if pimms.is_vector(grid): (ts1,ts2) = [c.t[0] + (c.t[-1] - c.t[0])*grid for c in (c1,c2)]
else: (ts1,ts2) = [np.linspace(c.t[0], c.t[-1], grid) for c in (c1,c2)]
(pts1,pts2) = [c(ts) for (c,ts) in zip([c1,c2],[ts1,ts2])]
ds = np.sqrt([np.sum((pts2.T - pp)**2, axis=1) for pp in pts1.T])
(ii,jj) = np.unravel_index(np.argmin(ds), ds.shape)
(t01,t02) = (ts1[ii], ts2[jj])
ttt = []
def f(t): return np.sum((c1(t[0]) - c2(t[1]))**2)
(t1,t2) = minimize(f, (t01, t02)).x
return (t1,t2)