本文整理汇总了Python中numpy.argwhere函数的典型用法代码示例。如果您正苦于以下问题:Python argwhere函数的具体用法?Python argwhere怎么用?Python argwhere使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了argwhere函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Simulate
def Simulate(self, T):
self.T = T
x = np.zeros((self.N, self.T), dtype=int)
v = np.zeros((self.N, self.T), dtype=int)
Q = np.zeros((self.N, self.T), dtype=int)
x[:,0] = self.x0
v[:,0] = self.v0
for t in range(1,self.T):
X = np.argwhere(x[:,t-1]==1)[:,0]
dX = (np.roll(X, -1)-X)%self.N
V = v[X, t-1]
#Rule 1: Accelerate if possible
V += np.logical_and(V<np.ones(len(V))*self.vmax,V<(dX+1))
#Rule 2: Slow down if needed
ind = np.argwhere(dX<=V)[:,0]
V[ind] = dX[ind]-1
#Rule 3: Slow down with chance p
V -= np.logical_and(np.random.rand(len(V))<0.5, 0<V)
#Rule 4: Take next time step
x[(X+V)%self.N, t] = 1
v[(X+V)%self.N, t] = V
#Obtain the flow at each position
for i, xi in enumerate(X):
Q[xi:(xi+V[i])%self.N,t] +=1
self.X = x
self.V = v
self.Q = Q
示例2: gain_ratio
def gain_ratio(examples, attribute):
"Returns the gain function for one attribute."
ent = h(examples)
remainder = 0
values = examples[:, attribute]
for v in value_attrs[attribute]:
exs_idx = np.argwhere(values == v).flatten()
count_v = len(exs_idx)
exs = examples[exs_idx]
if count_v != 0:
remainder += float(count_v)/len(examples) * h(exs)
ig = ent - remainder
iv = 0
for v in value_attrs[attribute]:
exs_idx = np.argwhere(values == v).flatten()
count_v = len(exs_idx)
exs = examples[exs_idx]
if count_v != 0:
iv -= float(count_v)/len(examples) * np.log2(float(count_v)/len(examples))
if iv > 1e-6:
return ig/iv
else:
return ig/1e-6
开发者ID:lb5160482,项目名称:Machine-Learning-Classifier-Artificial-Intelligence,代码行数:25,代码来源:decision_tree.py
示例3: crop_data
def crop_data(bg, overlay):
'''
Crop the data to get ride of large amounts of black space surrounding the
background image.
'''
#---------------------------------------------------------------
# First find all the slices that contain data you want
slices_list_x = list(np.argwhere(np.sum(bg, (1,2)) != 0)[:,0])
slices_list_y = list(np.argwhere(np.sum(bg, (0,2)) != 0)[:,0])
slices_list_z = list(np.argwhere(np.sum(bg, (0,1)) != 0)[:,0])
slices_list = [slices_list_x, slices_list_y, slices_list_z]
#---------------------------------------------------------------
# Make a copy of the data
bg_cropped = np.copy(bg)
overlay_cropped = np.copy(overlay)
#---------------------------------------------------------------
# Remove all slices that have no data in the background image
bg_cropped = bg_cropped[ slices_list_x, :, : ]
overlay_cropped = overlay_cropped[ slices_list_x, :, : ]
bg_cropped = bg_cropped[ :, slices_list_y, : ]
overlay_cropped = overlay_cropped[ :, slices_list_y, : ]
bg_cropped = bg_cropped[ :, :, slices_list_z ]
overlay_cropped = overlay_cropped[ :, :, slices_list_z ]
return bg_cropped, overlay_cropped, slices_list
示例4: sar
def sar(el2no):
"""
extract spatial difference matrix on the neighbores of each element
in 2D fem using triangular mesh.
Parameters
----------
el2no : NDArray
triangle structures
Returns
-------
NDArray
SAR matrix
"""
ne = el2no.shape[0]
L = np.eye(ne)
for i in range(ne):
ei = el2no[i, :]
#
i0 = np.argwhere(el2no == ei[0])[:, 0]
i1 = np.argwhere(el2no == ei[1])[:, 0]
i2 = np.argwhere(el2no == ei[2])[:, 0]
idx = np.unique(np.hstack([i0, i1, i2]))
# build row-i
for j in idx:
L[i, j] = -1
nn = idx.size - 1
L[i, i] = nn
return L
示例5: to_js
def to_js(fname,low=-3,high=3,template_file='template.js'):
name,suffix=fname.split('.')
im=Image.open(fname).convert('1')
mat=np.array(get_mat(im))
d1=np.argwhere(np.diff(mat.all(axis=1)))
d1min=np.min(d1)
d1max=np.max(d1)
d2=np.argwhere(np.diff(mat.all(axis=0)))
d2min=np.min(d2)
d2max=np.max(d2)
d1_scale=Scale([d1min,d1max],[low,high])
d2_scale=Scale([d2min,d2max],[high,low])
l=[]
for i in range(mat.shape[0]):
for j in range(mat.shape[1]):
if mat[(i,j)]==0:
l.append([d1_scale(i),d2_scale(j)])
with open(template_file) as f:
s=f.read()
template=jinja2.Template(s)
ss=template.render(name=name+'Graph',point_list=l)
with open(name+'.js','w') as f:
f.write(ss)
#xScale=scale([0,206],[-5,5])
#yScale=scale([0,195],[-5,5])
示例6: rmNanAndOutliers
def rmNanAndOutliers():
"""Plot without NAN and outliers from selected pen.
"""
if len(ds.EpmDatasetAnalysisPens.SelectedPens) < 1:
sr.msgBox('EPM Python Plugin - Demo Tools', 'Please select a single pen before applying this function!', 'Warning')
return 0
sd = 6
epmData = ds.EpmDatasetAnalysisPens.SelectedPens[0].values
y = epmData['Value']
t = epmData['Timestamp']
nanPos = np.argwhere(np.isnan(y))
y = np.delete(y,nanPos)
t = np.delete(t,nanPos)
s3 = np.floor(sd * np.sqrt(y.std()))
smin = y.mean() - s3
smax = y.mean() + s3
outPos = np.argwhere(y<smin)
y = np.delete(y,outPos)
t = np.delete(t,outPos)
outPos = np.argwhere(y>smax)
y = np.delete(y,outPos)
t = np.delete(t,outPos)
res = vec2epm(t,y)
penName = ds.EpmDatasetAnalysisPens.SelectedPens[0].name + '_NoOutliers'
sr.plot(penName, res)
return res
示例7: integralsChanged
def integralsChanged(self):
self.integralLimits = []
for row in range(self.integralTable.rowCount()-1):
if self.integralTable.item(row, 0) \
and self.integralTable.item(row, 1):
try:
limit_1 = float(self.integralTable.item(row, 0).text())
limit_2 = float(self.integralTable.item(row, 1).text())
self.integralLimits.append(
[row, min([limit_1, limit_2]), max([limit_1, limit_2])])
except ValueError:
pass
if not self.integralLimits or not self.qvals:
return
self.integralPlotWindow.clearCurves()
for limit in self.integralLimits:
yint = []
xint = []
for i, qval in enumerate(self.qvals):
xint.append(qval)
if self.integralMethodIntegral.isChecked():
yint.append(self.yvals[i][
np.argwhere(self.xvals[i]>=limit[1])[0][0]: \
np.argwhere(self.xvals[i]<=limit[2])[-1][0]].sum())
else:
yint.append(self.yvals[i][
np.argwhere(self.xvals[i]>=limit[1])[0][0]: \
np.argwhere(self.xvals[i]<=limit[2])[-1][0]].mean())
int2plot = np.vstack([xint, yint]).T
int2plot = int2plot[int2plot[:,0].argsort()]
self.integralPlotWindow.addCurve(int2plot[:,0], int2plot[:,1],
legend='Region %d' % (limit[0]+1), ylabel=' ',
symbol='o')
return
示例8: dfsi
def dfsi(bitmap):
#startpixel = [bitmapnonzero.item(0, 0), bitmapnonzero.item(0, 1)]
startrow = 0
while True:
scanline = bitmap[startrow, :]
if np.any(scanline):
startcol = np.argwhere(scanline)[0, 0]
break
startrow += 1
startpixel = [startrow, startcol]
#print startpixel
stack = [startpixel]
objpix = [startpixel]
bound = False
while stack:
row, col = stack.pop()
if row == 0 or col == 0: bound = True
edges = np.argwhere(bitmap[row-1:row+2, col-1:col+2]) - [1, 1]
for edge in edges:
nextpixel = [row+edge[0], col+edge[1]]
if nextpixel not in objpix:
stack += [nextpixel]
objpix += [nextpixel]
[bitmap.itemset((pix[0], pix[1]), False) for pix in objpix]
if bound: return [], bitmap
else: return objpix, bitmap
示例9: multivariate_initialize_seed
def multivariate_initialize_seed(CAC, from_gt=True):
image = CAC.image_obj.image
if from_gt:
print 'Seed from ground truth...'
inside_mask_seed = CAC.ground_truth_obj
outside_mask_seed = CAC.ground_truth_obj
else:
center = CAC.mask_obj.center
radius_point = CAC.mask_obj.radius_point
print 'CENTER:', center
print 'RADIUS POINT:', radius_point
print 'RADIUS:', np.linalg.norm(np.array(radius_point) - np.array(center))
radius = np.linalg.norm(np.array(radius_point) - np.array(center))
inside_seed_omega = [center[0] + radius * 0.2, center[1]]
outside_seed_omega = [center[0] + radius * 1.8, center[1]]
inside_mask_seed = MaskClass()
outside_mask_seed = MaskClass()
inside_mask_seed.from_points_and_image(center, inside_seed_omega, image)
outside_mask_seed.from_points_and_image(center, outside_seed_omega, image)
inside_seed = inside_mask_seed.mask
outside_seed = 255. - outside_mask_seed.mask
# inside_mask_seed.plot_image()
# CAC.mask_obj.plot_image()
# utils.printNpArray(outside_seed)
inside_coordinates = np.argwhere(inside_seed == 255.)
outside_coordinates = np.argwhere(outside_seed == 255.)
inside_gmm = get_values_in_region(inside_coordinates, image)
outside_gmm = get_values_in_region(outside_coordinates, image)
return inside_gmm, outside_gmm
示例10: psf
def psf(self,emin,emax,cthmin,cthmax):
"""Return energy- and livetime-weighted PSF density vector as
a function of angular offset for a bin in energy and
inclination angle."""
logemin = np.log10(emin)
logemax = np.log10(emax)
ilo = np.argwhere(self._energy > emin)[0,0]
ihi = np.argwhere(self._energy < emax)[-1,0]+1
jlo = np.argwhere(self._ctheta_axis.center > cthmin)[0,0]
jhi = np.argwhere(self._ctheta_axis.center < cthmax)[-1,0] +1
weights = (self._energy[ilo:ihi,np.newaxis]*
self._exp[ilo:ihi,jlo:jhi]*
self._wfn(self._energy[ilo:ihi,np.newaxis]))
wsum = np.sum(weights)
psf = np.apply_over_axes(np.sum,
self._psf[:,ilo:ihi,jlo:jhi]*
weights[np.newaxis,...],
[1,2])
psf = np.squeeze(psf)
psf *= (1./wsum)
return self._dtheta, psf
示例11: crop
def crop(self, img, edges, orig):
'''
Crops an image so that it is a rectangle
@npimg: an image to crop
@return: the cropped image
'''
#find the extents in the y direction
maxX = orig[0,...].max()
maxY = orig[1,...].max()
x1 = 0 - edges[0,0]
x2 = maxX - edges[1,0]
y1 = 0 - edges[0,1]
y2 = -(maxY - edges [1,1])
#slice the image in y direction
img = img[y1+1:img.shape[0]-y2-1]
#find the extents in the x direction
cropTop = numpy.argwhere(img[0,:,3]!=0)
cropBot = numpy.argwhere(img[-1,:,3]!=0)
minT = cropTop.min()
maxT = cropTop.max()
minB = cropBot.min()
maxB = cropBot.max()
#grab the correct extents
xMin = max(minT,minB)
xMax = min(maxT,maxB)
#slice the image in x direction
img = img[:,xMin:xMax]
return img
示例12: test_binary_classsification_should_out_row_vector_of_0_1_only
def test_binary_classsification_should_out_row_vector_of_0_1_only(self):
model = Model([np.random.rand(4, 6), np.random.rand(1, 5)])
prediction = model.predict_binary_classification(np.random.rand(10, 5))
self.assertEqual(prediction.shape, (10, 1))
zeros = len(np.argwhere(prediction == 0))
ones = len(np.argwhere(prediction == 1))
self.assertEqual(zeros + ones, 10)
示例13: np_combine_rare
def np_combine_rare(Xtrain, Xtest, col_list = list(), rare_line=1):
if Xtrain.shape[1] != Xtest.shape[1]:
print 'Xtrain, Xtest shape not match.'
return
if not col_list :
col_list = range(Xtrain.shape[1])
check_int = True
else:
check_int = False
n_train = Xtrain.shape[0]
for col in col_list:
col_data_train = Xtrain[:, col]
col_data_test = Xtest[:, col]
col_data = np.hstack((col_data_train, col_data_test))
# print col_data[0]
if issubclass(col_data.dtype.type, np.integer) or (not check_int):
le = preprocessing.LabelEncoder()
le.fit(col_data)
col_data = le.transform(col_data)
max_label = np.amax(col_data)
counts = np.bincount(col_data)
rare_cats = np.argwhere(counts <= rare_line)
rare_cats = rare_cats.reshape(rare_cats.shape[0])
rare_positions = [np.argwhere(col_data == rare_cat)[0,0] for rare_cat in rare_cats]
# print len(rare_positions)
col_data[rare_positions] = max_label+1
Xtrain[:, col] = col_data[:n_train]
Xtest[:, col] = col_data[n_train:]
else:
print 'col:{0:d} not integer'.format(col)
示例14: findValidFFTWDim
def findValidFFTWDim( inputDims ):
"""
Finds a valid dimension for which FFTW can optimize its calculations. The
return is a shape which is forced to be square, as this gives uniform pixel
size in x-y in Fourier space.
If you want a minimum padding size, call as findValidFFTWDim( image.shape + 128 )
or similar.
"""
dim = np.max( np.round( inputDims ) )
maxPow2 = np.int( np.ceil( math.log( dim, 2 ) ) )
maxPow3 = np.int( np.ceil( math.log( dim, 3 ) ) )
maxPow5 = np.int( np.ceil( math.log( dim, 5 ) ) )
maxPow7 = np.int( np.ceil( math.log( dim, 7 ) ) )
dimList = np.zeros( [(maxPow2+1)*(maxPow3+1)*(maxPow5+1)*(maxPow7+1)] )
count = 0
for I in np.arange(0,maxPow7+1):
for J in np.arange(0,maxPow5+1):
for K in np.arange(0,maxPow3+1):
for L in np.arange(0,maxPow2+1):
dimList[count] = 2**L * 3**K * 5**J * 7**I
count += 1
dimList = np.sort( np.unique( dimList ) )
dimList = dimList[ np.argwhere(dimList < 2*dim)].squeeze()
dimList = dimList.astype('int64')
# Throw out odd image shapes, this just causes more problems with many
# functions
dimList = dimList[ np.mod(dimList,2)==0 ]
# Find first dim that equals or exceeds dim
nextValidDim = dimList[np.argwhere( dimList >= dim)[0,0]]
return np.array( [nextValidDim, nextValidDim] )
示例15: fwhm
def fwhm(array):
"""
Computes the full width half maximum of a 1-d array
Returns the indices of the array elements left and right closest to the
maximum that cross below half the maximum value
"""
assert (type(array) == type(np.ndarray([])))
# Find the maximum in the interior of the array
fwhm = 0.5 * array[1:-1].max()
max_idx = array[1:-1].argmax() + 1
# Divide the intervall in halfs at the peak and find the index of the
# value in the left half of the intervall before it increases over max/2
# The FWHM is between the indices closest to the maximum, whose values
# are below 0.5 times the max
try:
left_idx = np.argwhere(array[1: max_idx] < fwhm)[-1] + 1
except IndexError:
# This can occurs if there is no value in the array smaller than
# 0.5*max.
# In this case, return the left limit of the array as the FWHM.
left_idx = 0
try:
right_idx = np.argwhere(array[max_idx:-1] < fwhm)[0] + max_idx
except IndexError:
# Subtract one because the index of an array with size n is
# within 0..n-1
right_idx = array.size() - 1
return np.array([int(left_idx), int(right_idx)])