当前位置: 首页>>代码示例>>Python>>正文


Python numpy.median方法代码示例

本文整理汇总了Python中numpy.median方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.median方法的具体用法?Python numpy.median怎么用?Python numpy.median使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numpy的用法示例。


在下文中一共展示了numpy.median方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _raise_on_mode

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import median [as 别名]
def _raise_on_mode(self, mode):
        """
        Checks that the provided query mode is one of the accepted values. If
        not, raises a :obj:`ValueError`.
        """
        valid_modes = [
            'random_sample',
            'random_sample_per_pix',
            'samples',
            'median',
            'mean',
            'best',
            'percentile']

        if mode not in valid_modes:
            raise ValueError(
                '"{}" is not a valid `mode`. Valid modes are:\n'
                '  {}'.format(mode, valid_modes)
            ) 
开发者ID:gregreen,项目名称:dustmaps,代码行数:21,代码来源:bayestar.py

示例2: update_hyperparameters

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import median [as 别名]
def update_hyperparameters(self):
        """Update hyperparameters like IoU thresholds for assigner and beta for
        SmoothL1 loss based on the training statistics.

        Returns:
            tuple[float]: the updated ``iou_thr`` and ``beta``.
        """
        new_iou_thr = max(self.train_cfg.dynamic_rcnn.initial_iou,
                          np.mean(self.iou_history))
        self.iou_history = []
        self.bbox_assigner.pos_iou_thr = new_iou_thr
        self.bbox_assigner.neg_iou_thr = new_iou_thr
        self.bbox_assigner.min_pos_iou = new_iou_thr
        new_beta = min(self.train_cfg.dynamic_rcnn.initial_beta,
                       np.median(self.beta_history))
        self.beta_history = []
        self.bbox_head.loss_bbox.beta = new_beta
        return new_iou_thr, new_beta 
开发者ID:open-mmlab,项目名称:mmdetection,代码行数:20,代码来源:dynamic_roi_head.py

示例3: vote

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import median [as 别名]
def vote(vec, tol):
    vec = np.sort(vec)
    n = np.arange(len(vec))[::-1]
    n = n[:, None] - n[None, :] + 1.0
    l = squareform(pdist(vec[:, None], 'minkowski', p=1) + 1e-9)

    invalid = (n < len(vec) * 0.4) | (l > tol)
    if (~invalid).sum() == 0 or len(vec) < tol:
        best_fit = np.median(vec)
        p_score = 0
    else:
        l[invalid] = 1e5
        n[invalid] = -1
        score = n
        max_idx = score.argmax()
        max_row = max_idx // len(vec)
        max_col = max_idx % len(vec)
        assert max_col > max_row
        best_fit = vec[max_row:max_col+1].mean()
        p_score = (max_col - max_row + 1) / len(vec)

    l1_score = np.abs(vec - best_fit).mean()

    return best_fit, p_score, l1_score 
开发者ID:sunset1995,项目名称:HorizonNet,代码行数:26,代码来源:post_proc.py

示例4: _rsp_findpeaks_outliers

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import median [as 别名]
def _rsp_findpeaks_outliers(rsp_cleaned, extrema, amplitude_min=0.3):

    # Only consider those extrema that have a minimum vertical distance to
    # their direct neighbor, i.e., define outliers in absolute amplitude
    # difference between neighboring extrema.
    vertical_diff = np.abs(np.diff(rsp_cleaned[extrema]))
    median_diff = np.median(vertical_diff)
    min_diff = np.where(vertical_diff > (median_diff * amplitude_min))[0]
    extrema = extrema[min_diff]

    # Make sure that the alternation of peaks and troughs is unbroken. If
    # alternation of sign in extdiffs is broken, remove the extrema that
    # cause the breaks.
    amplitudes = rsp_cleaned[extrema]
    extdiffs = np.sign(np.diff(amplitudes))
    extdiffs = np.add(extdiffs[0:-1], extdiffs[1:])
    removeext = np.where(extdiffs != 0)[0] + 1
    extrema = np.delete(extrema, removeext)
    amplitudes = np.delete(amplitudes, removeext)

    return extrema, amplitudes 
开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:23,代码来源:rsp_findpeaks.py

示例5: test_ParallellFiltersAndStability

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import median [as 别名]
def test_ParallellFiltersAndStability(self):
        x, y = self.model.sample_path(50)

        shape = 3000

        linear = AffineProcess((f, g), (1., 1.), self.norm, self.norm)
        self.model.hidden = linear

        filt = SISR(self.model, 1000).set_nparallel(shape).initialize().longfilter(y)

        filtermeans = filt.result.filter_means

        x = filtermeans[:, :1]
        mape = ((x - filtermeans[:, 1:]) / x).abs()

        assert mape.median(0)[0].max() < 0.05 
开发者ID:tingiskhan,项目名称:pyfilter,代码行数:18,代码来源:filters.py

