本文整理汇总了Python中numpy.spacing方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.spacing方法的具体用法?Python numpy.spacing怎么用?Python numpy.spacing使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.spacing方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: validate_cov_matrix
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import spacing [as 别名]
def validate_cov_matrix(M):
M = (M + M.T) * 0.5
k = 0
I = np.eye(M.shape[0])
while True:
try:
_ = np.linalg.cholesky(M)
break
except np.linalg.LinAlgError:
# Find the nearest positive definite matrix for M. Modified from
# http://www.mathworks.com/matlabcentral/fileexchange/42885-nearestspd
# Might take several minutes
k += 1
w, v = np.linalg.eig(M)
min_eig = v.min()
M += (-min_eig * k * k + np.spacing(min_eig)) * I
return M
示例2: MeanPixelAccuracy
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import spacing [as 别名]
def MeanPixelAccuracy(pred, label):
"""
Function to compute the mean pixel accuracy for semantic segmentation between mini-batch tensors
:param pred: Tensor of predictions
:param label: Tensor of ground-truth
:return: Mean pixel accuracy for all the mini-bath
"""
# Convert tensors to numpy arrays
imPred = np.asarray(torch.squeeze(pred))
imLab = np.asarray(torch.squeeze(label))
# Create empty numpy arrays
pixel_accuracy = np.empty(imLab.shape[0])
pixel_correct = np.empty(imLab.shape[0])
pixel_labeled = np.empty(imLab.shape[0])
# Compute pixel accuracy for each pair of images in the batch
for i in range(imLab.shape[0]):
pixel_accuracy[i], pixel_correct[i], pixel_labeled[i] = pixelAccuracy(imPred[i], imLab[i])
# Compute the final accuracy for the batch
acc = 100.0 * np.sum(pixel_correct) / (np.spacing(1) + np.sum(pixel_labeled))
return acc
示例3: semanticIoU
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import spacing [as 别名]
def semanticIoU(pred, label):
"""
Computes the mean Intersection over Union for all the classes between two mini-batch tensors of semantic
segmentation
:param pred: Tensor of predictions
:param label: Tensor of ground-truth
:return: Mean semantic intersection over Union for all the classes
"""
imPred = np.asarray(torch.squeeze(pred))
imLab = np.asarray(torch.squeeze(label))
area_intersection = []
area_union = []
for i in range(imLab.shape[0]):
intersection, union = intersectionAndUnion(imPred[i], imLab[i])
area_intersection.append(intersection)
area_union.append(union)
IoU = 1.0 * np.sum(area_intersection, axis=0) / np.sum(np.spacing(1)+area_union, axis=0)
return np.mean(IoU)
示例4: oks_iou
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import spacing [as 别名]
def oks_iou(g, d, a_g, a_d, sigmas=None, in_vis_thre=None):
if not isinstance(sigmas, np.ndarray):
sigmas = np.array([.26, .25, .25, .35, .35, .79, .79, .72, .72, .62, .62, 1.07, 1.07, .87, .87, .89, .89]) / 10.0
vars = (sigmas * 2) ** 2
xg = g[0::3]
yg = g[1::3]
vg = g[2::3]
ious = np.zeros((d.shape[0]))
for n_d in range(0, d.shape[0]):
xd = d[n_d, 0::3]
yd = d[n_d, 1::3]
vd = d[n_d, 2::3]
dx = xd - xg
dy = yd - yg
e = (dx ** 2 + dy ** 2) / vars / ((a_g + a_d[n_d]) / 2 + np.spacing(1)) / 2
if in_vis_thre is not None:
ind = list(vg > in_vis_thre) and list(vd > in_vis_thre)
e = e[ind]
ious[n_d] = np.sum(np.exp(-e)) / e.shape[0] if e.shape[0] != 0 else 0.0
return ious
示例5: test_spacing_nextafter
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import spacing [as 别名]
def test_spacing_nextafter(self):
"""Test np.spacing and np.nextafter"""
# All non-negative finite #'s
a = np.arange(0x7c00, dtype=uint16)
hinf = np.array((np.inf,), dtype=float16)
a_f16 = a.view(dtype=float16)
assert_equal(np.spacing(a_f16[:-1]), a_f16[1:]-a_f16[:-1])
assert_equal(np.nextafter(a_f16[:-1], hinf), a_f16[1:])
assert_equal(np.nextafter(a_f16[0], -hinf), -a_f16[1])
assert_equal(np.nextafter(a_f16[1:], -hinf), a_f16[:-1])
# switch to negatives
a |= 0x8000
assert_equal(np.spacing(a_f16[0]), np.spacing(a_f16[1]))
assert_equal(np.spacing(a_f16[1:]), a_f16[:-1]-a_f16[1:])
assert_equal(np.nextafter(a_f16[0], hinf), -a_f16[1])
assert_equal(np.nextafter(a_f16[1:], hinf), a_f16[:-1])
assert_equal(np.nextafter(a_f16[:-1], -hinf), a_f16[1:])
示例6: intersectionAndUnion
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import spacing [as 别名]
def intersectionAndUnion(imPred, imLab, numClass):
"""
This function takes the prediction and label of a single image,
returns intersection and union areas for each class
To compute over many images do:
for i in range(Nimages):
(area_intersection[:,i], area_union[:,i]) = intersectionAndUnion(imPred[i], imLab[i])
IoU = 1.0 * np.sum(area_intersection, axis=1) / np.sum(np.spacing(1)+area_union, axis=1)
"""
# Remove classes from unlabeled pixels in gt image.
# We should not penalize detections in unlabeled portions of the image.
imPred = imPred * (imLab >= 0)
# Compute area intersection:
intersection = imPred * (imPred == imLab)
(area_intersection, _) = np.histogram(intersection, bins=numClass, range=(1, numClass))
# Compute area union:
(area_pred, _) = np.histogram(imPred, bins=numClass, range=(1, numClass))
(area_lab, _) = np.histogram(imLab, bins=numClass, range=(1, numClass))
area_union = area_pred + area_lab - area_intersection
return (area_intersection, area_union)
示例7: laplacian
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import spacing [as 别名]
def laplacian(W, normalized=True):
"""Return graph Laplacian"""
# Degree matrix.
d = W.sum(axis=0)
# Laplacian matrix.
if not normalized:
D = scipy.sparse.diags(d.A.squeeze(), 0)
L = D - W
else:
d += np.spacing(np.array(0, W.dtype))
d = 1 / np.sqrt(d)
D = scipy.sparse.diags(d.A.squeeze(), 0)
I = scipy.sparse.identity(d.size, dtype=W.dtype)
L = I - D * W * D
assert np.abs(L - L.T).mean() < 1e-9
assert type(L) is scipy.sparse.csr.csr_matrix
return L
示例8: compute_oks
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import spacing [as 别名]
def compute_oks(src_keypoints, src_roi, dst_keypoints, dst_roi):
"""Compute OKS for predicted keypoints wrt gt_keypoints.
src_keypoints: 4xK
src_roi: 4x1
dst_keypoints: Nx4xK
dst_roi: Nx4
"""
sigmas = np.array([
.26, .25, .25, .35, .35, .79, .79, .72, .72, .62, .62, 1.07, 1.07, .87,
.87, .89, .89]) / 10.0
vars = (sigmas * 2)**2
# area
src_area = (src_roi[2] - src_roi[0] + 1) * (src_roi[3] - src_roi[1] + 1)
# measure the per-keypoint distance if keypoints visible
dx = dst_keypoints[:, 0, :] - src_keypoints[0, :]
dy = dst_keypoints[:, 1, :] - src_keypoints[1, :]
e = (dx**2 + dy**2) / vars / (src_area + np.spacing(1)) / 2
e = np.sum(np.exp(-e), axis=1) / e.shape[1]
return e
示例9: intersectionAndUnion
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import spacing [as 别名]
def intersectionAndUnion(imPred, imLab, numClass):
"""
This function takes the prediction and label of a single image,
returns intersection and union areas for each class
To compute over many images do:
for i in range(Nimages):
(area_intersection[:,i], area_union[:,i]) = intersectionAndUnion(imPred[i], imLab[i])
IoU = 1.0 * np.sum(area_intersection, axis=1) / np.sum(np.spacing(1)+area_union, axis=1)
"""
# Remove classes from unlabeled pixels in gt image.
# We should not penalize detections in unlabeled portions of the image.
imPred = imPred * (imLab > 0)
# Compute area intersection:
intersection = imPred * (imPred == imLab)
(area_intersection, _) = np.histogram(intersection, bins=numClass, range=(1, numClass))
# Compute area union:
(area_pred, _) = np.histogram(imPred, bins=numClass, range=(1, numClass))
(area_lab, _) = np.histogram(imLab, bins=numClass, range=(1, numClass))
area_union = area_pred + area_lab - area_intersection
return (area_intersection, area_union)
示例10: _yeo_johnson_inverse_transform
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import spacing [as 别名]
def _yeo_johnson_inverse_transform(self, x, lmbda):
"""Return inverse-transformed input x following Yeo-Johnson inverse
transform with parameter lambda.
"""
x_inv = np.zeros_like(x)
pos = x >= 0
# when x >= 0
if abs(lmbda) < np.spacing(1.):
x_inv[pos] = np.exp(x[pos]) - 1
else: # lmbda != 0
x_inv[pos] = np.power(x[pos] * lmbda + 1, 1 / lmbda) - 1
# when x < 0
if abs(lmbda - 2) > np.spacing(1.):
x_inv[~pos] = 1 - np.power(-(2 - lmbda) * x[~pos] + 1,
1 / (2 - lmbda))
else: # lmbda == 2
x_inv[~pos] = 1 - np.exp(-x[~pos])
return x_inv
示例11: _yeo_johnson_transform
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import spacing [as 别名]
def _yeo_johnson_transform(self, x, lmbda):
"""Return transformed input x following Yeo-Johnson transform with
parameter lambda.
"""
out = np.zeros_like(x)
pos = x >= 0 # binary mask
# when x >= 0
if abs(lmbda) < np.spacing(1.):
out[pos] = np.log1p(x[pos])
else: # lmbda != 0
out[pos] = (np.power(x[pos] + 1, lmbda) - 1) / lmbda
# when x < 0
if abs(lmbda - 2) > np.spacing(1.):
out[~pos] = -(np.power(-x[~pos] + 1, 2 - lmbda) - 1) / (2 - lmbda)
else: # lmbda == 2
out[~pos] = -np.log1p(-x[~pos])
return out
示例12: laplacian
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import spacing [as 别名]
def laplacian(W, normalized=True):
"""Return the Laplacian of the weigth matrix."""
# Degree matrix.
d = W.sum(axis=0)
# Laplacian matrix.
if not normalized:
D = scipy.sparse.diags(d.A.squeeze(), 0)
L = D - W
else:
d += np.spacing(np.array(0, W.dtype))
d = 1 / np.sqrt(d)
D = scipy.sparse.diags(d.A.squeeze(), 0)
I = scipy.sparse.identity(d.size, dtype=W.dtype)
L = I - D * W * D
# assert np.abs(L - L.T).mean() < 1e-9
assert type(L) is scipy.sparse.csr.csr_matrix
return L
示例13: __rtruediv__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import spacing [as 别名]
def __rtruediv__(self, other):
""" Support for division .../G
"""
if not np.equal(*self._shape):
raise ValueError('Nonsquare systems cannot be inverted')
a, b, c, d = self._a, self._b, self._c, self._d
if np.any(svdvals(d) < np.spacing(1.)):
raise LinAlgError('The feedthrough term of the system is not'
' invertible.')
else:
# A-BD^{-1}C | BD^{-1}
# -----------|--------
# -D^{-1}C | D^{-1}
if self._isgain:
ai, bi, ci = None, None, None
else:
ai = a - b @ solve(d, c)
bi = (solve(d.T, b.T)).T
ci = -solve(d, c)
di = inv(d)
return other @ State(ai, bi, ci, di, dt=self._dt)
示例14: contFrac
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import spacing [as 别名]
def contFrac(self, x, a = 5., b = 0., c = 5./2.):
#initialize
k = 1 - 2*(a-b)
l = 2*(c-1)
d = 4*c*(c-1)
n = 4*b*(c-a)
A = np.ones(x.size)
B = np.ones(x.size)
G = np.ones(x.size)
Gprev = np.zeros(x.size)+2
counter = 0
#loop until convergence of continued fraction
while (np.max(np.abs(G-Gprev)) > self.epsmult*np.max(np.spacing(G))) and (counter < 1000):
k = -k
l = l+2.
d = d+4.*l
n = n+(1.+k)*l
A = d/(d - n*A*x)
B = (A-1.)*B
Gprev = G
G = G + B
counter += 1
if (counter == 1000):
raise ValueError('Failed to converge on G, most likely due to divergence in continued fractions.')
return G
示例15: calcSTM
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import spacing [as 别名]
def calcSTM(self,dt,j):
#allocate
u = 0
deltaU = 0
t = 0
counter = 0
#For elliptic orbits, calculate period effects
if self.beta[j] >0:
P = 2*np.pi*self.mu[j]*self.beta[j]**(-3./2.)
n = np.floor((dt + P/2 - 2*self.nu0[j]/self.beta[j])/P)
deltaU = 2*np.pi*n*self.beta[j]**(-5./2.)
#loop until convergence of the time array to the time step
while (np.max(np.abs(t-dt)) > self.epsmult*np.spacing(dt)) and (counter < 1000):
q = self.beta[j]*u**2./(1+self.beta[j]*u**2.)
U0w2 = 1. - 2.*q
U1w2 = 2.*(1.-q)*u
temp = self.contFrac(q)
U = 16./15.*U1w2**5.*temp + deltaU
U0 = 2.*U0w2**2.-1.
U1 = 2.*U0w2*U1w2
U2 = 2.*U1w2**2.
U3 = self.beta[j]*U + U1*U2/3.
r = self.r0norm[j]*U0 + self.nu0[j]*U1 + self.mu[j]*U2
t = self.r0norm[j]*U1 + self.nu0[j]*U2 + self.mu[j]*U3
u = u - (t-dt)/(4.*(1.-q)*r)
counter += 1
if (counter == 1000):
raise ValueError('Failed to converge on t: %e/%e'%(np.max(np.abs(t-dt)), self.epsmult*np.spacing(dt)))
#Kepler solution
f = 1 - self.mu[j]/self.r0norm[j]*U2
g = self.r0norm[j]*U1 + self.nu0[j]*U2
F = -self.mu[j]*U1/r/self.r0norm[j]
G = 1 - self.mu[j]/r*U2
Phi = np.vstack((np.hstack((np.eye(3)*f, np.eye(3)*g)),np.hstack((np.eye(3)*F, np.eye(3)*G))))
return Phi