• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python numpy.nanargmax函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中numpy.nanargmax函数的典型用法代码示例。如果您正苦于以下问题:Python nanargmax函数的具体用法?Python nanargmax怎么用?Python nanargmax使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了nanargmax函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
开发者ID:BabeNovelty,项目名称:dask,代码行数:31,代码来源:test_reductions.py


示例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))
开发者ID:bj-wangjia,项目名称:dask,代码行数:32,代码来源:test_reductions.py


示例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]
开发者ID:irinatu,项目名称:long_inter,代码行数:28,代码来源:find_domains_my.py


示例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
开发者ID:ZhouJiaLinmumu,项目名称:topicvec,代码行数:26,代码来源:utils.py


示例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
开发者ID:vargasjeffrey52,项目名称:sat_spot_ratio,代码行数:33,代码来源:sat_spot_to_star_ratio3.py


示例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
开发者ID:egtaonline,项目名称:GameAnalysis,代码行数:25,代码来源:regret.py


示例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
开发者ID:paren8esis,项目名称:thesis,代码行数:59,代码来源:DeltaTrimax.py


示例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
开发者ID:EQ4,项目名称:contour_classification,代码行数:57,代码来源:experiment_utils.py


示例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)
开发者ID:gottscott,项目名称:IntraUrbanTemperatureVariabilityBaltimore,代码行数:55,代码来源:ibuttonplots.py


示例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
开发者ID:zhouxiazx,项目名称:ActionRecognition-2,代码行数:53,代码来源:AR_exp03.py


示例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
开发者ID:stuartcampbell,项目名称:mantid,代码行数:13,代码来源:IndirectILLEnergyTransfer.py


示例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
开发者ID:stuartcampbell,项目名称:mantid,代码行数:13,代码来源:IndirectILLReductionFWS.py


示例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
开发者ID:kramerfelix,项目名称:accpy,代码行数:14,代码来源:tunes.py


示例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)
开发者ID:panchohumeres,项目名称:eda-explorer,代码行数:14,代码来源:EDA-Artifact-Detection-Script.py


示例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
开发者ID:ushiku,项目名称:text2feature,代码行数:14,代码来源:dep2feature.py


示例16: clustercoordsbymax1d

def clustercoordsbymax1d(arr, pkind, critsepind):#results will be sorted. wherever there are peak indeces too close together. the peak index next to the peak index with highest arr value gets removed
    pkind.sort()
    indindslow=numpy.where((pkind[1:]-pkind[:-1])<critsepind)[0]
    indindshigh=indindslow+1
    while indindslow.size>0:
        maxindindindlow=numpy.nanargmax(arr[pkind[(indindslow,)]])
        maxindindindhigh=numpy.nanargmax(arr[pkind[(indindshigh,)]])
        if arr[pkind[indindslow[maxindindindlow]]]>arr[pkind[indindshigh[maxindindindhigh]]]:
            pkind=numpy.delete(pkind, indindshigh[maxindindindlow])
        else:
            pkind=numpy.delete(pkind, indindslow[maxindindindhigh])

        indindslow=numpy.where((pkind[1:]-pkind[:-1])<critsepind)[0]
        indindshigh=indindslow+1
    return pkind
开发者ID:johnmgregoire,项目名称:NanoCalorimetry,代码行数:15,代码来源:PnSC_math.py


示例17: test_reductions_2D_nans

def test_reductions_2D_nans():
    # chunks are a mix of some/all/no NaNs
    x = np.full((4, 4), np.nan)
    x[:2, :2] = np.array([[1, 2], [3, 4]])
    x[2, 2] = 5
    x[3, 3] = 6
    a = da.from_array(x, chunks=(2, 2))

    reduction_2d_test(da.sum, a, np.sum, x, False, False)
    reduction_2d_test(da.prod, a, np.prod, x, False, False)
    reduction_2d_test(da.mean, a, np.mean, x, False, False)
    reduction_2d_test(da.var, a, np.var, x, False, False)
    reduction_2d_test(da.std, a, np.std, x, False, False)
    reduction_2d_test(da.min, a, np.min, x, False, False)
    reduction_2d_test(da.max, a, np.max, x, False, False)
    reduction_2d_test(da.any, a, np.any, x, False, False)
    reduction_2d_test(da.all, a, np.all, x, False, False)

    reduction_2d_test(da.nansum, a, np.nansum, x, False, False)
    reduction_2d_test(da.nanprod, a, nanprod, x, False, False)
    reduction_2d_test(da.nanmean, a, np.nanmean, x, False, False)
    with pytest.warns(None):  # division by 0 warning
        reduction_2d_test(da.nanvar, a, np.nanvar, x, False, False)
    with pytest.warns(None):  # division by 0 warning
        reduction_2d_test(da.nanstd, a, np.nanstd, x, False, False)
    with pytest.warns(None):  # all NaN axis warning
        reduction_2d_test(da.nanmin, a, np.nanmin, x, False, False)
    with pytest.warns(None):  # all NaN axis warning
        reduction_2d_test(da.nanmax, a, np.nanmax, x, False, False)

    assert_eq(da.argmax(a), np.argmax(x))
    assert_eq(da.argmin(a), np.argmin(x))
    with pytest.warns(None):  # all NaN axis warning
        assert_eq(da.nanargmax(a), np.nanargmax(x))
    with pytest.warns(None):  # all NaN axis warning
        assert_eq(da.nanargmin(a), np.nanargmin(x))
    assert_eq(da.argmax(a, axis=0), np.argmax(x, axis=0))
    assert_eq(da.argmin(a, axis=0), np.argmin(x, axis=0))
    with pytest.warns(None):  # all NaN axis warning
        assert_eq(da.nanargmax(a, axis=0), np.nanargmax(x, axis=0))
    with pytest.warns(None):  # all NaN axis warning
        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))
    with pytest.warns(None):  # all NaN axis warning
        assert_eq(da.nanargmax(a, axis=1), np.nanargmax(x, axis=1))
    with pytest.warns(None):  # all NaN axis warning
        assert_eq(da.nanargmin(a, axis=1), np.nanargmin(x, axis=1))
