本文整理汇总了Python中numpy.linalg.norm方法的典型用法代码示例。如果您正苦于以下问题:Python linalg.norm方法的具体用法?Python linalg.norm怎么用?Python linalg.norm使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy.linalg
的用法示例。
在下文中一共展示了linalg.norm方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: preprocess_hog
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import norm [as 别名]
def preprocess_hog(digits):
samples = []
for img in digits:
gx = cv2.Sobel(img, cv2.CV_32F, 1, 0)
gy = cv2.Sobel(img, cv2.CV_32F, 0, 1)
mag, ang = cv2.cartToPolar(gx, gy)
bin_n = 16
bin = np.int32(bin_n*ang/(2*np.pi))
bin_cells = bin[:10,:10], bin[10:,:10], bin[:10,10:], bin[10:,10:]
mag_cells = mag[:10,:10], mag[10:,:10], mag[:10,10:], mag[10:,10:]
hists = [np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells)]
hist = np.hstack(hists)
# transform to Hellinger kernel
eps = 1e-7
hist /= hist.sum() + eps
hist = np.sqrt(hist)
hist /= norm(hist) + eps
samples.append(hist)
return np.float32(samples)
#不能保证包括所有省份
示例2: doAmplification
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import norm [as 别名]
def doAmplification(self, W, alpha):
self.rawAmplification = False
# #Step 1: Get the right singular vectors
# Mu = tde_mean(self.origDeltaCoords, W)
# (Y, S) = tde_rightsvd(self.origDeltaCoords, W, Mu)
#
# #Step 2: Choose which components to amplify by a visual inspection
# chooser = PCChooser(Y, (alpha, DEFAULT_NPCs))
# Alpha = chooser.getAlphaVec(alpha)
#Step 3: Perform the amplification
#Add the amplified delta coordinates back to the original delta coordinates
self.ampDeltaCoords = self.origDeltaCoords + subspace_tde_amplification(self.origDeltaCoords, self.origDeltaCoords.shape, W, alpha*np.ones((1,DEFAULT_NPCs)), self.origDeltaCoords.shape[1]/2)
# self.ampDeltaCoords = self.origDeltaCoords + tde_amplifyPCs(self.origDeltaCoords, W, Mu, Y, Alpha)
# print 'normalized error:',(linalg.norm(self.ampDeltaCoords-other_delta_coords)/linalg.norm(self.ampDeltaCoords))
# print "Finished Amplifying"
#Perform an amplification on the raw XYZ coordinates
示例3: test_GroupLasso_Lasso_equivalence
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import norm [as 别名]
def test_GroupLasso_Lasso_equivalence(sparse_X, fit_intercept, normalize):
"""Check that GroupLasso with groups of size 1 gives Lasso."""
n_features = 1000
X, y = build_dataset(
n_samples=100, n_features=n_features, sparse_X=sparse_X)
alpha_max = norm(X.T @ y, ord=np.inf) / len(y)
alpha = alpha_max / 10
clf = Lasso(alpha, tol=1e-12, fit_intercept=fit_intercept,
normalize=normalize, verbose=0)
clf.fit(X, y)
# take groups of size 1:
clf1 = GroupLasso(alpha=alpha, groups=1, tol=1e-12,
fit_intercept=fit_intercept, normalize=normalize,
verbose=0)
clf1.fit(X, y)
np.testing.assert_allclose(clf1.coef_, clf.coef_, atol=1e-6)
np.testing.assert_allclose(clf1.intercept_, clf.intercept_, rtol=1e-4)
示例4: test_MultiTaskLasso
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import norm [as 别名]
def test_MultiTaskLasso(fit_intercept):
"""Test that our MultiTaskLasso behaves as sklearn's."""
X, Y = build_dataset(n_samples=20, n_features=30, n_targets=10)
alpha_max = np.max(norm(X.T.dot(Y), axis=1)) / X.shape[0]
alpha = alpha_max / 2.
params = dict(alpha=alpha, fit_intercept=fit_intercept, tol=1e-10,
normalize=True)
clf = MultiTaskLasso(**params)
clf.verbose = 2
clf.fit(X, Y)
clf2 = sklearn_MultiTaskLasso(**params)
clf2.fit(X, Y)
np.testing.assert_allclose(clf.coef_, clf2.coef_, rtol=1e-5)
if fit_intercept:
np.testing.assert_allclose(clf.intercept_, clf2.intercept_)
clf.tol = 1e-7
check_estimator(clf)
示例5: test_celer_path_logreg
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import norm [as 别名]
def test_celer_path_logreg():
X, y = build_dataset(
n_samples=50, n_features=100, sparse_X=True)
y = np.sign(y)
alpha_max = norm(X.T.dot(y), ord=np.inf) / 2
alphas = alpha_max * np.geomspace(1, 1e-2, 10)
tol = 1e-8
coefs, Cs, n_iters = _logistic_regression_path(
X, y, Cs=1. / alphas, fit_intercept=False, penalty='l1',
solver='liblinear', tol=tol)
_, coefs_c, gaps = celer_path(
X, y, "logreg", alphas=alphas, tol=tol, verbose=2)
np.testing.assert_array_less(gaps, tol)
np.testing.assert_allclose(coefs != 0, coefs_c.T != 0)
np.testing.assert_allclose(coefs, coefs_c.T, atol=1e-5, rtol=1e-3)
示例6: test_Lasso
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import norm [as 别名]
def test_Lasso(sparse_X, fit_intercept, positive):
"""Test that our Lasso class behaves as sklearn's Lasso."""
X, y = build_dataset(n_samples=20, n_features=30, sparse_X=sparse_X)
if not positive:
alpha_max = norm(X.T.dot(y), ord=np.inf) / X.shape[0]
else:
alpha_max = X.T.dot(y).max() / X.shape[0]
alpha = alpha_max / 2.
params = dict(alpha=alpha, fit_intercept=fit_intercept, tol=1e-10,
normalize=True, positive=positive)
clf = Lasso(**params)
clf.fit(X, y)
clf2 = sklearn_Lasso(**params)
clf2.fit(X, y)
np.testing.assert_allclose(clf.coef_, clf2.coef_, rtol=1e-5)
if fit_intercept:
np.testing.assert_allclose(clf.intercept_, clf2.intercept_)
check_estimator(Lasso)
示例7: test_matrix_3x3
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import norm [as 别名]
def test_matrix_3x3(self):
# This test has been added because the 2x2 example
# happened to have equal nuclear norm and induced 1-norm.
# The 1/10 scaling factor accommodates the absolute tolerance
# used in assert_almost_equal.
A = (1 / 10) * \
self.array([[1, 2, 3], [6, 0, 5], [3, 2, 1]], dtype=self.dt)
assert_almost_equal(norm(A), (1 / 10) * 89 ** 0.5)
assert_almost_equal(norm(A, 'fro'), (1 / 10) * 89 ** 0.5)
assert_almost_equal(norm(A, 'nuc'), 1.3366836911774836)
assert_almost_equal(norm(A, inf), 1.1)
assert_almost_equal(norm(A, -inf), 0.6)
assert_almost_equal(norm(A, 1), 1.0)
assert_almost_equal(norm(A, -1), 0.4)
assert_almost_equal(norm(A, 2), 0.88722940323461277)
assert_almost_equal(norm(A, -2), 0.19456584790481812)
示例8: test_bad_args
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import norm [as 别名]
def test_bad_args(self):
# Check that bad arguments raise the appropriate exceptions.
A = self.array([[1, 2, 3], [4, 5, 6]], dtype=self.dt)
B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
# Using `axis=<integer>` or passing in a 1-D array implies vector
# norms are being computed, so also using `ord='fro'`
# or `ord='nuc'` raises a ValueError.
assert_raises(ValueError, norm, A, 'fro', 0)
assert_raises(ValueError, norm, A, 'nuc', 0)
assert_raises(ValueError, norm, [3, 4], 'fro', None)
assert_raises(ValueError, norm, [3, 4], 'nuc', None)
# Similarly, norm should raise an exception when ord is any finite
# number other than 1, 2, -1 or -2 when computing matrix norms.
for order in [0, 3]:
assert_raises(ValueError, norm, A, order, None)
assert_raises(ValueError, norm, A, order, (0, 1))
assert_raises(ValueError, norm, B, order, (1, 2))
# Invalid axis
assert_raises(np.AxisError, norm, B, None, 3)
assert_raises(np.AxisError, norm, B, None, (2, 3))
assert_raises(ValueError, norm, B, None, (0, 1, 2))
示例9: test_matrix_3x3
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import norm [as 别名]
def test_matrix_3x3(self):
# This test has been added because the 2x2 example
# happened to have equal nuclear norm and induced 1-norm.
# The 1/10 scaling factor accommodates the absolute tolerance
# used in assert_almost_equal.
A = (1 / 10) * \
np.array([[1, 2, 3], [6, 0, 5], [3, 2, 1]], dtype=self.dt)
assert_almost_equal(norm(A), (1 / 10) * 89 ** 0.5)
assert_almost_equal(norm(A, 'fro'), (1 / 10) * 89 ** 0.5)
assert_almost_equal(norm(A, 'nuc'), 1.3366836911774836)
assert_almost_equal(norm(A, inf), 1.1)
assert_almost_equal(norm(A, -inf), 0.6)
assert_almost_equal(norm(A, 1), 1.0)
assert_almost_equal(norm(A, -1), 0.4)
assert_almost_equal(norm(A, 2), 0.88722940323461277)
assert_almost_equal(norm(A, -2), 0.19456584790481812)
示例10: test_bad_args
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import norm [as 别名]
def test_bad_args(self):
# Check that bad arguments raise the appropriate exceptions.
A = array([[1, 2, 3], [4, 5, 6]], dtype=self.dt)
B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
# Using `axis=<integer>` or passing in a 1-D array implies vector
# norms are being computed, so also using `ord='fro'`
# or `ord='nuc'` raises a ValueError.
assert_raises(ValueError, norm, A, 'fro', 0)
assert_raises(ValueError, norm, A, 'nuc', 0)
assert_raises(ValueError, norm, [3, 4], 'fro', None)
assert_raises(ValueError, norm, [3, 4], 'nuc', None)
# Similarly, norm should raise an exception when ord is any finite
# number other than 1, 2, -1 or -2 when computing matrix norms.
for order in [0, 3]:
assert_raises(ValueError, norm, A, order, None)
assert_raises(ValueError, norm, A, order, (0, 1))
assert_raises(ValueError, norm, B, order, (1, 2))
# Invalid axis
assert_raises(ValueError, norm, B, None, 3)
assert_raises(ValueError, norm, B, None, (2, 3))
assert_raises(ValueError, norm, B, None, (0, 1, 2))
示例11: preprocess_hog
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import norm [as 别名]
def preprocess_hog(digits):
samples = []
for img in digits:
gx = cv2.Sobel(img, cv2.CV_32F, 1, 0)
gy = cv2.Sobel(img, cv2.CV_32F, 0, 1)
mag, ang = cv2.cartToPolar(gx, gy)
bin_n = 16
bin = np.int32(bin_n*ang/(2*np.pi))
bin_cells = bin[:10,:10], bin[10:,:10], bin[:10,10:], bin[10:,10:]
mag_cells = mag[:10,:10], mag[10:,:10], mag[:10,10:], mag[10:,10:]
hists = [np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells)]
hist = np.hstack(hists)
# transform to Hellinger kernel
eps = 1e-7
hist /= hist.sum() + eps
hist = np.sqrt(hist)
hist /= norm(hist) + eps
samples.append(hist)
return np.float32(samples)
示例12: test_norm
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import norm [as 别名]
def test_norm(ctx=default_context()):
try:
import scipy
assert LooseVersion(scipy.__version__) >= LooseVersion('0.1')
from scipy.linalg import norm as sp_norm
except (AssertionError, ImportError):
print("Could not import scipy.linalg.norm or scipy is too old. "
"Falling back to numpy.linalg.norm which is not numerically stable.")
from numpy.linalg import norm as sp_norm
def l1norm(input_data, axis=0, keepdims=False):
return np.sum(abs(input_data), axis=axis, keepdims=keepdims)
def l2norm(input_data, axis=0, keepdims=False):
return sp_norm(input_data, axis=axis, keepdims=keepdims)
in_data_dim = random_sample([4,5,6], 1)[0]
for force_reduce_dim1 in [True, False]:
in_data_shape = rand_shape_nd(in_data_dim)
if force_reduce_dim1:
in_data_shape = in_data_shape[:3] + (1, ) + in_data_shape[4:]
np_arr = np.random.uniform(-1, 1, in_data_shape).astype(np.float32)
mx_arr = mx.nd.array(np_arr, ctx=ctx)
for ord in [1, 2]:
for keep_dims in [True, False]:
for i in range(4):
npy_out = l1norm(np_arr, i, keep_dims) if ord == 1 else l2norm(
np_arr, i, keep_dims)
mx_out = mx.nd.norm(mx_arr, ord=ord, axis=i, keepdims=keep_dims)
assert npy_out.shape == mx_out.shape
mx.test_utils.assert_almost_equal(npy_out, mx_out.asnumpy())
if (i < 3):
npy_out = l1norm(np_arr, (i, i + 1), keep_dims) if ord == 1 else l2norm(
np_arr, (i, i + 1), keep_dims)
mx_out = mx.nd.norm(mx_arr, ord=ord, axis=(i, i + 1), keepdims=keep_dims)
assert npy_out.shape == mx_out.shape
mx.test_utils.assert_almost_equal(npy_out, mx_out.asnumpy())
示例13: distance
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import norm [as 别名]
def distance(self, vec1, vec2):
"""
Compute distance of two vector by consine distance
"""
super(ConsineDistance, self).distance(vec1, vec2) #super method
num = np.dot(vec1, vec2)
denom = linalg.norm(vec1) * linalg.norm(vec2)
if num == 0:
return 1
return - num / denom
#end ConsineDistance
示例14: _ecl_sim
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import norm [as 别名]
def _ecl_sim(inA, inB):
return 1.0 / (1.0 + la.norm(inA - inB))
# 皮尔逊相关系数,范围-1->+1, 越大越相似
示例15: _cos_sim
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import norm [as 别名]
def _cos_sim(inA, inB):
num = float(inB * inA.T)
de_nom = la.norm(inA) * la.norm(inB)
return 0.5 + 0.5 * (num / de_nom)