示例6: test_ParallelUnscented

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import median [as 别名]
def test_ParallelUnscented(self):
        x, y = self.model.sample_path(50)

        shape = 30

        linear = AffineProcess((f, g), (1., 1.), self.norm, self.norm)
        self.model.hidden = linear

        filt = SISR(self.model, 1000, proposal=Unscented()).set_nparallel(shape).initialize().longfilter(y)

        filtermeans = filt.result.filter_means

        x = filtermeans[:, :1]
        mape = ((x - filtermeans[:, 1:]) / x).abs()

        assert mape.median(0)[0].max() < 0.05 
开发者ID:tingiskhan,项目名称:pyfilter,代码行数:18,代码来源:filters.py

示例7: makeadmask

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import median [as 别名]
def makeadmask(cdat,min=True,getsum=False):

	nx,ny,nz,Ne,nt = cdat.shape

	mask = np.ones((nx,ny,nz),dtype=np.bool)

	if min:
		mask = cdat[:,:,:,:,:].prod(axis=-1).prod(-1)!=0
		return mask
	else:
		#Make a map of longest echo that a voxel can be sampled with,
		#with minimum value of map as X value of voxel that has median
		#value in the 1st echo. N.b. larger factor leads to bias to lower TEs
		emeans = cdat[:,:,:,:,:].mean(-1)
		medv = emeans[:,:,:,0] == stats.scoreatpercentile(emeans[:,:,:,0][emeans[:,:,:,0]!=0],33,interpolation_method='higher')
		lthrs = np.squeeze(np.array([ emeans[:,:,:,ee][medv]/3 for ee in range(Ne) ]))
		if len(lthrs.shape)==1: lthrs = np.atleast_2d(lthrs).T
		lthrs = lthrs[:,lthrs.sum(0).argmax()]
		mthr = np.ones([nx,ny,nz,ne])
		for ee in range(Ne): mthr[:,:,:,ee]*=lthrs[ee]
		mthr = np.abs(emeans[:,:,:,:])>mthr
		masksum = np.array(mthr,dtype=np.int).sum(-1)
		mask = masksum!=0
		if getsum: return mask,masksum
		else: return mask 
开发者ID:ME-ICA,项目名称:me-ica,代码行数:27,代码来源:tedana.py

示例8: fill_and_adj_numeric

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import median [as 别名]
def fill_and_adj_numeric(df):
	#there are NA for page views, fill median for this == 1
	df.pageviews.fillna(df.pageviews.median(), inplace = True)

	df.hits.fillna(df.hits.median(), inplace = True)
	df.visits.fillna(df.visits.median(), inplace = True)

	#are boolean, fill NaN with zeros, add to categorical
	df.isTrueDirect.fillna(0, inplace = True)
	df.bounces.fillna(0, inplace = True)
	df.newVisits.fillna(0, inplace = True)
	df.visitNumber.fillna(1, inplace = True)

	for col in ['isTrueDirect', 'bounces', 'newVisits']:
		df[col] = df[col].astype(int)

	return df 
开发者ID:CNuge,项目名称:kaggle-code,代码行数:19,代码来源:predict_spending_rough.py

示例9: drawNewLocation

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import median [as 别名]
def drawNewLocation(ax, image_dict, result, image_scale, radio, sx, sy, event, ar):
    x_offset = 0.0
    y_offset = 0.0
    if sx is not None and sy is not None:
        x_offset = sx.val
        y_offset = sy.val

    vosm = np.copy(image_dict["Visible"])
    vosm = OSMTGC.addOSMToImage(result.ways, vosm, pc, image_scale, x_offset, y_offset)
    image_dict["Visible Golf"] = vosm

    hosm = np.copy(image_dict["Heightmap"]).astype('float32')
    hosm = np.clip(hosm, 0.0, 3.5*np.median( hosm[ hosm >= 0.0 ])) # Limit outlier pixels
    hosm = hosm / np.max(hosm)
    hosm = cv2.cvtColor(hosm, cv2.COLOR_GRAY2RGB)
    hosm = OSMTGC.addOSMToImage(result.ways, hosm, pc, image_scale, x_offset, y_offset)
    image_dict["Heightmap Golf"] = hosm

    # Always set to Visible Golf after drawing new golf features
    ax.imshow(image_dict["Visible Golf"], origin='lower')
    radio.set_active(1) 
开发者ID:chadrockey,项目名称:TGC-Designer-Tools,代码行数:23,代码来源:offset_ui_tool.py

示例10: compute_median_rank_at_k

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import median [as 别名]
def compute_median_rank_at_k(tp_fp_list, k):
  """Computes MedianRank@k, where k is the top-scoring labels.

  Args:
    tp_fp_list: a list of numpy arrays; each numpy array corresponds to the all
        detection on a single image, where the detections are sorted by score in
        descending order. Further, each numpy array element can have boolean or
        float values. True positive elements have either value >0.0 or True;
        any other value is considered false positive.
    k: number of top-scoring proposals to take.

  Returns:
    median_rank: median rank of all true positive proposals among top k by
      score.
  """
  ranks = []
  for i in range(len(tp_fp_list)):
    ranks.append(
        np.where(tp_fp_list[i][0:min(k, tp_fp_list[i].shape[0])] > 0)[0])
  concatenated_ranks = np.concatenate(ranks)
  return np.median(concatenated_ranks) 
