本文整理匯總了Python中numpy.maximum方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.maximum方法的具體用法?Python numpy.maximum怎麽用?Python numpy.maximum使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.maximum方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: generate_moving_mnist
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import maximum [as 別名]
def generate_moving_mnist(self, num_digits=2):
'''
Get random trajectories for the digits and generate a video.
'''
data = np.zeros((self.n_frames_total, self.image_size_, self.image_size_), dtype=np.float32)
for n in range(num_digits):
# Trajectory
start_y, start_x = self.get_random_trajectory(self.n_frames_total)
ind = random.randint(0, self.mnist.shape[0] - 1)
digit_image = self.mnist[ind]
for i in range(self.n_frames_total):
top = start_y[i]
left = start_x[i]
bottom = top + self.digit_size_
right = left + self.digit_size_
# Draw digit
data[i, top:bottom, left:right] = np.maximum(data[i, top:bottom, left:right], digit_image)
data = data[..., np.newaxis]
return data
示例2: detect
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import maximum [as 別名]
def detect(self, img):
"""
img: rgb 3 channel
"""
minsize = 20 # minimum size of face
threshold = [0.6, 0.7, 0.7] # three steps's threshold
factor = 0.709 # scale factor
bounding_boxes, _ = FaceDet.detect_face(
img, minsize, self.pnet, self.rnet, self.onet, threshold, factor)
area = (bounding_boxes[:, 2] - bounding_boxes[:, 0]) * (bounding_boxes[:, 3] - bounding_boxes[:, 1])
face_idx = area.argmax()
bbox = bounding_boxes[face_idx][:4] # xy,xy
margin = 32
x0 = np.maximum(bbox[0] - margin // 2, 0)
y0 = np.maximum(bbox[1] - margin // 2, 0)
x1 = np.minimum(bbox[2] + margin // 2, img.shape[1])
y1 = np.minimum(bbox[3] + margin // 2, img.shape[0])
x0, y0, x1, y1 = bbox = [int(k + 0.5) for k in [x0, y0, x1, y1]]
cropped = img[y0:y1, x0:x1, :]
scaled = cv2.resize(cropped, (160, 160), interpolation=cv2.INTER_LINEAR)
return scaled, bbox
示例3: crop
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import maximum [as 別名]
def crop(self, bbox):
"""See :func:`BaseInstanceMasks.crop`."""
assert isinstance(bbox, np.ndarray)
assert bbox.ndim == 1
# clip the boundary
bbox = bbox.copy()
bbox[0::2] = np.clip(bbox[0::2], 0, self.width)
bbox[1::2] = np.clip(bbox[1::2], 0, self.height)
x1, y1, x2, y2 = bbox
w = np.maximum(x2 - x1, 1)
h = np.maximum(y2 - y1, 1)
if len(self.masks) == 0:
cropped_masks = np.empty((0, h, w), dtype=np.uint8)
else:
cropped_masks = self.masks[:, y1:y1 + h, x1:x1 + w]
return BitmapMasks(cropped_masks, h, w)
示例4: apply_perturbations
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import maximum [as 別名]
def apply_perturbations(i, j, X, increase, theta, clip_min, clip_max):
"""
TensorFlow implementation for apply perturbations to input features based
on salency maps
:param i: index of first selected feature
:param j: index of second selected feature
:param X: a matrix containing our input features for our sample
:param increase: boolean; true if we are increasing pixels, false otherwise
:param theta: delta for each feature adjustment
:param clip_min: mininum value for a feature in our sample
:param clip_max: maximum value for a feature in our sample
: return: a perturbed input feature matrix for a target class
"""
# perturb our input sample
if increase:
X[0, i] = np.minimum(clip_max, X[0, i] + theta)
X[0, j] = np.minimum(clip_max, X[0, j] + theta)
else:
X[0, i] = np.maximum(clip_min, X[0, i] - theta)
X[0, j] = np.maximum(clip_min, X[0, j] - theta)
return X
示例5: backward
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import maximum [as 別名]
def backward(self, req, out_grad, in_data, out_data, in_grad, aux):
if ReluOp.guided_backprop:
# Get output and gradients of output
y = out_data[0]
dy = out_grad[0]
# Zero out the negatives in the gradients of the output
dy_positives = nd.maximum(dy, nd.zeros_like(dy))
# What output values were greater than 0?
y_ones = y.__gt__(0)
# Mask out the values for which at least one of dy or y is negative
dx = dy_positives * y_ones
self.assign(in_grad[0], req[0], dx)
else:
# Regular backward for ReLU
x = in_data[0]
x_gt_zero = x.__gt__(0)
dx = out_grad[0] * x_gt_zero
self.assign(in_grad[0], req[0], dx)
示例6: voc_ap
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import maximum [as 別名]
def voc_ap(rec, prec, use_07_metric=False):
if use_07_metric:
ap = 0.
for t in np.arange(0., 1.1, 0.1):
if np.sum(rec >= t) == 0:
p = 0
else:
p = np.max(prec[rec >= t])
ap += p / 11.
else:
# append sentinel values at both ends
mrec = np.concatenate(([0.], rec, [1.]))
mpre = np.concatenate(([0.], prec, [0.]))
# compute precision integration ladder
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
# look for recall value changes
i = np.where(mrec[1:] != mrec[:-1])[0]
# sum (\delta recall) * prec
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
return ap
示例7: test_quantize_float32_to_int8
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import maximum [as 別名]
def test_quantize_float32_to_int8():
shape = rand_shape_nd(4)
data = rand_ndarray(shape, 'default', dtype='float32')
min_range = mx.nd.min(data)
max_range = mx.nd.max(data)
qdata, min_val, max_val = mx.nd.contrib.quantize(data, min_range, max_range, out_type='int8')
data_np = data.asnumpy()
min_range = min_range.asscalar()
max_range = max_range.asscalar()
real_range = np.maximum(np.abs(min_range), np.abs(max_range))
quantized_range = 127.0
scale = quantized_range / real_range
assert qdata.dtype == np.int8
assert min_val.dtype == np.float32
assert max_val.dtype == np.float32
assert same(min_val.asscalar(), -real_range)
assert same(max_val.asscalar(), real_range)
qdata_np = (np.sign(data_np) * np.minimum(np.abs(data_np) * scale + 0.5, quantized_range)).astype(np.int8)
assert_almost_equal(qdata.asnumpy(), qdata_np, atol = 1)
示例8: heuristic_fn_vec
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import maximum [as 別名]
def heuristic_fn_vec(n1, n2, n_ori, step_size):
# n1 is a vector and n2 is a single point.
dx = (n1[:,0] - n2[0,0])/step_size
dy = (n1[:,1] - n2[0,1])/step_size
dt = n1[:,2] - n2[0,2]
dt = np.mod(dt, n_ori)
dt = np.minimum(dt, n_ori-dt)
if n_ori == 6:
if dx*dy > 0:
d = np.maximum(np.abs(dx), np.abs(dy))
else:
d = np.abs(dy-dx)
elif n_ori == 4:
d = np.abs(dx) + np.abs(dy)
return (d + dt).reshape((-1,1))
示例9: resize_maps
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import maximum [as 別名]
def resize_maps(map, map_scales, resize_method):
scaled_maps = []
for i, sc in enumerate(map_scales):
if resize_method == 'antialiasing':
# Resize using open cv so that we can compute the size.
# Use PIL resize to use anti aliasing feature.
map_ = cv2.resize(map*1, None, None, fx=sc, fy=sc, interpolation=cv2.INTER_LINEAR)
w = map_.shape[1]; h = map_.shape[0]
map_img = PIL.Image.fromarray((map*255).astype(np.uint8))
map__img = map_img.resize((w,h), PIL.Image.ANTIALIAS)
map_ = np.asarray(map__img).astype(np.float32)
map_ = map_/255.
map_ = np.minimum(map_, 1.0)
map_ = np.maximum(map_, 0.0)
elif resize_method == 'linear_noantialiasing':
map_ = cv2.resize(map*1, None, None, fx=sc, fy=sc, interpolation=cv2.INTER_LINEAR)
else:
logging.error('Unknown resizing method')
scaled_maps.append(map_)
return scaled_maps
示例10: intersection
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import maximum [as 別名]
def intersection(boxes1, boxes2):
"""Compute pairwise intersection areas between boxes.
Args:
boxes1: a numpy array with shape [N, 4] holding N boxes
boxes2: a numpy array with shape [M, 4] holding M boxes
Returns:
a numpy array with shape [N*M] representing pairwise intersection area
"""
[y_min1, x_min1, y_max1, x_max1] = np.split(boxes1, 4, axis=1)
[y_min2, x_min2, y_max2, x_max2] = np.split(boxes2, 4, axis=1)
all_pairs_min_ymax = np.minimum(y_max1, np.transpose(y_max2))
all_pairs_max_ymin = np.maximum(y_min1, np.transpose(y_min2))
intersect_heights = np.maximum(
np.zeros(all_pairs_max_ymin.shape),
all_pairs_min_ymax - all_pairs_max_ymin)
all_pairs_min_xmax = np.minimum(x_max1, np.transpose(x_max2))
all_pairs_max_xmin = np.maximum(x_min1, np.transpose(x_min2))
intersect_widths = np.maximum(
np.zeros(all_pairs_max_xmin.shape),
all_pairs_min_xmax - all_pairs_max_xmin)
return intersect_heights * intersect_widths
示例11: create_random_boxes
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import maximum [as 別名]
def create_random_boxes(num_boxes, max_height, max_width):
"""Creates random bounding boxes of specific maximum height and width.
Args:
num_boxes: number of boxes.
max_height: maximum height of boxes.
max_width: maximum width of boxes.
Returns:
boxes: numpy array of shape [num_boxes, 4]. Each row is in form
[y_min, x_min, y_max, x_max].
"""
y_1 = np.random.uniform(size=(1, num_boxes)) * max_height
y_2 = np.random.uniform(size=(1, num_boxes)) * max_height
x_1 = np.random.uniform(size=(1, num_boxes)) * max_width
x_2 = np.random.uniform(size=(1, num_boxes)) * max_width
boxes = np.zeros(shape=(num_boxes, 4))
boxes[:, 0] = np.minimum(y_1, y_2)
boxes[:, 1] = np.minimum(x_1, x_2)
boxes[:, 2] = np.maximum(y_1, y_2)
boxes[:, 3] = np.maximum(x_1, x_2)
return boxes.astype(np.float32)
示例12: nullspace
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import maximum [as 別名]
def nullspace(A, atol=1e-13, rtol=0):
"""
Compute an approximate basis for the nullspace of A.
INPUT (1) array 'A': 1-D array with length k will be treated
as a 2-D with shape (1, k).
(2) float 'atol': the absolute tolerance for a zero singular value.
Singular values smaller than `atol` are considered to be zero.
(3) float 'rtol': relative tolerance. Singular values less than
rtol*smax are considered to be zero, where smax is the largest
singular value.
If both `atol` and `rtol` are positive, the combined tolerance
is the maximum of the two; tol = max(atol, rtol * smax)
Singular values smaller than `tol` are considered to be zero.
OUTPUT (1) array 'B': if A is an array with shape (m, k), then B will be
an array with shape (k, n), where n is the estimated dimension
of the nullspace of A. The columns of B are a basis for the
nullspace; each element in np.dot(A, B) will be
approximately zero.
"""
# Expand A to a matrix
A = np.atleast_2d(A)
# Singular value decomposition
u, s, vh = al.svd(A)
# Set tolerance
tol = max(atol, rtol * s[0])
# Compute the number of non-zero entries
nnz = (s >= tol).sum()
# Conjugate and transpose to ensure real numbers
ns = vh[nnz:].conj().T
return ns
示例13: project_simplex
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import maximum [as 別名]
def project_simplex(self, v, z=1.0):
"""
Project vector onto simplex using sorting.
Reference: "Efficient Projections onto the L1-Ball for Learning in High
Dimensions (Duchi, Shalev-Shwartz, Singer, Chandra, 2006)."
Parameters
----------
v : array
vector to be projected (n dimensions by 0)
z : float
constant (def: 1.0)
Returns
-------
w : array
projected vector (n dimensions by 0)
"""
# Number of dimensions
n = v.shape[0]
# Sort vector
mu = np.sort(v, axis=0)[::-1]
# Find rho
C = np.cumsum(mu) - z
j = np.arange(n) + 1
rho = j[mu - C/j > 0][-1]
# Define theta
theta = C[mu - C/j > 0][-1] / float(rho)
# Subtract theta from original vector and cap at 0
w = np.maximum(v - theta, 0)
# Return projected vector
return w
示例14: iwe_kernel_densities
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import maximum [as 別名]
def iwe_kernel_densities(self, X, Z, clip=1000):
"""
Estimate importance weights based on kernel density estimation.
Parameters
----------
X : array
source data (N samples by D features)
Z : array
target data (M samples by D features)
clip : float
maximum allowed value for individual weights (def: 1000)
Returns
-------
array
importance weights (N samples by 1)
"""
# Data shapes
N, DX = X.shape
M, DZ = Z.shape
# Assert equivalent dimensionalities
assert DX == DZ
# Compute probabilities based on source kernel densities
pT = st.gaussian_kde(Z.T).pdf(X.T)
pS = st.gaussian_kde(X.T).pdf(X.T)
# Check for numerics
assert not np.any(np.isnan(pT)) or np.any(pT == 0)
assert not np.any(np.isnan(pS)) or np.any(pS == 0)
# Compute importance weights
iw = pT / pS
# Clip importance weights
return np.minimum(clip, np.maximum(0, iw))
示例15: __init__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import maximum [as 別名]
def __init__(self, nelx, nely, rmin):
"""
Filter: Build (and assemble) the index+data vectors for the coo matrix
format.
"""
nfilter = int(nelx * nely * ((2 * (np.ceil(rmin) - 1) + 1)**2))
iH = np.zeros(nfilter)
jH = np.zeros(nfilter)
sH = np.zeros(nfilter)
cc = 0
for i in range(nelx):
for j in range(nely):
row = i * nely + j
kk1 = int(np.maximum(i - (np.ceil(rmin) - 1), 0))
kk2 = int(np.minimum(i + np.ceil(rmin), nelx))
ll1 = int(np.maximum(j - (np.ceil(rmin) - 1), 0))
ll2 = int(np.minimum(j + np.ceil(rmin), nely))
for k in range(kk1, kk2):
for l in range(ll1, ll2):
col = k * nely + l
fac = rmin - np.sqrt(
((i - k) * (i - k) + (j - l) * (j - l)))
iH[cc] = row
jH[cc] = col
sH[cc] = np.maximum(0.0, fac)
cc = cc + 1
# Finalize assembly and convert to csc format
self.H = scipy.sparse.coo_matrix((sH, (iH, jH)),
shape=(nelx * nely, nelx * nely)).tocsc()
self.Hs = self.H.sum(1)