當前位置: 首頁>>代碼示例>>Python>>正文


Python linalg.svd方法代碼示例

本文整理匯總了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] 
開發者ID:rafasashi,項目名稱:razzy-spinner,代碼行數:26,代碼來源:__init__.py

示例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))) 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:26,代碼來源:test_linalg.py

示例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_) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:18,代碼來源:vecm.py

示例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) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:21,代碼來源:utils_old.py

示例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) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:21,代碼來源:tools.py

示例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 
開發者ID:Benardi,項目名稱:touvlo,代碼行數:18,代碼來源:pca.py

示例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 
開發者ID:aimi-cn,項目名稱:AILearners,代碼行數:18,代碼來源:svdRec.py

示例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) 
開發者ID:aimi-cn,項目名稱:AILearners,代碼行數:19,代碼來源:svdRec.py

示例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() 
開發者ID:X-DataInitiative,項目名稱:tick,代碼行數:22,代碼來源:prox_nuclear.py

示例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 
開發者ID:wmkouw,項目名稱:libTLDA,代碼行數:39,代碼來源:util.py

示例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)) 
開發者ID:thunlp,項目名稱:OpenNE,代碼行數:7,代碼來源:grarep.py

示例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) 
開發者ID:thunlp,項目名稱:OpenNE,代碼行數:8,代碼來源:tadw.py

示例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)) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:9,代碼來源:test_linalg.py

示例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)) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:10,代碼來源:test_linalg.py

示例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)) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:15,代碼來源:test_linalg.py


注:本文中的numpy.linalg.svd方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。