本文整理汇总了Python中numpy.nanargmax函数的典型用法代码示例。如果您正苦于以下问题:Python nanargmax函数的具体用法?Python nanargmax怎么用?Python nanargmax使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了nanargmax函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_reductions_2D_int
def test_reductions_2D_int():
x = np.arange(1, 122).reshape((11, 11)).astype('i4')
a = da.from_array(x, chunks=(4, 4))
reduction_2d_test(da.sum, a, np.sum, x)
reduction_2d_test(da.prod, a, np.prod, x)
reduction_2d_test(da.mean, a, np.mean, x)
reduction_2d_test(da.var, a, np.var, x, False) # Difference in dtype algo
reduction_2d_test(da.std, a, np.std, x, False) # Difference in dtype algo
reduction_2d_test(da.min, a, np.min, x, False)
reduction_2d_test(da.max, a, np.max, x, False)
reduction_2d_test(da.any, a, np.any, x, False)
reduction_2d_test(da.all, a, np.all, x, False)
reduction_2d_test(da.nansum, a, np.nansum, x)
with ignoring(AttributeError):
reduction_2d_test(da.nanprod, a, np.nanprod, x)
reduction_2d_test(da.nanmean, a, np.mean, x)
reduction_2d_test(da.nanvar, a, np.nanvar, x, False) # Difference in dtype algo
reduction_2d_test(da.nanstd, a, np.nanstd, x, False) # Difference in dtype algo
reduction_2d_test(da.nanmin, a, np.nanmin, x, False)
reduction_2d_test(da.nanmax, a, np.nanmax, x, False)
assert eq(da.argmax(a, axis=0), np.argmax(x, axis=0))
assert eq(da.argmin(a, axis=0), np.argmin(x, axis=0))
assert eq(da.nanargmax(a, axis=0), np.nanargmax(x, axis=0))
assert eq(da.nanargmin(a, axis=0), np.nanargmin(x, axis=0))
assert eq(da.argmax(a, axis=1), np.argmax(x, axis=1))
assert eq(da.argmin(a, axis=1), np.argmin(x, axis=1))
assert eq(da.nanargmax(a, axis=1), np.nanargmax(x, axis=1))
assert eq(da.nanargmin(a, axis=1), np.nanargmin(x, axis=1))
示例2: test_reductions_1D
def test_reductions_1D(dtype):
x = np.arange(5).astype(dtype)
a = da.from_array(x, chunks=(2,))
reduction_1d_test(da.sum, a, np.sum, x)
reduction_1d_test(da.prod, a, np.prod, x)
reduction_1d_test(da.mean, a, np.mean, x)
reduction_1d_test(da.var, a, np.var, x)
reduction_1d_test(da.std, a, np.std, x)
reduction_1d_test(da.min, a, np.min, x, False)
reduction_1d_test(da.max, a, np.max, x, False)
reduction_1d_test(da.any, a, np.any, x, False)
reduction_1d_test(da.all, a, np.all, x, False)
reduction_1d_test(da.nansum, a, np.nansum, x)
with ignoring(AttributeError):
reduction_1d_test(da.nanprod, a, np.nanprod, x)
reduction_1d_test(da.nanmean, a, np.mean, x)
reduction_1d_test(da.nanvar, a, np.var, x)
reduction_1d_test(da.nanstd, a, np.std, x)
reduction_1d_test(da.nanmin, a, np.nanmin, x, False)
reduction_1d_test(da.nanmax, a, np.nanmax, x, False)
assert eq(da.argmax(a, axis=0), np.argmax(x, axis=0))
assert eq(da.argmin(a, axis=0), np.argmin(x, axis=0))
assert eq(da.nanargmax(a, axis=0), np.nanargmax(x, axis=0))
assert eq(da.nanargmin(a, axis=0), np.nanargmin(x, axis=0))
assert eq(da.argmax(a, axis=0, split_every=2), np.argmax(x, axis=0))
assert eq(da.argmin(a, axis=0, split_every=2), np.argmin(x, axis=0))
assert eq(da.nanargmax(a, axis=0, split_every=2), np.nanargmax(x, axis=0))
assert eq(da.nanargmin(a, axis=0, split_every=2), np.nanargmin(x, axis=0))
示例3: dynamic
def dynamic(quality_matrix):
size = quality_matrix.shape[0]
optimal_score = np.empty(size)
optimal_score.fill(-np.inf)
optimal_score[0] = 0
previous_end = np.empty(size)
previous_end.fill(-1)
domain_defining = np.empty(size)
np.set_printoptions(threshold=np.nan)
for i in range(size):
cand_nodomain = np.nanargmax(optimal_score)
with_domain = optimal_score + quality_matrix[:, i]
cand_domain = np.nanargmax(with_domain)
if optimal_score[cand_nodomain] > with_domain[cand_domain]:
domain_defining[i] = 0
previous_end[i] = cand_nodomain
optimal_score[i] = optimal_score[cand_nodomain]
else:
domain_defining[i] = 1
previous_end[i] = cand_domain
optimal_score[i] = with_domain[cand_domain]
current_end = size - 2
result = []
while current_end > 0:
if domain_defining[current_end] == 1:
result.append(Domain(Bin(previous_end[current_end]), Bin(current_end), 0))
current_end = previous_end[current_end]
return result[::-1]
示例4: predict_ana
def predict_ana( model, a, a2, b, realb2 ):
questWordIndices = [ model.word2id[x] for x in (a,a2,b) ]
# b2 is effectively iterating through the vocab. The row is all the cosine values
b2a2 = model.sim_row(a2)
b2a = model.sim_row(a)
b2b = model.sim_row(b)
addsims = b2a2 - b2a + b2b
addsims[questWordIndices] = -10000
iadd = np.nanargmax(addsims)
b2add = model.vocab[iadd]
# For debugging purposes
ia = model.word2id[a]
ia2 = model.word2id[a2]
ib = model.word2id[b]
ib2 = model.word2id[realb2]
realaddsim = addsims[ib2]
mulsims = ( b2a2 + 1 ) * ( b2b + 1 ) / ( b2a + 1.001 )
mulsims[questWordIndices] = -10000
imul = np.nanargmax(mulsims)
b2mul = model.vocab[imul]
return b2add, b2mul
示例5: extract_stamp
def extract_stamp(im, xy, box_size):
""" Extracts stamp centered on star/spot in image based on initial guess
Args:
image - a slice of the original data cube
xy - initial xy coordinate guess to center of spot
box_size - size of stamp to be extracted (actually, size of radial mask, box is 4 pixels bigger)
Return:
output - box cutout of spot with optimized center
"""
box_size = float(box_size)
xguess = float(xy[0])
yguess = float(xy[1])
#Exctracts a 10px stamp centered on the guess and refines based on maximum pixel location
for i in range(0, 2):
x,y = gen_xy(10.0)
x += (xguess-10/2.)
y += (yguess-10/2.)
output = pixel_map(im,x,y)
xguess = x[np.unravel_index(np.nanargmax(output), np.shape(output))]
yguess = y[np.unravel_index(np.nanargmax(output), np.shape(output))]
#Fits location of star/spot
xc,yc = return_pos(output, (xguess,yguess), x,y)
#Extracts a box_size + 4 width stamp centered on exact position
x,y = gen_xy(box_size+4)
x += (xc-np.round((box_size+4)/2.))
y += (yc-np.round((box_size+4)/2.))
output = pixel_map(im,x,y)
return output
示例6: max_pure_social_welfare
def max_pure_social_welfare(game, *, by_role=False):
"""Returns the maximum social welfare over the known profiles.
If by_role is specified, then max social welfare applies to each role
independently. If there are no profiles with full payoff data for a role,
an arbitrary profile will be returned."""
if by_role: # pylint: disable=no-else-return
if game.num_profiles: # pylint: disable=no-else-return
welfares = np.add.reduceat(
game.profiles() * game.payoffs(), game.role_starts, 1)
prof_inds = np.nanargmax(welfares, 0)
return (welfares[prof_inds, np.arange(game.num_roles)],
game.profiles()[prof_inds])
else:
welfares = np.full(game.num_roles, np.nan)
profiles = np.full(game.num_roles, None)
return welfares, profiles
else:
if game.num_complete_profiles: # pylint: disable=no-else-return
welfares = np.einsum('ij,ij->i', game.profiles(), game.payoffs())
prof_ind = np.nanargmax(welfares)
return welfares[prof_ind], game.profiles()[prof_ind]
else:
return np.nan, None
示例7: _single_node_deletion
def _single_node_deletion(self, chroms, genes, samples):
"""
The single node deletion routine of the algorithm.
Parameters
----------
chroms : ndarray
Contains 1 for a chromosome pair that belongs to the tricluster
currently examined, 0 otherwise.
genes : ndarray
Contains 1 for a gene that belongs to the tricluster currently
examined, 0 otherwise.
samples : ndarray
Contains 1 for a sample that belongs to the tricluster currently
examined, 0 otherwise.
Returns
-------
chroms : ndarray
Contains 1 for a chromosome pair that belongs to the tricluster
examined, 0 otherwise.
genes : ndarray
Contains 1 for a gene that belongs to the tricluster examined,
0 otherwise.
samples : ndarray
Contains 1 for a sample that belongs to the tricluster examined,
0 otherwise.
"""
self._compute_MSR(chroms, genes, samples)
while (self.MSR > self.delta):
chrom_idx = np.nanargmax(self.MSR_chrom)
gene_idx = np.nanargmax(self.MSR_gene)
sample_idx = np.nanargmax(self.MSR_sample)
with warnings.catch_warnings(): # We expect mean of NaNs here
warnings.simplefilter("ignore", category=RuntimeWarning)
if (self.MSR_chrom[chrom_idx] > self.MSR_gene[gene_idx]):
if (self.MSR_chrom[chrom_idx] > self.MSR_sample[sample_idx]):
# Delete chrom
nonz_idx = chroms.nonzero()[0]
chroms.put(nonz_idx[chrom_idx], 0)
else:
# Delete sample
nonz_idx = samples.nonzero()[0]
samples.put(nonz_idx[sample_idx], 0)
else:
if (self.MSR_gene[gene_idx] > self.MSR_sample[sample_idx]):
# Delete gene
nonz_idx = genes.nonzero()[0]
genes.put(nonz_idx[gene_idx], 0)
else:
# Delete sample
nonz_idx = samples.nonzero()[0]
samples.put(nonz_idx[sample_idx], 0)
self._compute_MSR(chroms, genes, samples)
return chroms, genes, samples
示例8: get_best_threshold
def get_best_threshold(y_ref, y_pred_score, plot=True):
""" Get threshold on scores that maximizes f1 score.
Parameters
----------
y_ref : array
Reference labels (binary).
y_pred_score : array
Predicted scores.
plot : bool
If true, plot ROC curve
Returns
-------
best_threshold : float
threshold on score that maximized f1 score
max_fscore : float
f1 score achieved at best_threshold
"""
pos_weight = 1.0 - float(len(y_ref[y_ref == 1]))/float(len(y_ref))
neg_weight = 1.0 - float(len(y_ref[y_ref == 0]))/float(len(y_ref))
sample_weight = np.zeros(y_ref.shape)
sample_weight[y_ref == 1] = pos_weight
sample_weight[y_ref == 0] = neg_weight
print "max prediction value = %s" % np.max(y_pred_score)
print "min prediction value = %s" % np.min(y_pred_score)
precision, recall, thresholds = \
metrics.precision_recall_curve(y_ref, y_pred_score, pos_label=1,
sample_weight=sample_weight)
beta = 1.0
btasq = beta**2.0
fbeta_scores = (1.0 + btasq)*(precision*recall)/((btasq*precision)+recall)
max_fscore = fbeta_scores[np.nanargmax(fbeta_scores)]
best_threshold = thresholds[np.nanargmax(fbeta_scores)]
if plot:
plt.figure(1)
plt.subplot(1, 2, 1)
plt.plot(recall, precision, '.b', label='PR curve')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.0])
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('Precision-Recall Curve')
plt.legend(loc="lower right", frameon=True)
plt.subplot(1, 2, 2)
plt.plot(thresholds, fbeta_scores[:-1], '.r', label='f1-score')
plt.xlabel('Probability Threshold')
plt.ylabel('F1 score')
plt.show()
plot_data = (recall, precision, thresholds, fbeta_scores[:-1])
return best_threshold, max_fscore, plot_data
示例9: mapmean
def mapmean(tempDF, meta, name = '', option = 0):
import cartopy.crs as ccrs
from cartopy.io.img_tiles import MapQuestOSM
from mpl_toolkits.axes_grid1 import make_axes_locatable
#fig = plt.figure(figsize=(30, 30))
x = meta['location:Longitude'].values
y = meta['location:Latitude'].values
c = tempDF[meta.index].mean()
marker_size = 350
imagery = MapQuestOSM()
fig = plt.figure(figsize=[15,15])
ax = plt.axes(projection=imagery.crs)
ax.set_extent(( meta['location:Longitude'].min()-.005,
meta['location:Longitude'].max()+.005 ,
meta['location:Latitude'].min()-.005,
meta['location:Latitude'].max()+.005))
ax.add_image(imagery, 14)
cmap = matplotlib.cm.OrRd
bounds = np.linspace(round((c.mean()-3)),round((c.mean()+3)),13)
norm = matplotlib.colors.BoundaryNorm(bounds, cmap.N)
plotHandle = ax.scatter(x,y,c = c, s = marker_size, transform=ccrs.Geodetic(),
cmap = cmap,
norm = norm)
if option ==0 :
cbar1 = plt.colorbar(plotHandle, label = 'Temperature in $^\circ $C')
else :
cbar1 = plt.colorbar(plotHandle, label = option)
lon = x[np.nanargmax(c)]
lat = y[np.nanargmax(c)]
at_x, at_y = ax.projection.transform_point(lon, lat,
src_crs=ccrs.Geodetic())
plt.annotate(
'%2.1f'%np.nanmax(c.values), xy=(at_x, at_y), #xytext=(30, 20), textcoords='offset points',
color='black', backgroundcolor='none', size=22,
)
lon = x[np.nanargmin(c)]
lat = y[np.nanargmin(c)]
at_x, at_y = ax.projection.transform_point(lon, lat,
src_crs=ccrs.Geodetic())
plt.annotate(
'%2.1f'%np.nanmin(c.values), xy=(at_x, at_y), #xytext=(30, 20), textcoords='offset points',
color='black', size = 22, backgroundcolor='none')
plt.annotate(
'$\mu = $ %2.1f, $\sigma = $ %2.1f'%(np.nanmean(c.values), np.nanstd(c.values)), (0.01,0.01), xycoords ='axes fraction', #xytext=(30, 20), textcoords='offset points',
color='black', size = 22, backgroundcolor='none')
plt.title('Mean Temperature %s'%name)
filename = './plots/meantempmap%s.eps'%name
plt.savefig(filename, format = 'eps', dpi = 600)
示例10: predict
def predict(self, X):
"""
Predict class
"""
n_frame = len(X)
n_label = len(le.classes_)
self.labels_predicted = np.empty(n_frame, dtype=int)
#尤度保存用行列
matP = np.empty((n_frame, n_label))
#初期確率はクラス0が0.99, その他は当確率とする
matP[0, 0] = 0.99
for i in xrange(1,n_label):
matP[0, i] = (1 - 0.99) / (n_label - 1)
#ラベル保存用行列
matL = np.empty((n_frame, n_label))
#ヴィタビ経路の計算
for j in xrange(1, n_frame):
for yj in xrange(n_label):
prob = np.empty(n_label)
for yk in xrange(n_label):
#出力確率または遷移確率が0の場合はNone
if (self.emit_prob[X[j], yj] == 0.) or (self.trans_prob[yk, yj] == 0.):
prob[yk] = None
else:
prob[yk] = self.emit_prob[X[j], yj] * self.trans_prob[yk, yj] * matP[j-1, yk]
#logprobが全てnanの場合はnanを返す
count = 0
for i in prob:
if np.isnan(i) == True:
count += 1
if count == len(prob):
matP[j, yj] = None
matL[j, yj] = None
else:
matP[j, yj] = np.nanmax(prob)
matL[j, yj] = np.nanargmax(prob)
#クラスごとの確率を足すと1になるように正規化
matP[j, :] = matP[j, :] / np.sum(matP[j, :])
self.likelihoods = matP
#推定ラベル列の決定
self.labels_predicted[n_frame-1] = np.nanargmax(matP[n_frame-1, :])
for j in reversed(xrange(n_frame-1)):
self.labels_predicted[j] = matL[j+1, self.labels_predicted[j+1]]
return self.labels_predicted
示例11: _monitor_max_range
def _monitor_max_range(self, ws):
"""
Gives the bin indices of the first and last peaks in the monitor
@param ws :: input workspace name
return :: [xmin,xmax]
"""
y = mtd[ws].readY(0)
size = len(y)
mid = int(size / 2)
imin = np.nanargmax(y[0:mid])
imax = np.nanargmax(y[mid:size]) + mid
return imin, imax
示例12: _ifws_peak_bins
def _ifws_peak_bins(self, ws):
'''
Gives the bin indices of the first and last peaks (of spectra 0) in the IFWS
@param ws :: input workspace
return :: [xmin,xmax]
'''
y = mtd[ws].readY(0)
size = len(y)
mid = int(size / 2)
imin = np.nanargmax(y[0:mid])
imax = np.nanargmax(y[mid:size]) + mid
return imin, imax
示例13: findpeaks
def findpeaks(f, fft, f_cent, f_span, points, fig, ax, line1, line2):
center = round(points/2.)
region = round(points/8.)
lc = center - region
rc = center + region
region1 = round(points/6.)
l = lc - region1
r = rc + region1
mu1 = nanargmax(fft[l:lc]) + l
mu2 = nanargmax(fft[lc:rc]) + lc
mu3 = nanargmax(fft[rc:r]) + rc
args = [mu1, mu2, mu3]
line1[0].set_data(f[args], fft[args])
return args
示例14: get3MaxDerivatives
def get3MaxDerivatives(eda,num_max=3):
deriv, second_deriv = getDerivatives(eda)
d = copy.deepcopy(deriv)
d2 = copy.deepcopy(second_deriv)
max_indices = []
for i in range(num_max):
maxd_idx = np.nanargmax(abs(d))
max_indices.append(maxd_idx)
d[maxd_idx] = 0
max2d_idx = np.nanargmax(abs(d2))
max_indices.append(max2d_idx)
d2[max2d_idx] = 0
return max_indices, abs(deriv), abs(second_deriv)
示例15: sim_print
def sim_print(self, input_word, corpus_word, sim_matrix, number=5):
for input_sent, sim_vector in zip(input_word, sim_matrix):
print("input=", input_sent)
for count in range(0, number): # 上位n個を出す(n未満の配列には対応しないので注意)
ans_sim = [np.nanmax(sim_vector), np.nanargmax(sim_vector)]
print('配列番号:', np.nanargmax(sim_vector), 'No.', count, 'sim=', ans_sim[0])
print('output=', corpus_word[ans_sim[1]])
src_set = set(input_sent.split())
tag_set = set(corpus_word[ans_sim[1]].split())
print('共通部分', list(src_set & tag_set))
print()
sim_vector[np.nanargmax(sim_vector)] = -1
print()
return 0