本文整理汇总了Python中scipy.linalg.norm方法的典型用法代码示例。如果您正苦于以下问题:Python linalg.norm方法的具体用法?Python linalg.norm怎么用?Python linalg.norm使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.linalg
的用法示例。
在下文中一共展示了linalg.norm方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: doa
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import norm [as 别名]
def doa(self, receiver, source):
''' Computes the direction of arrival wrt a source and receiver '''
s_ind = self.key2ind(source)
r_ind = self.key2ind(receiver)
# vector from receiver to source
v = self.X[:,s_ind] - self.X[:,r_ind]
azimuth = np.arctan2(v[1], v[0])
elevation = np.arctan2(v[2], la.norm(v[:2]))
azimuth = azimuth + 2*np.pi if azimuth < 0. else azimuth
elevation = elevation + 2*np.pi if elevation < 0. else elevation
return np.array([azimuth, elevation])
示例2: nn
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import norm [as 别名]
def nn(model, text, vectors, query, k=5):
"""
Return the nearest neighbour sentences to query
text: list of sentences
vectors: the corresponding representations for text
query: a string to search
"""
qf = encode(model, [query])
qf /= norm(qf)
scores = numpy.dot(qf, vectors.T).flatten()
sorted_args = numpy.argsort(scores)[::-1]
sentences = [text[a] for a in sorted_args[:k]]
print 'QUERY: ' + query
print 'NEAREST: '
for i, s in enumerate(sentences):
print s, sorted_args[i]
示例3: _orthogonalize
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import norm [as 别名]
def _orthogonalize(X):
"""Orthogonalize every column of design `X` w.r.t preceding columns
Parameters
----------
X : array of shape(n, p)
the data to be orthogonalized
Returns
-------
X : array of shape(n, p)
the data after orthogonalization
Notes
-----
X is changed in place. The columns are not normalized.
"""
if X.size == X.shape[0]:
return X
from scipy.linalg import pinv, norm
for i in range(1, X.shape[1]):
X[:, i] -= np.dot(np.dot(X[:, i], X[:, :i]), pinv(X[:, :i]))
# X[:, i] /= norm(X[:, i])
return X
示例4: nn
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import norm [as 别名]
def nn(model, text, vectors, query, k=5):
"""
Return the nearest neighbour sentences to query
text: list of sentences
vectors: the corresponding representations for text
query: a string to search
"""
qf = encode(model, [query])
qf /= norm(qf)
scores = numpy.dot(qf, vectors.T).flatten()
sorted_args = numpy.argsort(scores)[::-1]
sentences = [text[a] for a in sorted_args[:k]]
print(('QUERY: ' + query))
print('NEAREST: ')
for i, s in enumerate(sentences):
print((s, sorted_args[i]))
示例5: norm_of_columns
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import norm [as 别名]
def norm_of_columns(A, p=2):
"""Vector p-norm of each column of a matrix.
Parameters
----------
A : array_like
Input matrix.
p : int, optional
p-th norm.
Returns
-------
array_like
p-norm of each column of A.
"""
_, N = A.shape
return np.asarray([linalg.norm(A[:, j], ord=p) for j in range(N)])
示例6: coherence_of_columns
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import norm [as 别名]
def coherence_of_columns(A):
"""Mutual coherence of columns of A.
Parameters
----------
A : array_like
Input matrix.
p : int, optional
p-th norm.
Returns
-------
array_like
Mutual coherence of columns of A.
"""
A = np.asmatrix(A)
_, N = A.shape
A = A * np.asmatrix(np.diag(1/norm_of_columns(A)))
Gram_A = A.H*A
for j in range(N):
Gram_A[j, j] = 0
return np.max(np.abs(Gram_A))
示例7: test_size
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import norm [as 别名]
def test_size():
np.random.seed(0)
N = 50
L = 12
n_features = 16
D = np.random.randn(L, n_features)
B = np.array(sp.sparse.random(N, L, density=0.5).todense())
X = np.dot(B, D)
dico1 = ApproximateKSVD(n_components=L, transform_n_nonzero_coefs=L)
dico1.fit(X)
gamma1 = dico1.transform(X)
e1 = norm(X - gamma1.dot(dico1.components_))
dico2 = DictionaryLearning(n_components=L, transform_n_nonzero_coefs=L)
dico2.fit(X)
gamma2 = dico2.transform(X)
e2 = norm(X - gamma2.dot(dico2.components_))
assert dico1.components_.shape == dico2.components_.shape
assert gamma1.shape == gamma2.shape
assert e1 < e2
示例8: test_amplitude_damping
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import norm [as 别名]
def test_amplitude_damping(self):
"""Test amplitude damping on a simple qubit state"""
# With probability 0
test_density_matrix = (
amplitude_damping_channel(self.density_matrix, 0, 1))
self.assertAlmostEquals(norm(self.density_matrix -
test_density_matrix), 0.0)
test_density_matrix = (
amplitude_damping_channel(self.density_matrix, 0, 1,
transpose=True))
self.assertAlmostEquals(norm(self.density_matrix -
test_density_matrix), 0.0)
# With probability 1
correct_density_matrix = zeros((4, 4), dtype=complex)
correct_density_matrix[2, 2] = 1
test_density_matrix = (
amplitude_damping_channel(self.density_matrix, 1, 1))
self.assertAlmostEquals(norm(correct_density_matrix -
test_density_matrix), 0.0)
示例9: test_jw_restrict_operator
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import norm [as 别名]
def test_jw_restrict_operator(self):
"""Test the scheme for restricting JW encoded operators to number"""
# Make a Hamiltonian that cares mostly about number of electrons
n_qubits = 6
target_electrons = 3
penalty_const = 100.
number_sparse = jordan_wigner_sparse(number_operator(n_qubits))
bias_sparse = jordan_wigner_sparse(
sum([FermionOperator(((i, 1), (i, 0)), 1.0) for i
in range(n_qubits)], FermionOperator()))
hamiltonian_sparse = penalty_const * (
number_sparse - target_electrons *
scipy.sparse.identity(2**n_qubits)).dot(
number_sparse - target_electrons *
scipy.sparse.identity(2**n_qubits)) + bias_sparse
restricted_hamiltonian = jw_number_restrict_operator(
hamiltonian_sparse, target_electrons, n_qubits)
true_eigvals, _ = eigh(hamiltonian_sparse.A)
test_eigvals, _ = eigh(restricted_hamiltonian.A)
self.assertAlmostEqual(norm(true_eigvals[:20] - test_eigvals[:20]),
0.0)
示例10: test_jw_number_restrict_state
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import norm [as 别名]
def test_jw_number_restrict_state(self):
n_qubits = numpy.random.randint(1, 12)
n_particles = numpy.random.randint(0, n_qubits)
number_indices = jw_number_indices(n_particles, n_qubits)
subspace_dimension = len(number_indices)
# Create a vector that has entry 1 for every coordinate with
# the specified particle number, and 0 everywhere else
vector = numpy.zeros(2**n_qubits, dtype=float)
vector[number_indices] = 1
# Restrict the vector
restricted_vector = jw_number_restrict_state(vector, n_particles)
# Check that it has the correct shape
self.assertEqual(restricted_vector.shape[0], subspace_dimension)
# Check that it has the same norm as the original vector
self.assertAlmostEqual(inner_product(vector, vector),
inner_product(restricted_vector,
restricted_vector))
示例11: test_twodiags
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import norm [as 别名]
def test_twodiags(self):
A = spdiags([[1, 2, 3, 4, 5], [6, 5, 8, 9, 10]], [0, 1], 5, 5)
b = array([1, 2, 3, 4, 5])
# condition number of A
cond_A = norm(A.todense(),2) * norm(inv(A.todense()),2)
for t in ['f','d','F','D']:
eps = finfo(t).eps # floating point epsilon
b = b.astype(t)
for format in ['csc','csr']:
Asp = A.astype(t).asformat(format)
x = spsolve(Asp,b)
assert_(norm(b - Asp*x) < 10 * cond_A * eps)
示例12: check_maxiter
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import norm [as 别名]
def check_maxiter(solver, case):
A = case.A
tol = 1e-12
b = arange(A.shape[0], dtype=float)
x0 = 0*b
residuals = []
def callback(x):
residuals.append(norm(b - case.A*x))
x, info = solver(A, b, x0=x0, tol=tol, maxiter=3, callback=callback)
assert_equal(len(residuals), 3)
assert_equal(info, 3)
示例13: __init__
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import norm [as 别名]
def __init__(self, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None,
iter=None, norm=maxnorm):
if f_tol is None:
f_tol = np.finfo(np.float_).eps ** (1./3)
if f_rtol is None:
f_rtol = np.inf
if x_tol is None:
x_tol = np.inf
if x_rtol is None:
x_rtol = np.inf
self.x_tol = x_tol
self.x_rtol = x_rtol
self.f_tol = f_tol
self.f_rtol = f_rtol
self.norm = maxnorm
self.iter = iter
self.f0_norm = None
self.iteration = 0
示例14: test_barycenter_kneighbors_graph
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import norm [as 别名]
def test_barycenter_kneighbors_graph():
X = np.array([[0, 1], [1.01, 1.], [2, 0]])
A = barycenter_kneighbors_graph(X, 1)
assert_array_almost_equal(
A.toarray(),
[[0., 1., 0.],
[1., 0., 0.],
[0., 1., 0.]])
A = barycenter_kneighbors_graph(X, 2)
# check that columns sum to one
assert_array_almost_equal(np.sum(A.toarray(), 1), np.ones(3))
pred = np.dot(A.toarray(), X)
assert_less(linalg.norm(pred - X) / X.shape[0], 1)
# ----------------------------------------------------------------------
# Test LLE by computing the reconstruction error on some manifolds.
示例15: test_rank_deficient_design
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import norm [as 别名]
def test_rank_deficient_design():
# consistency test that checks that LARS Lasso is handling rank
# deficient input data (with n_features < rank) in the same way
# as coordinate descent Lasso
y = [5, 0, 5]
for X in (
[[5, 0],
[0, 5],
[10, 10]],
[[10, 10, 0],
[1e-32, 0, 0],
[0, 0, 1]]
):
# To be able to use the coefs to compute the objective function,
# we need to turn off normalization
lars = linear_model.LassoLars(.1, normalize=False)
coef_lars_ = lars.fit(X, y).coef_
obj_lars = (1. / (2. * 3.)
* linalg.norm(y - np.dot(X, coef_lars_)) ** 2
+ .1 * linalg.norm(coef_lars_, 1))
coord_descent = linear_model.Lasso(.1, tol=1e-6, normalize=False)
coef_cd_ = coord_descent.fit(X, y).coef_
obj_cd = ((1. / (2. * 3.)) * linalg.norm(y - np.dot(X, coef_cd_)) ** 2
+ .1 * linalg.norm(coef_cd_, 1))
assert_less(obj_lars, obj_cd * (1. + 1e-8))