Here are the examples of the python api numpy.median taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
977 Examples
5
Source : extract_bg_tmf.py
with Apache License 2.0
from CVIR
with Apache License 2.0
from CVIR
def median_calc(median_array):
return numpy.median(median_array[:, :, :, 0], axis=0), \
numpy.median(median_array[:, :, :, 1], axis=0), \
numpy.median(median_array[:, :, :, 2], axis=0)
def make_a_video(output_dir, output_format, name):
3
Source : meters.py
with Apache License 2.0
from 1adrianb
with Apache License 2.0
from 1adrianb
def get_win_median(self):
"""
Calculate the current median value of the deque.
"""
return np.median(self.deque)
def get_win_avg(self):
3
Source : detrend_window.py
with MIT License
from 3fon3fonov
with MIT License
from 3fon3fonov
def add_dilution(self):
D_flux = self.flux/(self.ui.Dilution_fact.value())
self.flux = D_flux - np.median(D_flux) * (1.0 - self.ui.Dilution_fact.value())
D_flux_err = self.flux_err/(self.ui.Dilution_fact.value())
self.flux_err = D_flux_err
self.ui.radio_remove_median.setChecked(True)
#self.plot()
self.worker_detrend()
return
def add_bjd(self):
3
Source : functions.py
with MIT License
from 3fon3fonov
with MIT License
from 3fon3fonov
def get_median_of_samples(samples, nsamp):
median_samp = []
for i in range(nsamp):
median_samp.append(np.median(samples[:,i]))
return median_samp
def get_MAD_of_samples(samples, nsamp):
3
Source : test_function_base.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_array_like(self):
x = [1, 2, 3]
assert_almost_equal(np.median(x), 2)
x2 = [x]
assert_almost_equal(np.median(x2), 2)
assert_allclose(np.median(x2, axis=0), x)
def test_subclass(self):
3
Source : test_nanfunctions.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_result_values(self):
tgt = [np.median(d) for d in _rdat]
res = np.nanmedian(_ndat, axis=1)
assert_almost_equal(res, tgt)
def test_allnans(self):
3
Source : test_analytics.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_median(self):
self._check_stat_op('median', np.median)
# test with integers, test failure
int_ts = Series(np.ones(10, dtype=int), index=lrange(10))
tm.assert_almost_equal(np.median(int_ts), int_ts.median())
def test_mode(self):
3
Source : test_nanops.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_nanmedian(self):
with warnings.catch_warnings(record=True):
self.check_funs(nanops.nanmedian, np.median, allow_complex=False,
allow_str=False, allow_date=False,
allow_tdelta=True, allow_obj='convert')
@pytest.mark.parametrize('ddof', range(3))
3
Source : test_binned_statistic.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_1d_median(self):
x = self.x
v = self.v
stat1, edges1, bc = binned_statistic(x, v, 'median', bins=10)
stat2, edges2, bc = binned_statistic(x, v, np.median, bins=10)
assert_allclose(stat1, stat2)
assert_allclose(edges1, edges2)
def test_1d_bincode(self):
3
Source : test_binned_statistic.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_2d_median(self):
x = self.x
y = self.y
v = self.v
stat1, binx1, biny1, bc = binned_statistic_2d(
x, y, v, 'median', bins=5)
stat2, binx2, biny2, bc = binned_statistic_2d(
x, y, v, np.median, bins=5)
assert_allclose(stat1, stat2)
assert_allclose(binx1, binx2)
assert_allclose(biny1, biny2)
def test_2d_bincode(self):
3
Source : test_binned_statistic.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_dd_median(self):
X = self.X
v = self.v
stat1, edges1, bc = binned_statistic_dd(X, v, 'median', bins=3)
stat2, edges2, bc = binned_statistic_dd(X, v, np.median, bins=3)
assert_allclose(stat1, stat2)
assert_allclose(edges1, edges2)
def test_dd_bincode(self):
3
Source : cwru_data_loader.py
with GNU General Public License v3.0
from al3xsh
with GNU General Public License v3.0
from al3xsh
def normalise(x, axis=0):
# calculate the center and scale
x_center = np.median(x, axis=axis)
x_scale = np.median(np.abs(x - x_center), axis=axis)
# normalise our data and return
x_norm = (x - x_center) / x_scale
return x_norm
# filter the keys from the matlab file to just match the ones we are
# interested in
def filter_key(keys, variables):
3
Source : DimensionReduction.py
with MIT License
from alan-turing-institute
with MIT License
from alan-turing-institute
def median_dist(X):
"""Return the median of the pairwise (Euclidean) distances between
each row of X
"""
return np.median(pdist(X))
class gKDR(object):
3
Source : stats.py
with BSD 3-Clause "New" or "Revised" License
from alan-turing-institute
with BSD 3-Clause "New" or "Revised" License
from alan-turing-institute
def median(X):
"""Numba median function for a single time series."""
return np.median(X)
@njit(fastmath=True, cache=True)
3
Source : utils.py
with MIT License
from alex000kim
with MIT License
from alex000kim
def auto_canny(image, sigma=0.3):
v = np.median(image)
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
edged = cv2.Canny(image, lower, upper)
return edged
def resize_img(image, width=None, height=None, inter=cv2.INTER_AREA):
3
Source : utils.py
with MIT License
from alex000kim
with MIT License
from alex000kim
def get_median_frame(frames):
median_frame = np.median(frames, axis=0)
return median_frame
def get_stdev_frame(frames):
3
Source : imutils.py
with Mozilla Public License 2.0
from AlexisTheLarge
with Mozilla Public License 2.0
from AlexisTheLarge
def minMaxMeanMedian(gray):
#h, w = cv_size(image);
min_val = gray.min()
max_val = gray.max()
mean = gray.mean()
median = np.median(gray)
return (min_val, max_val, mean, median)
def getLuminosity(image):
3
Source : QgsVideoFilters.py
with GNU General Public License v3.0
from All4Gis
with GNU General Public License v3.0
from All4Gis
def EdgeFilter(image, sigma=0.33):
"""Edge Image Filter
@type image: QImage
@param image:
@return: QImage
"""
gray = convertQImageToMat(image)
v = np.median(gray)
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
canny = Canny(gray, lower, upper)
return convertMatToQImage(canny)
@staticmethod
3
Source : test_baseline_regressor.py
with BSD 3-Clause "New" or "Revised" License
from alteryx
with BSD 3-Clause "New" or "Revised" License
from alteryx
def test_baseline_median(X_y_regression):
X, y = X_y_regression
median = np.median(y)
clf = BaselineRegressor(strategy="median")
clf.fit(X, y)
expected_predictions = pd.Series([median] * len(X))
predictions = clf.predict(X)
assert_series_equal(expected_predictions, predictions)
np.testing.assert_allclose(clf.feature_importance, np.array([0.0] * X.shape[1]))
3
Source : test_data.py
with MIT License
from alvarobartt
with MIT License
from alvarobartt
def test_robust_scaler_iris():
X = iris.data
scaler = RobustScaler()
X_trans = scaler.fit_transform(X)
assert_array_almost_equal(np.median(X_trans, axis=0), 0)
X_trans_inv = scaler.inverse_transform(X_trans)
assert_array_almost_equal(X, X_trans_inv)
q = np.percentile(X_trans, q=(25, 75), axis=0)
iqr = q[1] - q[0]
assert_array_almost_equal(iqr, 1)
def test_robust_scaler_iris_quantiles():
3
Source : test_data.py
with MIT License
from alvarobartt
with MIT License
from alvarobartt
def test_robust_scaler_iris_quantiles():
X = iris.data
scaler = RobustScaler(quantile_range=(10, 90))
X_trans = scaler.fit_transform(X)
assert_array_almost_equal(np.median(X_trans, axis=0), 0)
X_trans_inv = scaler.inverse_transform(X_trans)
assert_array_almost_equal(X, X_trans_inv)
q = np.percentile(X_trans, q=(10, 90), axis=0)
q_range = q[1] - q[0]
assert_array_almost_equal(q_range, 1)
def test_quantile_transform_iris():
3
Source : test_data.py
with MIT License
from alvarobartt
with MIT License
from alvarobartt
def test_robust_scale_axis1():
X = iris.data
X_trans = robust_scale(X, axis=1)
assert_array_almost_equal(np.median(X_trans, axis=1), 0)
q = np.percentile(X_trans, q=(25, 75), axis=1)
iqr = q[1] - q[0]
assert_array_almost_equal(iqr, 1)
def test_robust_scaler_zero_variance_features():
3
Source : evpost.py
with BSD 3-Clause "New" or "Revised" License
from amulog
with BSD 3-Clause "New" or "Revised" License
from amulog
def outlier(sr, outlier_threshold=2.0, **kwargs):
ret = sr * 0
base = np.median(sr)
ret[sr > base + outlier_threshold] = 1
return ret
def outlier_median_absdev(sr, outlier_threshold=2.0, **kwargs):
3
Source : evpost.py
with BSD 3-Clause "New" or "Revised" License
from amulog
with BSD 3-Clause "New" or "Revised" License
from amulog
def outlier_median_absdev(sr, outlier_threshold=2.0, **kwargs):
ret = sr * 0
# median absolute deviation
base = np.median(np.abs(sr - np.median(sr)))
ret[sr > base + outlier_threshold] = 1
return ret
def anomaly_lof(sr, **kwargs):
3
Source : period.py
with BSD 3-Clause "New" or "Revised" License
from amulog
with BSD 3-Clause "New" or "Revised" License
from amulog
def restore_data(data, data_filtered, th_restore):
thval = th_restore * max(data_filtered)
periodic_time = (data > 0) & (data_filtered >= thval) # bool
periodic_cnt = np.median(data[periodic_time])
data_periodic = np.zeros(len(data))
data_periodic[periodic_time] = periodic_cnt
data_remain = data - data_periodic
return data_remain
def power2(length):
3
Source : cacheSim.py
with GNU Affero General Public License v3.0
from andreas-abel
with GNU Affero General Public License v3.0
from andreas-abel
def getGraph(blocks, seq, policySimClass, assoc, maxAge, nSets=1, nRep=1, agg="med"):
traces = []
for block in blocks:
trace = []
for i in range(0, maxAge):
curSeq = seq + ' ' + ' '.join('N' + str(n) for n in range(0,i)) + ' ' + block + '?'
hits = [getHits(curSeq, policySimClass, assoc, '0-'+str(nSets-1)) for _ in range(0, nRep)]
if agg == "med":
aggValue = median(hits)
elif agg == "min":
aggValue = min(hits)
else:
aggValue = float(sum(hits))/nRep
trace.append(aggValue)
traces.append((block, trace))
return traces
def getPermutations(policySimClass, assoc):
3
Source : neural_pooling.py
with MIT License
from apmoore1
with MIT License
from apmoore1
def matrix_median(matrix, **kwargs):
'''
:param matrix: matrix or vector
:param kwargs: Can keywords that are accepted by `matrix_checking` function
:type matrix: np.ndarray
:type kwargs: dict
:returns: The median column values in the matrix.
:rtype: np.ndarray
'''
return np.median(matrix, axis=0)
@inf_nan_check
3
Source : misc.py
with Apache License 2.0
from armandmcqueen
with Apache License 2.0
from armandmcqueen
def _trigger_epoch(self):
duration = time.time() - self._last_time
self._last_time = time.time()
self._times.append(duration)
epoch_time = np.median(self._times) if self._median else np.mean(self._times)
time_left = (self._max_epoch - self.epoch_num) * epoch_time
if time_left > 0:
logger.info("Estimated Time Left: " + humanize_time_delta(time_left))
3
Source : AutoEncoder.py
with The Unlicense
from AshwathSalimath
with The Unlicense
from AshwathSalimath
def outliers_modified_z_score(ys):
threshold = 3.5
median_y = np.median(ys)
median_absolute_deviation_y = np.median([np.abs(y - median_y) for y in ys])
modified_z_scores = [0.6745 * (y - median_y) / median_absolute_deviation_y
for y in ys]
return np.where(np.abs(modified_z_scores) > threshold)
outliers_modified_z_score_np = outliers_modified_z_score(iot_error_np)
3
Source : cog_types.py
with GNU General Public License v3.0
from automorphis
with GNU General Public License v3.0
from automorphis
def get_average_std_obj(self, cog_array=None, obj_fxn=None, samples_per_coord=1):
if not self.average_obj:
if not cog_array or not obj_fxn:
raise RuntimeError
objs = []
for coords,_ in cog_array:
for _ in range(samples_per_coord):
cog_array.move_all_to_spares().move_cog_from_spares(coords,self).randomize()
obj1 = obj_fxn(cog_array.move_all_to_spares().move_cog_from_spares(coords, self).randomize())
obj2 = obj_fxn(cog_array.move_cog_to_spares(coords))
objs.append(obj1-obj2)
self.average_obj = np.median(objs)
self.std_obj = (np.percentile(objs,100*(0.50+ONE_SIG_PROB)) - np.percentile(objs,100*(0.50-ONE_SIG_PROB)))/2
return self.average_obj, self.std_obj
"""
3
Source : geometry.py
with MIT License
from autonomousvision
with MIT License
from autonomousvision
def center_pcl(pcl, robust=False, copy=False, axis=1):
if copy:
pcl = pcl.copy()
if robust:
mu = np.median(pcl, axis=axis, keepdims=True)
else:
mu = np.mean(pcl, axis=axis, keepdims=True)
return pcl - mu
def to_homogeneous(x):
3
Source : vocode.py
with MIT License
from averak
with MIT License
from averak
def masking(self, frame: np.ndarray, freq_mask: np.ndarray) -> np.ndarray:
freq_mask = np.where(freq_mask < np.median(freq_mask) - 0.1, 0, 1)
freq_mask = np.reshape(freq_mask, frame.shape)
return frame * freq_mask
def save(self, wav: np.ndarray, file_name: str) -> None:
3
Source : xloc_utils.py
with GNU General Public License v3.0
from awech
with GNU General Public License v3.0
from awech
def location_scatter(loc, lats, lons, deps):
dist = list()
for y, x in zip(lats, lons):
a = gps2dist_azimuth(loc.latitude, loc.longitude, y, x)
dist.append(a[0] / float(1000))
scatter_x = np.median(dist)
scatter_z = np.median(np.abs(deps - loc.depth))
return scatter_x, scatter_z
def rotate_coords(x, y, x0, y0, angle):
3
Source : test_stat_reductions.py
with Apache License 2.0
from aws-samples
with Apache License 2.0
from aws-samples
def test_median(self):
string_series = tm.makeStringSeries().rename('series')
self._check_stat_op('median', np.median, string_series)
# test with integers, test failure
int_ts = Series(np.ones(10, dtype=int), index=lrange(10))
tm.assert_almost_equal(np.median(int_ts), int_ts.median())
def test_prod(self):
3
Source : test_nanops.py
with Apache License 2.0
from aws-samples
with Apache License 2.0
from aws-samples
def test_nanmedian(self):
with warnings.catch_warnings(record=True):
warnings.simplefilter("ignore", RuntimeWarning)
self.check_funs(nanops.nanmedian, np.median, allow_complex=False,
allow_str=False, allow_date=False,
allow_tdelta=True, allow_obj='convert')
@pytest.mark.parametrize('ddof', range(3))
3
Source : canny_edge_det.py
with MIT License
from axenhammer
with MIT License
from axenhammer
def auto_canny(image, sigma=0.33):
# compute the median of the single channel pixel intensities
v = np.median(image)
# apply automatic Canny edge detection using the computed median
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
edged = cv2.Canny(image, lower, upper)
return(edged)
# return the edged image
def main():
3
Source : edge_detection.py
with MIT License
from axenhammer
with MIT License
from axenhammer
def auto_canny(image, sigma=0.33):
# compute the median of the single channel pixel intensities
v = np.median(image)
# apply automatic Canny edge detection using the computed median
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
edged = cv2.Canny(image, lower, upper)
return(edged)
# return the edged image
def edgedetection(frame):
3
Source : VToF.py
with MIT License
from axenhammer
with MIT License
from axenhammer
def auto_canny(image, sigma=0.33):
# compute the median of the single channel pixel intensities
v = np.median(image)
# apply automatic Canny edge detection using the computed median
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
edged = cv2.Canny(image, lower, upper)
return(edged)
# return the edged image
# Extract Edges from Hand Frames
def convertToEdge(gesture_folder, target_folder, swap_):
3
Source : stats.py
with MIT License
from bartongroup
with MIT License
from bartongroup
def median_absolute_deviation(arr):
'''Returns the MAD of an array'''
return np.median(np.abs(arr - np.median(arr)))
def kmeans_init_clusters(X, detect_outliers='mad', init_method='kmeans++',
3
Source : agg_functions.py
with MIT License
from basedrhys
with MIT License
from basedrhys
def aggregate(self):
return np.concatenate((
np.median(self.vectors, 0),
np.min(self.vectors, 0)),
axis=0)
@staticmethod
3
Source : agg_functions.py
with MIT License
from basedrhys
with MIT License
from basedrhys
def aggregate(self):
return np.concatenate((
np.median(self.vectors, 0),
np.std(self.vectors, 0)),
axis=0)
@staticmethod
3
Source : agg_functions.py
with MIT License
from basedrhys
with MIT License
from basedrhys
def aggregate(self):
return np.concatenate((
np.median(self.vectors, 0),
np.sum(self.vectors, 0)),
axis=0)
@staticmethod
3
Source : resampling_policies.py
with Apache License 2.0
from bds-ailab
with Apache License 2.0
from bds-ailab
def allow_resampling(self, history):
"""Defines if resampling should be allowed or not."""
if self.allow_resampling_schedule:
if self.last_elem_nbr < 2:
return True
# Compute median up until the evaluated new parametrization
current_median = np.median(
history["fitness"][: (self.total_nbr - self.last_elem_nbr)]
)
return (
np.median(self.last_elem_fitness)
< = self.allow_resampling_schedule(
(self.total_nbr - self.last_elem_nbr)
)
* current_median
)
return True
def ic_length(self):
3
Source : resampling_policies.py
with Apache License 2.0
from bds-ailab
with Apache License 2.0
from bds-ailab
def ic_threshold(self):
"""Computes the threshold value for the IC length."""
percentage = self.resampling_schedule(
(self.total_nbr - self.last_elem_nbr)
)
return np.abs(percentage * np.median(self.last_elem_fitness))
3
Source : test_shaman_config_model.py
with Apache License 2.0
from bds-ailab
with Apache License 2.0
from bds-ailab
def test_pruning_parameters_function(self):
"""Tests that the pruning parameters are properly parsed when max_step_duration is a function.
"""
pruning_parameters = PruningParameters(
max_step_duration="numpy.median")
self.assertEqual(pruning_parameters.max_step_duration, numpy.median)
def test_pruning_parameters_wrong_type(self):
3
Source : samples_to_phrases.py
with MIT License
from beefoo
with MIT License
from beefoo
def getPhraseFeatures(samples, clarityKey="clarity", powerKey="power"):
# weights = [s["dur"] for s in samples]
# clarity = np.average([s[clarityKey] for s in samples], weights=weights)
# power = np.average([s[powerKey] for s in samples], weights=weights)
clarity = np.median([s[clarityKey] for s in samples])
power = np.median([s[powerKey] for s in samples])
return (clarity, power)
def addPhrase(phrases, phrase):
3
Source : features.py
with MIT License
from biolab-put
with MIT License
from biolab-put
def force_feature_median(series, window, step):
"""Median value"""
windows_strided, indexes = biolab_utilities.moving_window_stride(series.values, window, step)
return pd.Series(data=np.median(windows_strided, axis=1), index=series.index[indexes])
def force_feature_last(series, window, step):
3
Source : transformations.py
with MIT License
from bjherger
with MIT License
from bjherger
def generate_embedding_sequence_length(observation_series):
lengths = list(map(len, observation_series))
embedding_sequence_length = max([int(numpy.median(lengths)), 1])
logging.info('Generated embedding_sequence_length: {}'.format(embedding_sequence_length))
return embedding_sequence_length
def process_string(self, input_string):
3
Source : generate_mask.py
with Apache License 2.0
from bleakie
with Apache License 2.0
from bleakie
def add_median_colr(img_ori, img_mask, mask, min_bbox):
img_crop = faceCrop(img_ori, min_bbox, scale_ratio=0.5)
(B, G, R) = cv2.split(img_crop)
B_median = np.median(B)
G_median = np.median(G)
R_median = np.median(R)
# mean_pixel = cv2.mean(img[int(rect[1]):int(rect[3]), int(rect[0]):int(rect[2])]) # get img mean pixel
rows, cols, _ = img_ori.shape
for row in range(rows):
for col in range(cols):
if mask[row, col] < 1:
img_mask[row, col][0] = B_median
img_mask[row, col][1] = G_median
img_mask[row, col][2] = R_median
return img_mask
def align_face(input, preds, canonical_vertices, target_size=(318,361)):
3
Source : mgp_tcn_fit.py
with BSD 3-Clause "New" or "Revised" License
from BorgwardtLab
with BSD 3-Clause "New" or "Revised" License
from BorgwardtLab
def mad(arr):
""" Median Absolute Deviation: a "Robust" version of standard deviation.
Indices variabililty of the sample.
https://en.wikipedia.org/wiki/Median_absolute_deviation
"""
med = np.median(arr)
return np.median(np.abs(arr - med))
def print_var_statistics(name, values):
See More Examples