本文整理汇总了Python中numpy.minimum函数的典型用法代码示例。如果您正苦于以下问题:Python minimum函数的具体用法?Python minimum怎么用?Python minimum使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了minimum函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __PlotWeightedAtlas
def __PlotWeightedAtlas(self, sortedfunctiontuples, weightdict):
# initialize the data
median = self.__Curves[sortedfunctiontuples[0][0]]
minimum = np.Inf + np.zeros(len(median))
maximum = -np.Inf + np.zeros(len(median))
outliers = []
cumulativeWeight = weightdict[sortedfunctiontuples[0][0]]
i = 0
# determine the functions in inter quartile range (IQR)
while cumulativeWeight < .5:
maximum = np.maximum(
maximum, self.__Curves[sortedfunctiontuples[i][0]])
minimum = np.minimum(
minimum, self.__Curves[sortedfunctiontuples[i][0]])
cumulativeWeight += weightdict[sortedfunctiontuples[i][0]]
i += 1
upperfence = maximum[:]
lowerfence = minimum[:]
fences = AtlasMath.BandDepth.GenerateFences(minimum, maximum, median)
# Determine the functions in the 99.3% confidence interval
while cumulativeWeight < .993:
upperfence = np.maximum(
upperfence, self.__Curves[sortedfunctiontuples[i][0]])
lowerfence = np.minimum(
lowerfence, self.__Curves[sortedfunctiontuples[i][0]])
cumulativeWeight += weightdict[sortedfunctiontuples[i][0]]
i += 1
fences = [
np.minimum(upperfence, fences[0]), np.maximum(lowerfence, fences[1])]
# the left over functions are outliers
for pair in sortedfunctiontuples[i:]:
outliers.append(self.__Curves[pair[0]])
self.__PlotLines(median, maximum, minimum, outliers, fences)
return
示例2: process_chunk
def process_chunk(self, t0, t1, intensity, weights, pp_intensity, pp_weights):
# Loop over intensity/weights in chunks of size v1_chunk
for ichunk in xrange(0, self.nt_chunk, self.v1_chunk):
for frequency in xrange(self.nfreq):
# Calculate the v1 for each frequency
self.v1_tmp[frequency] = self._v1(intensity[frequency, ichunk:ichunk+self.v1_chunk], weights[frequency, ichunk:ichunk+self.v1_chunk])
# Once v1s have been calculated for each frequency, update the weights and running variance
non_zero_v1 = self.v1_tmp != 0
zero_v1 = np.logical_not(non_zero_v1)
# For nonzero (successful) v1s, increase the weights (if possible) and update the running variance
self.running_weights[non_zero_v1] = np.minimum(2.0, self.running_weights[non_zero_v1] + self.w_clamp)
self.v1_tmp[non_zero_v1] = np.minimum((1-self.var_weight) * self.running_var[non_zero_v1] + self.var_weight * self.v1_tmp[non_zero_v1],
self.running_var[non_zero_v1] + self.var_clamp_add + self.running_var[non_zero_v1] * self.var_clamp_mult)
self.v1_tmp[non_zero_v1] = np.maximum(self.v1_tmp[non_zero_v1], self.running_var[non_zero_v1] - self.var_clamp_add - self.running_var[non_zero_v1] * self.var_clamp_mult)
self.running_var[non_zero_v1] = self.v1_tmp[non_zero_v1]
# For unsuccessful v1s, decrease the weights (if possible) and do not modify the running variance
self.running_weights[zero_v1] = np.maximum(0, self.running_weights[zero_v1] - self.w_clamp)
# Mask fill!
intensity_valid = (weights[:, ichunk:ichunk+self.v1_chunk] > self.w_cutoff)
rand_intensity = np.random.standard_normal(size=intensity[:, ichunk:ichunk+self.v1_chunk].shape)
for (ifreq,v) in enumerate(self.running_var):
if v > 0.0:
rand_intensity[ifreq, :] *= v**0.5
intensity[:, ichunk:ichunk+self.v1_chunk] = np.where(intensity_valid, intensity[:, ichunk:ichunk+self.v1_chunk], rand_intensity)
weights[:, ichunk:ichunk+self.v1_chunk] = np.repeat(self.running_weights, self.v1_chunk).reshape(self.nfreq, self.v1_chunk)
示例3: util_analysis
def util_analysis(arrps):
cpu_u, cpu_u_orig, dead_miss_orig, dead_miss = [], [], [], []
for ix, arrp in enumerate(arrps):
original_deadline_misses = len(arrp[(arrp['abs_deadline'] - arrp['abs_start'] < arrp['original_duration'])])*100.0/len(arrp)
deadline_misses = len(arrp[arrp['miss']==1])*100.0/len(arrp)
sum_my_offload_task_dur = sum(arrps[(ix+1)%3]['dur_offload'])
exp_dur = arrp['abs_end'][-1] - arrp['abs_start'][0]
original_cpu_util = sum(np.minimum(arrp['original_duration'], arrp['abs_deadline'] - arrp['abs_start']))*100.0/exp_dur
cpu_util = (sum_my_offload_task_dur + sum(np.minimum(arrp['duration'], arrp['abs_deadline'] - arrp['abs_start'])))*100.0/exp_dur
print 'CPU %d, Util %2.2f --> %2.2f, Deadline miss %2.5f --> %2.5f'%(ix, original_cpu_util, cpu_util, original_deadline_misses, deadline_misses)
cpu_u_orig.append(original_cpu_util)
cpu_u.append(cpu_util)
dead_miss_orig.append(original_deadline_misses)
dead_miss.append(deadline_misses)
result = [cpu_u, cpu_u_orig, dead_miss_orig, dead_miss]
return result
示例4: reflective_transformation
def reflective_transformation(y, lb, ub):
"""Compute reflective transformation and its gradient."""
if in_bounds(y, lb, ub):
return y, np.ones_like(y)
lb_finite = np.isfinite(lb)
ub_finite = np.isfinite(ub)
x = y.copy()
g_negative = np.zeros_like(y, dtype=bool)
mask = lb_finite & ~ub_finite
x[mask] = np.maximum(y[mask], 2 * lb[mask] - y[mask])
g_negative[mask] = y[mask] < lb[mask]
mask = ~lb_finite & ub_finite
x[mask] = np.minimum(y[mask], 2 * ub[mask] - y[mask])
g_negative[mask] = y[mask] > ub[mask]
mask = lb_finite & ub_finite
d = ub - lb
t = np.remainder(y[mask] - lb[mask], 2 * d[mask])
x[mask] = lb[mask] + np.minimum(t, 2 * d[mask] - t)
g_negative[mask] = t > d[mask]
g = np.ones_like(y)
g[g_negative] = -1
return x, g
示例5: compute_overlap
def compute_overlap(a, b):
"""
Parameters
----------
a: (N, 4) ndarray of float
b: (K, 4) ndarray of float
Returns
-------
overlaps: (N, K) ndarray of overlap between boxes and query_boxes
"""
area = (b[:, 2] - b[:, 0] + 1) * (b[:, 3] - b[:, 1] + 1)
iw = np.minimum(np.expand_dims(a[:, 2], axis=1), b[:, 2]) - np.maximum(np.expand_dims(a[:, 0], 1), b[:, 0]) + 1
ih = np.minimum(np.expand_dims(a[:, 3], axis=1), b[:, 3]) - np.maximum(np.expand_dims(a[:, 1], 1), b[:, 1]) + 1
iw = np.maximum(iw, 0)
ih = np.maximum(ih, 0)
ua = np.expand_dims((a[:, 2] - a[:, 0] + 1) * (a[:, 3] - a[:, 1] + 1), axis=1) + area - iw * ih
ua = np.maximum(ua, np.finfo(float).eps)
intersection = iw * ih
return intersection / ua
示例6: nms2d
def nms2d(boxes, overlap=0.3):
"""Compute the nms given a set of scored boxes,
as numpy array with 5 columns <x1> <y1> <x2> <y2> <score>
return the indices of the tubelets to keep
"""
if boxes.size == 0:
return np.array([],dtype=np.int32)
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
scores = boxes[:, 4]
areas = (x2-x1+1) * (y2-y1+1)
I = np.argsort(scores)
indices = np.zeros(scores.shape, dtype=np.int32)
counter = 0
while I.size > 0:
i = I[-1]
indices[counter] = i
counter += 1
xx1 = np.maximum(x1[i],x1[I[:-1]])
yy1 = np.maximum(y1[i],y1[I[:-1]])
xx2 = np.minimum(x2[i],x2[I[:-1]])
yy2 = np.minimum(y2[i],y2[I[:-1]])
inter = np.maximum(0.0, xx2 - xx1 + 1) * np.maximum(0.0, yy2 - yy1 + 1)
iou = inter / (areas[i] + areas[I[:-1]] - inter)
I = I[np.where(iou <= overlap)[0]]
return indices[:counter]
示例7: clip_upper
def clip_upper(arr,upper_bound):
"""
In-place, one-sided version of numpy.clip().
i.e. numpy.clip(arr,a_max=upper_bound,out=arr) if it existed.
"""
minimum(arr,upper_bound,arr)
示例8: connect_extrema
def connect_extrema(im_pos, target, markers, visualize=False):
'''
im_pos : XYZ positions of each point in image formation (n x m x 3)
'''
height, width,_ = im_pos.shape
centroid = np.array(target)
im_pos = np.ascontiguousarray(im_pos.astype(np.int16))
cost_map = np.ascontiguousarray(np.zeros([height, width], dtype=np.uint16))
extrema = dgn.geodesic_map_MPI(cost_map, im_pos, np.array(centroid, dtype=np.int16), 1, 1)
cost_map = extrema[-1]
trails = []
for m in markers:
trail = dgn.geodesic_trail(cost_map.copy()+(32000*(im_pos[:,:,2]==0)).astype(np.uint16), np.array(m, dtype=np.int16))
trails += [trail.copy()]
if visualize:
cost_map = deepcopy(cost_map)
circ = circle(markers[0][0],markers[0][1], 5)
circ = np.array([np.minimum(circ[0], height-1), np.minimum(circ[1], width-1)])
circ = np.array([np.maximum(circ[0], 0), np.maximum(circ[1], 0)])
cost_map[circ[0], circ[1]] = 0
for i,t in enumerate(trails[1:]):
# embed()
cost_map[t[:,0], t[:,1]] = 0
circ = circle(markers[i+1][0],markers[i+1][1], 5)
circ = np.array([np.minimum(circ[0], height-1), np.minimum(circ[1], width-1)])
circ = np.array([np.maximum(circ[0], 0), np.maximum(circ[1], 0)])
cost_map[circ[0], circ[1]] = 0
return trails, cost_map
else:
return trails
示例9: test_get_output_for
def test_get_output_for(self, ParametricRectifierLayer, init_alpha):
input_shape = (3, 3, 28, 28)
# random input tensor
input = np.random.randn(*input_shape).astype(theano.config.floatX)
# default: alphas shared only along 2nd axis
layer = ParametricRectifierLayer(input_shape, alpha=init_alpha)
alpha_v = layer.alpha.get_value()
expected = np.maximum(input, 0) + np.minimum(input, 0) * \
alpha_v[None, :, None, None]
assert np.allclose(layer.get_output_for(input).eval(), expected)
# scalar alpha
layer = ParametricRectifierLayer(input_shape, alpha=init_alpha,
shared_axes='all')
alpha_v = layer.alpha.get_value()
expected = np.maximum(input, 0) + np.minimum(input, 0) * alpha_v
assert np.allclose(layer.get_output_for(input).eval(), expected)
# alphas shared over the 1st axis
layer = ParametricRectifierLayer(input_shape, alpha=init_alpha,
shared_axes=0)
alpha_v = layer.alpha.get_value()
expected = np.maximum(input, 0) + np.minimum(input, 0) * \
alpha_v[None, :, :, :]
assert np.allclose(layer.get_output_for(input).eval(), expected)
# alphas shared over the 1st and 4th axes
layer = ParametricRectifierLayer(input_shape, shared_axes=(0, 3),
alpha=init_alpha)
alpha_v = layer.alpha.get_value()
expected = np.maximum(input, 0) + np.minimum(input, 0) * \
alpha_v[None, :, :, None]
assert np.allclose(layer.get_output_for(input).eval(), expected)
示例10: onmouse
def onmouse(event, x, y, flags, param):
global selection, drag_start, tracking_state, show_backproj, down_x, down_y, selcFrame
global mouseX, mouseY, trackBoxShow
x, y = np.int16([x, y]) #[sic] BUG
mouseX = x
mouseY = y
if event == cv2.EVENT_LBUTTONDOWN:
down_x = x
down_y = y
drag_start = (x, y)
tracking_state = 0
trackBoxShow = True
if event == cv2.EVENT_LBUTTONUP:
trackBoxShow = False
if drag_start:
if flags & cv2.EVENT_FLAG_LBUTTON:
h, w = selcFrame.shape[:2]
xo, yo = drag_start
x0, y0 = np.maximum(0, np.minimum([xo, yo], [x, y]))
x1, y1 = np.minimum([w, h], np.maximum([xo, yo], [x, y]))
selection = None
if x1-x0 > 0 and y1-y0 > 0:
selection = (x0, y0, x1, y1)
else:
drag_start = None
if selection is not None:
tracking_state = 1
示例11: __getitem__
def __getitem__(self, index):
if self._representation == 'mv':
representation_idx = 1
elif self._representation == 'residual':
representation_idx = 2
else:
representation_idx = 0
if self._is_train:
video_path, label, num_frames = random.choice(self._video_list)
else:
video_path, label, num_frames = self._video_list[index]
frames = []
for seg in range(self._num_segments):
if self._is_train:
gop_index, gop_pos = self._get_train_frame_index(num_frames, seg)
else:
gop_index, gop_pos = self._get_test_frame_index(num_frames, seg)
img = load(video_path, gop_index, gop_pos,
representation_idx, self._accumulate)
if img is None:
print('Error: loading video %s failed.' % video_path)
img = np.zeros((256, 256, 2)) if self._representation == 'mv' else np.zeros((256, 256, 3))
else:
if self._representation == 'mv':
img = clip_and_scale(img, 20)
img += 128
img = (np.minimum(np.maximum(img, 0), 255)).astype(np.uint8)
elif self._representation == 'residual':
img += 128
img = (np.minimum(np.maximum(img, 0), 255)).astype(np.uint8)
if self._representation == 'iframe':
img = color_aug(img)
# BGR to RGB. (PyTorch uses RGB according to doc.)
img = img[..., ::-1]
frames.append(img)
frames = self._transform(frames)
frames = np.array(frames)
frames = np.transpose(frames, (0, 3, 1, 2))
input = torch.from_numpy(frames).float() / 255.0
if self._representation == 'iframe':
input = (input - self._input_mean) / self._input_std
elif self._representation == 'residual':
input = (input - 0.5) / self._input_std
elif self._representation == 'mv':
input = (input - 0.5)
return input, label
示例12: calculate_coeff_proratisation
def calculate_coeff_proratisation(self, info_ind, trim_wage_regime, trim_wage_all):
''' Calcul du coefficient de proratisation '''
def _assurance_corrigee(trim_regime, agem):
'''
Deux types de corrections :
- correction de 1948-1982
- Détermination de la durée d'assurance corrigée introduite par la réforme Boulin
(majoration quand départ à la retraite après 65 ans) à partir de 1983'''
P = reduce(getattr, self.param_name.split('.'), self.P)
if P.prorat.dispositif == 1:
correction = (P.prorat.n_trim - trim_regime)/2
return trim_regime + correction
elif P.prorat.dispositif == 2:
age_taux_plein = P.decote.age_null
trim_majo = divide(agem - age_taux_plein, 3)*(agem > age_taux_plein)
elig_majo = (trim_regime < P.prorat.n_trim)
correction = trim_regime*P.tx_maj*trim_majo*elig_majo
return trim_regime + correction
else:
return trim_regime
P = reduce(getattr, self.param_name.split('.'), self.P)
trim_regime = trim_wage_regime['trimesters']['regime'].sum(1)
trim_regime_maj = sum(trim_wage_regime['maj'].values())
agem = info_ind['agem']
trim_regime = trim_regime_maj + trim_regime # _assurance_corrigee(trim_regime, agem)
#disposition pour montée en charge de la loi Boulin (ne s'applique qu'entre 72 et 74) :
if P.prorat.application_plaf == 1:
trim_regime = minimum(trim_regime, P.prorat.plaf)
CP = minimum(1, divide(trim_regime, P.prorat.n_trim))
return CP
示例13: minimum_pension
def minimum_pension(self, trim_wages_reg, trim_wages_all, pension_reg, pension_all):
''' MICO du régime général : allocation différentielle
RQ : ASPA et minimum vieillesse sont gérés par OF
Il est attribué quels que soient les revenus dont dispose le retraité en plus de ses pensions : loyers, revenus du capital, activité professionnelle...
+ mécanisme de répartition si cotisations à plusieurs régimes
TODO: coder toutes les évolutions et rebondissements 2004/2008'''
P = reduce(getattr, self.param_name.split('.'), self.P)
# pension_RG, pension, trim_RG, trim_cot, trim
trimesters = trim_wages_reg['trimesters']
trim_regime = trimesters['regime'].sum() + sum(trim_wages_reg['maj'].values())
coeff = minimum(1, divide(trim_regime, P.prorat.n_trim))
if P.mico.dispositif == 0:
# Avant le 1er janvier 1983, comparé à l'AVTS
min_pension = self.P.common.avts
return maximum(min_pension - pension_reg,0)*coeff
elif P.mico.dispositif == 1:
# TODO: Voir comment gérer la limite de cumul relativement complexe (Doc n°5 du COR)
mico = P.mico.entier
return maximum(mico - pension_reg,0)*coeff
elif P.mico.dispositif == 2:
# A partir du 1er janvier 2004 les périodes cotisées interviennent (+ dispositif transitoire de 2004)
nb_trim = P.prorat.n_trim
trim_regime = trimesters['regime'].sum() #+ sum(trim_wages_regime['maj'].values())
trim_cot_regime = sum(trimesters[key].sum() for key in trimesters.keys() if 'cot' in key)
mico_entier = P.mico.entier*minimum(divide(trim_regime, nb_trim), 1)
maj = (P.mico.entier_maj - P.mico.entier)*divide(trim_cot_regime, nb_trim)
mico = mico_entier + maj*(trim_cot_regime >= P.mico.trim_min)
return (mico - pension_reg)*(mico > pension_reg)*(pension_reg>0)
示例14: step
def step(self):
"""
Perform single automaton step.
"""
gsum = sum(self.grid)
# Compute burn touched cells
maximum(1, self.grid, self.burn_map)
self.burn_map -= 1
# Correlate cells for next set of fires
correlate(self.burn_map, self.spread, mode='constant', cval=0,
output=self.next_burn_map)
# And cutoff at 1 and multiply by grid to remove
# barren cells.
self.next_burn_map *= self.grid
minimum(1, self.next_burn_map, self.next_burn_map)
# Finally ignite next set of trees and top at barren
self.grid += self.next_burn_map
self.grid += self.burn_map
minimum(3, self.grid, self.grid)
if p.sleep:
__import__('time').sleep(p.sleep)
# No more fire?
return gsum < sum(self.grid)
示例15: test_elementwise_min_grad
def test_elementwise_min_grad(self, n, m, d, gc, dc):
go = np.random.rand(n, m, d).astype(np.float32)
X = np.random.rand(n, m, d).astype(np.float32)
Y = np.random.rand(n, m, d).astype(np.float32)
Z = np.random.rand(n, m, d).astype(np.float32)
mx = np.minimum(np.minimum(X, Y), Z)
inputs = [mx, go, X, Y, Z]
def min_grad_op(mx, go, X, Y, Z):
def mx_grad(a):
return go * (mx == a)
return [mx_grad(a) for a in [X, Y, Z]]
op = core.CreateOperator(
"MinGradient",
["mx", "go", "X", "Y", "Z"],
["gX", "gY", "gZ"]
)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=inputs,
reference=min_grad_op,
)
self.assertDeviceChecks(dc, op, inputs, [0, 1, 2])