本文整理汇总了Python中numpy.linalg.svd方法的典型用法代码示例。如果您正苦于以下问题:Python linalg.svd方法的具体用法?Python linalg.svd怎么用?Python linalg.svd使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy.linalg
的用法示例。
在下文中一共展示了linalg.svd方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: cluster
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import svd [as 别名]
def cluster(self, vectors, assign_clusters=False, trace=False):
assert len(vectors) > 0
# normalise the vectors
if self._should_normalise:
vectors = map(self._normalise, vectors)
# use SVD to reduce the dimensionality
if self._svd_dimensions and self._svd_dimensions < len(vectors[0]):
[u, d, vt] = linalg.svd(numpy.transpose(array(vectors)))
S = d[:self._svd_dimensions] * \
numpy.identity(self._svd_dimensions, numpy.Float64)
T = u[:,:self._svd_dimensions]
Dt = vt[:self._svd_dimensions,:]
vectors = numpy.transpose(numpy.matrixmultiply(S, Dt))
self._Tt = numpy.transpose(T)
# call abstract method to cluster the vectors
self.cluster_vectorspace(vectors, trace)
# assign the vectors to clusters
if assign_clusters:
print self._Tt, vectors
return [self.classify(vector) for vector in vectors]
示例2: do
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import svd [as 别名]
def do(self, a, b):
arr = np.asarray(a)
m, n = arr.shape
u, s, vt = linalg.svd(a, 0)
x, residuals, rank, sv = linalg.lstsq(a, b)
if m <= n:
assert_almost_equal(b, dot(a, x))
assert_equal(rank, m)
else:
assert_equal(rank, n)
assert_almost_equal(sv, sv.__array_wrap__(s))
if rank == n and m > n:
expect_resids = (
np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
expect_resids = np.asarray(expect_resids)
if len(np.asarray(b).shape) == 1:
expect_resids.shape = (1,)
assert_equal(residuals.shape, expect_resids.shape)
else:
expect_resids = np.array([]).view(type(x))
assert_almost_equal(residuals, expect_resids)
assert_(np.issubdtype(residuals.dtype, np.floating))
assert_(imply(isinstance(b, matrix), isinstance(x, matrix)))
assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix)))
示例3: _mat_sqrt
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import svd [as 别名]
def _mat_sqrt(_2darray):
"""Calculates the square root of a matrix.
Parameters
----------
_2darray : ndarray
A 2-dimensional ndarray representing a square matrix.
Returns
-------
result : ndarray
Square root of the matrix given as function argument.
"""
u_, s_, v_ = svd(_2darray, full_matrices=False)
s_ = np.sqrt(s_)
return u_.dot(s_[:, None] * v_)
示例4: fullrank
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import svd [as 别名]
def fullrank(X, r=None):
"""
Return a matrix whose column span is the same as X.
If the rank of X is known it can be specified as r -- no check
is made to ensure that this really is the rank of X.
"""
if r is None:
r = rank(X)
V, D, U = L.svd(X, full_matrices=0)
order = np.argsort(D)
order = order[::-1]
value = []
for i in range(r):
value.append(V[:,order[i]])
return np.asarray(np.transpose(value)).astype(np.float64)
示例5: fullrank
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import svd [as 别名]
def fullrank(X, r=None):
"""
Return a matrix whose column span is the same as X.
If the rank of X is known it can be specified as r -- no check
is made to ensure that this really is the rank of X.
"""
if r is None:
r = np_matrix_rank(X)
V, D, U = L.svd(X, full_matrices=0)
order = np.argsort(D)
order = order[::-1]
value = []
for i in range(r):
value.append(V[:, order[i]])
return np.asarray(np.transpose(value)).astype(np.float64)
示例6: pca
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import svd [as 别名]
def pca(X):
"""Runs Principal Component Analysis on dataset
Args:
X (numpy.array): Features' dataset
Returns:
(numpy.array, numpy.array): A 2-tuple of U, eigenvectors of covariance
matrix, and S, eigenvalues (on diagonal) of covariance matrix.
"""
m, n = X.shape
Sigma = (1 / m) * X.T.dot(X)
U, S, V = svd(Sigma)
S = diag(S)
return U, S
示例7: svdEst
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import svd [as 别名]
def svdEst(dataMat, user, simMeas, item):
n = shape(dataMat)[1]
simTotal = 0.0; ratSimTotal = 0.0
U,Sigma,VT = la.svd(dataMat)
Sig4 = mat(eye(4)*Sigma[:4]) #arrange Sig4 into a diagonal matrix
xformedItems = dataMat.T * U[:,:4] * Sig4.I #create transformed items
for j in range(n):
userRating = dataMat[user,j]
if userRating == 0 or j==item: continue
similarity = simMeas(xformedItems[item,:].T,\
xformedItems[j,:].T)
print 'the %d and %d similarity is: %f' % (item, j, similarity)
simTotal += similarity
ratSimTotal += similarity * userRating
if simTotal == 0: return 0
else: return ratSimTotal/simTotal
示例8: imgCompress
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import svd [as 别名]
def imgCompress(numSV=3, thresh=0.8):
myl = []
for line in open('0_5.txt').readlines():
newRow = []
for i in range(32):
newRow.append(int(line[i]))
myl.append(newRow)
myMat = mat(myl)
print "****original matrix******"
printMat(myMat, thresh)
U,Sigma,VT = la.svd(myMat)
SigRecon = mat(zeros((numSV, numSV)))
for k in range(numSV):#construct diagonal matrix from vector
SigRecon[k,k] = Sigma[k]
reconMat = U[:,:numSV]*SigRecon*VT[:numSV,:]
print "****reconstructed matrix using %d singular values******" % numSV
printMat(reconMat, thresh)
示例9: value
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import svd [as 别名]
def value(self, coeffs: np.ndarray):
"""
Returns the value of the penalization at ``coeffs``
Parameters
----------
coeffs : `numpy.ndarray`, shape=(n_coeffs,)
The value of the penalization is computed at this point
Returns
-------
output : `float`
Value of the penalization at ``coeffs``
"""
x = self._get_matrix(coeffs)
if x.shape[0] != x.shape[1]:
raise ValueError('Prox nuclear must be called on a squared matrix'
', received {} np.ndarray'.format(x.shape))
s = svd(x, compute_uv=False, full_matrices=False)
return self.strength * s.sum()
示例10: nullspace
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import svd [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
示例11: GetRepUseSVD
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import svd [as 别名]
def GetRepUseSVD(self, probTranMat, alpha):
U, S, VT = la.svd(probTranMat)
Ud = U[:, 0:self.dim]
Sd = S[0:self.dim]
return np.array(Ud)*np.power(Sd, alpha).reshape((self.dim))
示例12: preprocessFeature
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import svd [as 别名]
def preprocessFeature(self):
if self.features.shape[1] > 200:
U, S, VT = la.svd(self.features)
Ud = U[:, 0:200]
Sd = S[0:200]
self.features = np.array(Ud)*Sd.reshape(200)
示例13: do
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import svd [as 别名]
def do(self, a, b, tags):
u, s, vt = linalg.svd(a, 0)
assert_allclose(a, dot_generalized(np.asarray(u) * np.asarray(s)[..., None, :],
np.asarray(vt)),
rtol=get_rtol(u.dtype))
assert_(consistent_subclass(u, a))
assert_(consistent_subclass(vt, a))
示例14: test_types
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import svd [as 别名]
def test_types(self, dtype):
x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
u, s, vh = linalg.svd(x)
assert_equal(u.dtype, dtype)
assert_equal(s.dtype, get_real_dtype(dtype))
assert_equal(vh.dtype, dtype)
s = linalg.svd(x, compute_uv=False)
assert_equal(s.dtype, get_real_dtype(dtype))
示例15: test_empty_identity
# 需要导入模块: from numpy import linalg [as 别名]
# 或者: from numpy.linalg import svd [as 别名]
def test_empty_identity(self):
""" Empty input should put an identity matrix in u or vh """
x = np.empty((4, 0))
u, s, vh = linalg.svd(x, compute_uv=True)
assert_equal(u.shape, (4, 4))
assert_equal(vh.shape, (0, 0))
assert_equal(u, np.eye(4))
x = np.empty((0, 4))
u, s, vh = linalg.svd(x, compute_uv=True)
assert_equal(u.shape, (0, 0))
assert_equal(vh.shape, (4, 4))
assert_equal(vh, np.eye(4))