开发者ID:ahmetozlu,项目名称:vehicle_counting_tensorflow,代码行数:23,代码来源:metrics.py

示例11: test_laplace_sample

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import median [as 别名]
def test_laplace_sample():
    """Test whether the mean and the variance of the samples are correct."""
    mu = np.array([-1, 0., 1.])
    beta = np.array([0.5, 1., 2.])
    nSamples = 1000000

    nParameters = mu.shape[0]
    parameters = {"mu": tf.constant(mu),
                  "beta": tf.constant(beta)}
    tfNSamples = tf.constant(nSamples)
    r = LaplaceAlgorithms.sample(parameters=parameters,
                                 nSamples=tfNSamples)

    with tf.Session() as sess:
        r = sess.run(r)

    assert(r.shape == (nSamples, nParameters))
    muHat = np.median(r, axis=0)
    assert(np.allclose(muHat, mu, atol=1e-1))
    betaHat = np.sqrt(np.var(r, axis=0)/2.)
    assert(np.allclose(betaHat, beta, atol=1e-1)) 
开发者ID:bethgelab,项目名称:decompose,代码行数:23,代码来源:test_laplaceAlgorithms.py

示例12: mad

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import median [as 别名]
def mad(resid, c=0.6745):
    """
    Returns Median-Absolute-Deviation (MAD) for residuals

    Args:
        resid (np.ndarray): residuals
        c (float): scale factor to get to ~standard normal (default: 0.6745)
                 (i.e. 1 / 0.75iCDF ~= 1.4826 = 1 / 0.6745)

    Returns:
        float: MAD 'robust' variance estimate

    Reference:
        http://en.wikipedia.org/wiki/Median_absolute_deviation
    """
    # Return median absolute deviation adjusted sigma
    return np.median(np.fabs(resid - np.median(resid))) / c


# UTILITY FUNCTIONS
# np.any prevents nopython 
开发者ID:ceholden,项目名称:yatsm,代码行数:23,代码来源:robust_fit.py

示例13: kmeans

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import median [as 别名]
def kmeans(self, boxes, k, dist=np.median):
        box_number = boxes.shape[0]
        distances = np.empty((box_number, k))
        last_nearest = np.zeros((box_number,))
        np.random.seed()
        clusters = boxes[np.random.choice(
            box_number, k, replace=False)]  # init k clusters
        while True:

            distances = 1 - self.iou(boxes, clusters)

            current_nearest = np.argmin(distances, axis=1)
            if (last_nearest == current_nearest).all():
                break  # clusters won't change
            for cluster in range(k):
                clusters[cluster] = dist(  # update clusters
                    boxes[current_nearest == cluster], axis=0)

            last_nearest = current_nearest

        return clusters 
开发者ID:bing0037,项目名称:keras-yolo3,代码行数:23,代码来源:kmeans.py

示例14: timeDomain

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import median [as 别名]
def timeDomain(NN):
    
    L = len(NN)    
    ANN = np.mean(NN)
    SDNN = np.std(NN)
    SDSD = np.std(np.diff(NN))    
    NN50 = len(np.where(np.diff(NN) > 0.05)[0])    
    pNN50 = NN50/L    
    NN20 = len(np.where(np.diff(NN) > 0.02)[0])
    pNN20 = NN20/L
    rMSSD = np.sqrt((1/L) * sum(np.diff(NN) ** 2))        
    MedianNN = np.median(NN)
    
    timeDomainFeats = {'ANN': ANN, 'SDNN': SDNN,
                       'SDSD': SDSD, 'NN50': NN50,
                       'pNN50': pNN50, 'NN20': NN20,
                       'pNN20': pNN20, 'rMSSD': rMSSD,
                       'MedianNN':MedianNN}
                       
    return timeDomainFeats 
开发者ID:pickus91,项目名称:HRV,代码行数:22,代码来源:timeDomain.py

示例15: test_axis_keyword

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import median [as 别名]
def test_axis_keyword(self):
        a3 = np.array([[2, 3],
                       [0, 1],
                       [6, 7],
                       [4, 5]])
        for a in [a3, np.random.randint(0, 100, size=(2, 3, 4))]:
            orig = a.copy()
            np.median(a, axis=None)
            for ax in range(a.ndim):
                np.median(a, axis=ax)
            assert_array_equal(a, orig)

        assert_allclose(np.median(a3, axis=0), [3,  4])
        assert_allclose(np.median(a3.T, axis=1), [3,  4])
        assert_allclose(np.median(a3), 3.5)
        assert_allclose(np.median(a3, axis=None), 3.5)
        assert_allclose(np.median(a3.T), 3.5) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:19,代码来源:test_function_base.py


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