本文整理匯總了Python中numpy.argwhere方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.argwhere方法的具體用法?Python numpy.argwhere怎麽用?Python numpy.argwhere使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.argwhere方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: format_mask
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argwhere [as 別名]
def format_mask(x):
"""
Formats a mask into a readable string.
Args:
x (ndarray): an array with the mask;
Returns:
A readable string with the mask.
"""
x = numpy.asanyarray(x)
if len(x) == 0:
return "(empty)"
if x.dtype == bool:
x = numpy.argwhere(x)[:, 0]
grps = tuple(list(g) for _, g in groupby(x, lambda n, c=count(): n-next(c)))
return ",".join("{:d}-{:d}".format(i[0], i[-1]) if len(i) > 1 else "{:d}".format(i[0]) for i in grps)
示例2: add_intercept
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argwhere [as 別名]
def add_intercept(self, X):
"""Add 1's to data as last features."""
# Data shape
N, D = X.shape
# Check if there's not already an intercept column
if np.any(np.sum(X, axis=0) == N):
# Report
print('Intercept is not the last feature. Swapping..')
# Find which column contains the intercept
intercept_index = np.argwhere(np.sum(X, axis=0) == N)
# Swap intercept to last
X = X[:, np.setdiff1d(np.arange(D), intercept_index)]
# Add intercept as last column
X = np.hstack((X, np.ones((N, 1))))
# Append column of 1's to data, and increment dimensionality
return X, D+1
示例3: test
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argwhere [as 別名]
def test(imgL,imgR,disp_true):
model.eval()
imgL = Variable(torch.FloatTensor(imgL))
imgR = Variable(torch.FloatTensor(imgR))
if args.cuda:
imgL, imgR = imgL.cuda(), imgR.cuda()
with torch.no_grad():
output3 = model(imgL,imgR)
pred_disp = output3.data.cpu()
#computing 3-px error#
true_disp = disp_true
index = np.argwhere(true_disp>0)
disp_true[index[0][:], index[1][:], index[2][:]] = np.abs(true_disp[index[0][:], index[1][:], index[2][:]]-pred_disp[index[0][:], index[1][:], index[2][:]])
correct = (disp_true[index[0][:], index[1][:], index[2][:]] < 3)|(disp_true[index[0][:], index[1][:], index[2][:]] < true_disp[index[0][:], index[1][:], index[2][:]]*0.05)
torch.cuda.empty_cache()
return 1-(float(torch.sum(correct))/float(len(index[0])))
示例4: lowdinPop
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argwhere [as 別名]
def lowdinPop(mol,coeff,ova,enorb,occ):
print '\nLowdin population for LMOs:'
nb,nc = coeff.shape
s12 = sqrtm(ova)
lcoeff = s12.dot(coeff)
diff = reduce(numpy.dot,(lcoeff.T,lcoeff)) - numpy.identity(nc)
print 'diff=',numpy.linalg.norm(diff)
pthresh = 0.05
labels = mol.ao_labels(None)
nelec = 0.0
for iorb in range(nc):
vec = lcoeff[:,iorb]**2
idx = list(numpy.argwhere(vec>pthresh))
print ' iorb=',iorb,' occ=',occ[iorb],' <i|F|i>=',enorb[iorb]
for iao in idx:
print ' iao=',labels[iao],' pop=',vec[iao]
nelec += occ[iorb]
print 'nelec=',nelec
return 0
示例5: precond
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argwhere [as 別名]
def precond(r, e0, x0):
idx = numpy.argwhere(abs(x0)>.1).ravel()
#idx = numpy.arange(20)
m = idx.size
if m > 2:
h0 = a[idx][:,idx] - numpy.eye(m)*e0
h0x0 = x0 / (a.diagonal() - e0)
h0x0[idx] = numpy.linalg.solve(h0, h0x0[idx])
h0r = r / (a.diagonal() - e0)
h0r[idx] = numpy.linalg.solve(h0, r[idx])
e1 = numpy.dot(x0, h0r) / numpy.dot(x0, h0x0)
x1 = (r - e1*x0) / (a.diagonal() - e0)
x1[idx] = numpy.linalg.solve(h0, (r-e1*x0)[idx])
return x1
else:
return r / (a.diagonal() - e0)
示例6: calculate_ranking_metrics
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argwhere [as 別名]
def calculate_ranking_metrics(triplets, scores, true_relations):
for i in range(scores.shape[0]):
head, tail, relation = triplets[i]
for j in true_relations[head, tail] - {relation}:
scores[i, j] -= 1.0
sorted_indices = np.argsort(-scores, axis=1)
relations = np.array(triplets)[0:scores.shape[0], 2]
sorted_indices -= np.expand_dims(relations, 1)
zero_coordinates = np.argwhere(sorted_indices == 0)
rankings = zero_coordinates[:, 1] + 1
mrr = float(np.mean(1 / rankings))
mr = float(np.mean(rankings))
hit1 = float(np.mean(rankings <= 1))
hit3 = float(np.mean(rankings <= 3))
hit5 = float(np.mean(rankings <= 5))
return mrr, mr, hit1, hit3, hit5
示例7: getHistory
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argwhere [as 別名]
def getHistory(self,vehId,t,refVehId,dsId):
if vehId == 0:
return np.empty([0,2])
else:
if self.T.shape[1]<=vehId-1:
return np.empty([0,2])
refTrack = self.T[dsId-1][refVehId-1].transpose()
vehTrack = self.T[dsId-1][vehId-1].transpose()
refPos = refTrack[np.where(refTrack[:,0]==t)][0,1:3]
if vehTrack.size==0 or np.argwhere(vehTrack[:, 0] == t).size==0:
return np.empty([0,2])
else:
stpt = np.maximum(0, np.argwhere(vehTrack[:, 0] == t).item() - self.t_h)
enpt = np.argwhere(vehTrack[:, 0] == t).item() + 1
hist = vehTrack[stpt:enpt:self.d_s,1:3]-refPos
if len(hist) < self.t_h//self.d_s + 1:
return np.empty([0,2])
return hist
## Helper function to get track future
示例8: point_cloud_to_sem_vox
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argwhere [as 別名]
def point_cloud_to_sem_vox(pt, sem_label, vs=0.06,xymin=-3.84, xymax=3.84, zmin=-0.2, zmax=2.68):
pt[:,0]=pt[:,0]-xymin
pt[:,1]=pt[:,1]-xymin
pt[:,2]=pt[:,2]-zmin
pt=pt/vs
vxy=int((xymax-xymin)/vs)
vz = int((zmax-zmin)/vs)
pt = np.clip(pt, 0,vxy-1)
pt[:,2] = np.clip(pt[:,2], 0,vz-1)
vol=np.zeros((vxy,vxy,vz), np.float32)
pt = pt.astype(np.int32)
for i in range(pt.shape[0]):
if sem_label[i] not in choose_classes:
continue
vol[pt[i,0], pt[i,1], pt[i,2]]=np.argwhere(choose_classes==sem_label[i])[0,0]+1
return vol
示例9: VOCap
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argwhere [as 別名]
def VOCap(rec,prec):
mpre = np.zeros([1,2+len(prec)])
mpre[0,1:len(prec)+1] = prec
mrec = np.zeros([1,2+len(rec)])
mrec[0,1:len(rec)+1] = rec
mrec[0,len(rec)+1] = 1.0
for i in range(mpre.size-2,-1,-1):
mpre[0,i] = max(mpre[0,i],mpre[0,i+1])
i = np.argwhere( ~np.equal( mrec[0,1:], mrec[0,:mrec.shape[1]-1]) )+1
i = i.flatten()
# compute area under the curve
ap = np.sum( np.multiply( np.subtract( mrec[0,i], mrec[0,i-1]), mpre[0,i] ) )
return ap
示例10: _points_next_to_surface
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argwhere [as 別名]
def _points_next_to_surface(self, surf, modes, pivot):
""" Searches for points within a distance self.tau from the
interface.
"""
pivot_pos = self.cluster_group[pivot].positions
z_max = np.max(pivot_pos[:, 2])
z_min = np.min(pivot_pos[:, 2])
z_max += self.alpha * 2
z_min -= self.alpha * 2
positions = self.cluster_group.positions[:]
# TODO other directions
z = positions[:, 2]
condition = np.logical_and(z > z_min, z < z_max)
candidates = np.argwhere(condition)[:, 0]
dists = surf.surface_from_modes(positions[candidates], modes)
dists = dists - z[candidates]
return candidates[dists * dists < self.tau**2]
示例11: _tojson
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argwhere [as 別名]
def _tojson(*numpy_objs):
'''Utility function which returns a list where each element of numpy_objs
is converted to its python equivalent (float or list)'''
ret = []
# problem: browsers might not be happy with JSON 'NAN', so convert
# NaNs to None. Unfortunately, the conversion must be done element wise
# in numpy (seems not to exist a pandas na filter):
for obj in numpy_objs:
isscalar = np.isscalar(obj)
nan_indices = None if isscalar else \
np.argwhere(np.isnan(obj)).flatten()
# note: numpy.float64(N).tolist() returns a python float, so:
obj = None if isscalar and np.isnan(obj) else obj.tolist()
if nan_indices is not None:
for idx in nan_indices:
obj[idx] = None
ret.append(obj)
return ret # tuple(_.tolist() for _ in numpy_objs)
示例12: _matvec_numpy
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argwhere [as 別名]
def _matvec_numpy(self, x):
x = x.reshape(self.dims)
y = np.zeros(self.dimsd, dtype=self.dtype)
for it in range(self.dims[1]):
for ix0 in range(self.dims[0]):
if self.usetable:
indices = self.table[ix0, it]
if self.interp:
dindices = self.dtable[ix0, it]
else:
if self.interp:
indices, dindices = self.fh(ix0, it)
else:
indices = self.fh(ix0, it)
mask = np.argwhere(~np.isnan(indices))
if mask.size > 0:
indices = (indices[mask]).astype(np.int)
if not self.interp:
y[mask, indices] += x[ix0, it]
else:
y[mask, indices] += (1-dindices[mask])*x[ix0, it]
y[mask, indices + 1] += dindices[mask] * x[ix0, it]
return y.ravel()
示例13: _rmatvec_numpy
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argwhere [as 別名]
def _rmatvec_numpy(self, x):
x = x.reshape(self.dimsd)
y = np.zeros(self.dims, dtype=self.dtype)
for it in range(self.dims[1]):
for ix0 in range(self.dims[0]):
if self.usetable:
indices = self.table[ix0, it]
if self.interp:
dindices = self.dtable[ix0, it]
else:
if self.interp:
indices, dindices = self.fh(ix0, it)
else:
indices = self.fh(ix0, it)
mask = np.argwhere(~np.isnan(indices))
if mask.size > 0:
indices = (indices[mask]).astype(np.int)
if not self.interp:
y[ix0, it] = np.sum(x[mask, indices])
else:
y[ix0, it] = \
np.sum(x[mask, indices]*(1-dindices[mask])) + \
np.sum(x[mask, indices+1]*dindices[mask])
return y.ravel()
示例14: find_points
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argwhere [as 別名]
def find_points(mask, x_shift=0, y_shift=0):
# Find points where mask change class on edges
mask = mask > 0
mask = mask.astype(np.int)
n = mask.shape[1]
edges = [mask[:, 0+x_shift], mask[:, -1-x_shift],
mask[0+y_shift, :], mask[-1-y_shift, :]]
diffs = [np.diff(edge, n=1) for edge in edges]
pos = [np.argwhere(diff>0)+1 for diff in diffs]
neg = [np.argwhere(diff<0)+1 for diff in diffs]
pos = [[int(x) for x in p] for p in pos]
neg = [[int(x) for x in n] for n in neg]
if mask[0, 0] > 0:
for i in [left, top]:
pos[i] = [0] + pos[i]
if mask[-1, 0] > 0:
pos[bottom] = [0] + pos[bottom]
neg[left] = [n] + neg[left]
if mask[0, -1] > 0:
pos[right] = [0] + pos[right]
neg[top] = [n] + neg[top]
if mask[-1, -1] > 0:
for i in [right, bottom]:
neg[i] = [n] + neg[i]
return(pos, neg)
示例15: timeIndex
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import argwhere [as 別名]
def timeIndex(self, slider):
## Return the time and frame index indicated by a slider
if self.image is None:
return (0,0)
t = slider.value()
xv = self.tVals
if xv is None:
ind = int(t)
else:
if len(xv) < 2:
return (0,0)
totTime = xv[-1] + (xv[-1]-xv[-2])
inds = np.argwhere(xv < t)
if len(inds) < 1:
return (0,t)
ind = inds[-1,0]
return ind, t