开发者ID:mmngreco,项目名称:dask,代码行数:48,代码来源:test_reductions.py


示例18: _create_new_neuron

    def _create_new_neuron(self):
        '''
        create new neuron if t mod \lambda = 0 and |K| < \theta
            a. find neuron q with the greatest counter: q := arg max_{n \in K} e_n
            b. find neighbor f of q with f := arg max_{n \in N_q} e_n
            c. initialize new neuron l
                K := K \cup l
                w_l := 1/2 * (w_q + w_f)
                c_l := 1/2 * (c_q + c_f)
                e_l := \delta * (e_f + e_q)
            d. adapt connections: E := (E \ {(q, f)}) \cup {(q, n), (n, f)}
            e. decrease counter of q and f by the factor \delta
                e_q := (1 - \deta) * e_q
                e_f := (1 - \deta) * e_f
        '''
        q = np.nanargmax(self.errors)
        N_q = None
        if q:
            N_q = self.model.neighbors(q)
        if N_q:
            f = max(N_q, key=lambda n: self.errors[n])
            l = self._add_node(e=self.delta*(self.errors[q] + self.errors[f]),
                               w=(self.weights[q] + self.weights[f]) / 2,
                               c=(self.contexts[q] + self.contexts[f]) / 2)
            self.model.remove_edge(q, f)
            self._add_edge(q, l)
            self._add_edge(f, l)
            self.errors[q] *= (1 - self.delta)
            self.errors[f] *= (1 - self.delta)

            return l
开发者ID:mtambos,项目名称:bachelorsthesis,代码行数:31,代码来源:mgng.py


示例19: rngWorker

def rngWorker(inputEdges, queue):
    """
    Work done by each processor
    :param inputEdges: set of edges (p, q)
    :param queue: shared Queue to place results
    """
    edges = set()
    for p, q in inputEdges:
        relationPQ = _globalRelationalMatrix[p, q]
        row = _globalRelationalMatrix[p]
        # maxJRow = getBestScore(relationMatrix[q])
        # non-numerical distances/similarities will not be counted as edges
        if np.isnan(relationPQ):
            isEdge = False
        # if there is a numeric value
        else:
            isEdge = True   # assume edge until proven wrong
            # loop through all columns in the ith row
            # relationPR is weight of edge p,r ***************************************************** (N^3)/2
            for r, relationPR in enumerate(row):
                # skip rows p and q and any points for which there is no distance value
                if p != r != q and (not np.isnan(relationPR)) and (not np.isnan(_globalRelationalMatrix[q, r])):
                    # for triangle prq, if pq is the longest distance, then p and q are not neighbors
                    lengths = [relationPR, _globalRelationalMatrix[q, r]]
                    if lengths[np.nanargmax(lengths)] < relationPQ:
                        isEdge = False      # not an edge!
                        break               # break to next q
        # if p and q are neighbors
        if isEdge:
            edges.add(frozenset((p, q)))    # add (p,q) tuple to edges set
    queue.put(edges)
开发者ID:schoolacct,项目名称:GeneExpressionNeighborhoods,代码行数:31,代码来源:ProximityGraph.py


示例20: decide_migration_loadaware_woi

	def decide_migration_loadaware_woi(self):
		migrate_me_maybe = (self.window_overload_index > self.relocation_thresholds)[0]
		if np.sum(migrate_me_maybe) > 0:
			indexes = np.array(np.where(migrate_me_maybe)).tolist()[0] # potential migration sources
			pm_source = random.choice(indexes)
			set_of_vms = (self.location[:, pm_source] == 1).transpose()
			vm_set_migration = np.array(np.where(set_of_vms)).tolist()[0]

			volumes = np.array([x.get_volume() for x in self.pms])
			available_volume_per_pm = volumes - self.physical_volume_vector
			aware_matrix = np.zeros((self.num_vms, self.num_pms))
			for col in range(0,self.num_pms):
				aware_matrix[:, col] = available_volume_per_pm[col]
			for row in range(0,self.num_vms):
				if row in vm_set_migration:
					vol_to_remove = self.volumes[row]
				else:
					vol_to_remove = np.inf
				aware_matrix[row, :] = aware_matrix[row, :] - vol_to_remove
			aware_matrix[:, pm_source] = np.nan
			aware_matrix[aware_matrix<0] = np.nan

			if not np.isnan(aware_matrix).all():
				argmaxidx = np.nanargmax(aware_matrix)
				coordinates = np.unravel_index(argmaxidx, (self.num_vms, self.num_pms))
				vm_migrate = coordinates[0]
				pm_destination = coordinates[1]
				self.migrate(vm_migrate, pm_source, pm_destination)
				self.integrated_overload_index[0,pm_source] = 0
开发者ID:alleneben,项目名称:vm-migration-sim,代码行数:29,代码来源:MigrationManager.py



注:本文中的numpy.nanargmax函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python numpy.nanargmin函数代码示例发布时间:2022-05-27
下一篇:
Python numpy.nan_to_num函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap