Python numpy.linalg.svd() Examples

The following are code examples for showing how to use numpy.linalg.svd(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: razzy-spinner   Author: rafasashi   File: __init__.py    GNU General Public License v3.0 6 votes vote down vote up
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] 
Example 2
Project: LaserTOF   Author: kyleuckert   File: test_linalg.py    MIT License 6 votes vote down vote up
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))) 
Example 3
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_linalg.py    GNU General Public License v3.0 6 votes vote down vote up
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))) 
Example 4
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_linalg.py    MIT License 6 votes vote down vote up
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))) 
Example 5
Project: ocelot   Author: ocelot-collab   File: orbit_correction.py    GNU General Public License v3.0 6 votes vote down vote up
def apply_svd(self, resp_matrix, misallign, weight=None, alpha=1.e-4):
        #print resp_matrix
        if weight is None:
            weight = np.eye(len(misallign))
        resp_matrix_w = np.dot(weight, resp_matrix)
        misallign_w = np.dot(weight, misallign)
        U, s, V = svd(resp_matrix_w)
        #print (s)
        s_inv = np.zeros(len(s))
        for i in range(len(s)):
            #if s[i]<1./max(s):
            if s[i] < alpha:
                s_inv[i] = 0.
            else:
                s_inv[i] = 1./s[i]
        Sinv = np.zeros((np.shape(U)[0], np.shape(V)[0]))
        Sinv[:len(s), :len(s)] = np.diag(s_inv)
        Sinv = np.transpose(Sinv)
        A = np.dot(np.transpose(V), np.dot(Sinv, np.transpose(U)))
        angle = np.dot(A, misallign_w)
        return angle 
Example 6
Project: OpenNE   Author: thunlp   File: grarep.py    MIT License 5 votes vote down vote up
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)) 
Example 7
Project: OpenNE   Author: thunlp   File: tadw.py    MIT License 5 votes vote down vote up
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) 
Example 8
Project: LaserTOF   Author: kyleuckert   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b):
        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_(imply(isinstance(a, matrix), isinstance(u, matrix)))
        assert_(imply(isinstance(a, matrix), isinstance(vt, matrix))) 
Example 9
Project: LaserTOF   Author: kyleuckert   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_types(self):
        def check(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))

        for dtype in [single, double, csingle, cdouble]:
            yield check, dtype 
Example 10
Project: LaserTOF   Author: kyleuckert   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b):
        c = asarray(a)  # a might be a matrix
        s = linalg.svd(c, compute_uv=False)
        old_assert_almost_equal(
            s[..., 0] / s[..., -1], linalg.cond(a), decimal=5) 
Example 11
Project: LaserTOF   Author: kyleuckert   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b):
        c = asarray(a)  # a might be a matrix
        s = linalg.svd(c, compute_uv=False)
        old_assert_almost_equal(
            s[..., 0] / s[..., -1], linalg.cond(a, 2), decimal=5) 
Example 12
Project: LaserTOF   Author: kyleuckert   File: test_regression.py    MIT License 5 votes vote down vote up
def test_large_svd_32bit(self):
        # See gh-4442, 64bit would require very large/slow matrices.
        x = np.eye(1000, 66)
        np.linalg.svd(x) 
Example 13
Project: LaserTOF   Author: kyleuckert   File: test_regression.py    MIT License 5 votes vote down vote up
def test_svd_no_uv(self):
        # gh-4733
        for shape in (3, 4), (4, 4), (4, 3):
            for t in float, complex:
                a = np.ones(shape, dtype=t)
                w = linalg.svd(a, compute_uv=False)
                c = np.count_nonzero(np.absolute(w) > 0.5)
                assert_equal(c, 1)
                assert_equal(np.linalg.matrix_rank(a), 1)
                assert_array_less(1, np.linalg.norm(a, ord=2)) 
Example 14
Project: ABRW   Author: houchengbin   File: tadw.py    MIT License 5 votes vote down vote up
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)
            #from .utils import dim_reduction
            #self.features = dim_reduction(self.features, dim=200, method='svd') 
Example 15
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_linalg.py    MIT License 5 votes vote down vote up
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, hermitian=self.hermitian)
        assert_equal(s.dtype, get_real_dtype(dtype)) 
Example 16
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_linalg.py    MIT License 5 votes vote down vote up
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)) 
Example 17
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_linalg.py    MIT License 5 votes vote down vote up
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, hermitian=self.hermitian)
        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, hermitian=self.hermitian)
        assert_equal(u.shape, (0, 0))
        assert_equal(vh.shape, (4, 4))
        assert_equal(vh, np.eye(4)) 
Example 18
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b, tags):
        u, s, vt = linalg.svd(a, 0, hermitian=True)
        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)) 
Example 19
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b, tags):
        c = asarray(a)  # a might be a matrix
        if 'size-0' in tags:
            assert_raises(LinAlgError, linalg.cond, c)
            return

        # +-2 norms
        s = linalg.svd(c, compute_uv=False)
        assert_almost_equal(
            linalg.cond(a), s[..., 0] / s[..., -1],
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, 2), s[..., 0] / s[..., -1],
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, -2), s[..., -1] / s[..., 0],
            single_decimal=5, double_decimal=11)

        # Other norms
        cinv = np.linalg.inv(c)
        assert_almost_equal(
            linalg.cond(a, 1),
            abs(c).sum(-2).max(-1) * abs(cinv).sum(-2).max(-1),
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, -1),
            abs(c).sum(-2).min(-1) * abs(cinv).sum(-2).min(-1),
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, np.inf),
            abs(c).sum(-1).max(-1) * abs(cinv).sum(-1).max(-1),
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, -np.inf),
            abs(c).sum(-1).min(-1) * abs(cinv).sum(-1).min(-1),
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, 'fro'),
            np.sqrt((abs(c)**2).sum(-1).sum(-1)
                    * (abs(cinv)**2).sum(-1).sum(-1)),
            single_decimal=5, double_decimal=11) 
Example 20
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b, tags):
        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
        if m == 0:
            assert_((x == 0).all())
        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 np.asarray(b).ndim == 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_(consistent_subclass(x, b))
        assert_(consistent_subclass(residuals, b)) 
Example 21
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_regression.py    MIT License 5 votes vote down vote up
def test_svd_build(self):
        # Ticket 627.
        a = array([[0., 1.], [1., 1.], [2., 1.], [3., 1.]])
        m, n = a.shape
        u, s, vh = linalg.svd(a)

        b = dot(transpose(u[:, n:]), a)

        assert_array_almost_equal(b, np.zeros((2, 2))) 
Example 22
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_regression.py    MIT License 5 votes vote down vote up
def test_large_svd_32bit(self):
        # See gh-4442, 64bit would require very large/slow matrices.
        x = np.eye(1000, 66)
        np.linalg.svd(x) 
Example 23
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_regression.py    MIT License 5 votes vote down vote up
def test_svd_no_uv(self):
        # gh-4733
        for shape in (3, 4), (4, 4), (4, 3):
            for t in float, complex:
                a = np.ones(shape, dtype=t)
                w = linalg.svd(a, compute_uv=False)
                c = np.count_nonzero(np.absolute(w) > 0.5)
                assert_equal(c, 1)
                assert_equal(np.linalg.matrix_rank(a), 1)
                assert_array_less(1, np.linalg.norm(a, ord=2)) 
Example 24
Project: recruit   Author: Frank-qlu   File: test_linalg.py    Apache License 2.0 5 votes vote down vote up
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)) 
Example 25
Project: recruit   Author: Frank-qlu   File: test_linalg.py    Apache License 2.0 5 votes vote down vote up
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)) 
Example 26
Project: recruit   Author: Frank-qlu   File: test_linalg.py    Apache License 2.0 5 votes vote down vote up
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)) 
Example 27
Project: recruit   Author: Frank-qlu   File: test_linalg.py    Apache License 2.0 5 votes vote down vote up
def do(self, a, b, tags):
        c = asarray(a)  # a might be a matrix
        if 'size-0' in tags:
            assert_raises(LinAlgError, linalg.cond, c)
            return

        # +-2 norms
        s = linalg.svd(c, compute_uv=False)
        assert_almost_equal(
            linalg.cond(a), s[..., 0] / s[..., -1],
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, 2), s[..., 0] / s[..., -1],
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, -2), s[..., -1] / s[..., 0],
            single_decimal=5, double_decimal=11)

        # Other norms
        cinv = np.linalg.inv(c)
        assert_almost_equal(
            linalg.cond(a, 1),
            abs(c).sum(-2).max(-1) * abs(cinv).sum(-2).max(-1),
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, -1),
            abs(c).sum(-2).min(-1) * abs(cinv).sum(-2).min(-1),
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, np.inf),
            abs(c).sum(-1).max(-1) * abs(cinv).sum(-1).max(-1),
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, -np.inf),
            abs(c).sum(-1).min(-1) * abs(cinv).sum(-1).min(-1),
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, 'fro'),
            np.sqrt((abs(c)**2).sum(-1).sum(-1)
                    * (abs(cinv)**2).sum(-1).sum(-1)),
            single_decimal=5, double_decimal=11) 
Example 28
Project: recruit   Author: Frank-qlu   File: test_linalg.py    Apache License 2.0 5 votes vote down vote up
def test_basic_nonsvd(self):
        # Smoketest the non-svd norms
        A = array([[1., 0, 1], [0, -2., 0], [0, 0, 3.]])
        assert_almost_equal(linalg.cond(A, inf), 4)
        assert_almost_equal(linalg.cond(A, -inf), 2/3)
        assert_almost_equal(linalg.cond(A, 1), 4)
        assert_almost_equal(linalg.cond(A, -1), 0.5)
        assert_almost_equal(linalg.cond(A, 'fro'), np.sqrt(265 / 12)) 
Example 29
Project: recruit   Author: Frank-qlu   File: test_regression.py    Apache License 2.0 5 votes vote down vote up
def test_svd_build(self):
        # Ticket 627.
        a = array([[0., 1.], [1., 1.], [2., 1.], [3., 1.]])
        m, n = a.shape
        u, s, vh = linalg.svd(a)

        b = dot(transpose(u[:, n:]), a)

        assert_array_almost_equal(b, np.zeros((2, 2))) 
Example 30
Project: recruit   Author: Frank-qlu   File: test_regression.py    Apache License 2.0 5 votes vote down vote up
def test_large_svd_32bit(self):
        # See gh-4442, 64bit would require very large/slow matrices.
        x = np.eye(1000, 66)
        np.linalg.svd(x) 
Example 31
Project: recruit   Author: Frank-qlu   File: test_regression.py    Apache License 2.0 5 votes vote down vote up
def test_svd_no_uv(self):
        # gh-4733
        for shape in (3, 4), (4, 4), (4, 3):
            for t in float, complex:
                a = np.ones(shape, dtype=t)
                w = linalg.svd(a, compute_uv=False)
                c = np.count_nonzero(np.absolute(w) > 0.5)
                assert_equal(c, 1)
                assert_equal(np.linalg.matrix_rank(a), 1)
                assert_array_less(1, np.linalg.norm(a, ord=2)) 
Example 32
Project: OpenTDA   Author: outlace   File: matreduce.py    Apache License 2.0 5 votes vote down vote up
def reduce_matrix(A, eps=None):
    if np.size(A) == 0:
        return A, 0, 0
    if np.size(A) == 1:
        return A, 1, []

    m, n = A.shape
    if m != n:
        M = np.zeros(2 * (max(A.shape), ))
        M[:m, :n] = A
    else:
        M = A

    u, s, v = svd(M)
    if eps is None:
        eps = s.max() * max(M.shape) * np.finfo(s.dtype).eps

    null_mask = (s <= eps)

    rank = sum(~null_mask)
    null_space = v[null_mask]

    u = u[~null_mask][:, ~null_mask]
    s = np.diag(s[~null_mask])
    v = v[~null_mask]
    reduced = u.dot(s.dot(v))

    return reduced, rank, null_space 
Example 33
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
def do(self, a, b):
        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_(imply(isinstance(a, matrix), isinstance(u, matrix)))
        assert_(imply(isinstance(a, matrix), isinstance(vt, matrix))) 
Example 34
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
def test_types(self):
        def check(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))

        for dtype in [single, double, csingle, cdouble]:
            yield check, dtype 
Example 35
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
def do(self, a, b):
        c = asarray(a) # a might be a matrix
        s = linalg.svd(c, compute_uv=False)
        old_assert_almost_equal(s[0]/s[-1], linalg.cond(a), decimal=5) 
Example 36
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
def do(self, a, b):
        c = asarray(a) # a might be a matrix
        s = linalg.svd(c, compute_uv=False)
        old_assert_almost_equal(s[0]/s[-1], linalg.cond(a, 2), decimal=5) 
Example 37
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_regression.py    GNU General Public License v3.0 5 votes vote down vote up
def test_large_svd_32bit(self):
        # See gh-4442, 64bit would require very large/slow matrices.
        x = np.eye(1000, 66)
        np.linalg.svd(x) 
Example 38
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_regression.py    GNU General Public License v3.0 5 votes vote down vote up
def test_svd_no_uv(self):
        # gh-4733
        for shape in (3, 4), (4, 4), (4, 3):
            for t in float, complex:
                a = np.ones(shape, dtype=t)
                w = linalg.svd(a, compute_uv=False)
                c = np.count_nonzero(np.absolute(w) > 0.5)
                assert_equal(c, 1)
                assert_equal(np.linalg.matrix_rank(a), 1)
                assert_array_less(1, np.linalg.norm(a, ord=2)) 
Example 39
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: bench_decom.py    GNU General Public License v3.0 5 votes vote down vote up
def bench_svd():
    numpy_svd = nl.svd
    scipy_svd = sl.svd
    print()
    print('           Finding the SVD decomposition')
    print('      ==================================')
    print('      |    contiguous     |   non-contiguous ')
    print('----------------------------------------------')
    print(' size |  scipy  | numpy   |  scipy  | numpy ')

    for size,repeat in [(20,150),(100,7),(200,2)]:
        repeat *= 1
        print('%5s' % size, end=' ')
        sys.stdout.flush()

        a = random([size,size])

        print('| %6.2f ' % measure('scipy_svd(a)',repeat), end=' ')
        sys.stdout.flush()

        print('| %6.2f ' % measure('numpy_svd(a)',repeat), end=' ')
        sys.stdout.flush()

        a = a[-1::-1,-1::-1]  # turn into a non-contiguous array
        assert_(not a.flags['CONTIGUOUS'])

        print('| %6.2f ' % measure('scipy_svd(a)',repeat), end=' ')
        sys.stdout.flush()

        print('| %6.2f ' % measure('numpy_svd(a)',repeat), end=' ')
        sys.stdout.flush()

        print('   (secs for %s calls)' % (repeat)) 
Example 40
Project: brain_language_nlp   Author: mtoneva   File: ridge_tools.py    MIT License 5 votes vote down vote up
def ridge_svd(X,Y,lmbda):
    U, s, Vt = svd(X, full_matrices=False)
    d = s / (s** 2 + lmbda)
    return np.dot(Vt,np.diag(d).dot(U.T.dot(Y))) 
Example 41
Project: brain_language_nlp   Author: mtoneva   File: ridge_tools.py    MIT License 5 votes vote down vote up
def ridge_by_lambda_svd(X, Y, Xval, Yval, lambdas=np.array([0.1,1,10,100,1000])):
    error = np.zeros((lambdas.shape[0],Y.shape[1]))
    U, s, Vt = svd(X, full_matrices=False)
    for idx,lmbda in enumerate(lambdas):
        d = s / (s** 2 + lmbda)
        weights = np.dot(Vt,np.diag(d).dot(U.T.dot(Y)))
        error[idx] = 1 - R2(np.dot(Xval,weights),Yval)
    return error 
Example 42
Project: brain_language_nlp   Author: mtoneva   File: ridge_tools.py    MIT License 5 votes vote down vote up
def kernel_ridge_svd(X,Y,lmbda):
    U, s, Vt = svd(X.T, full_matrices=False)
    d = s / (s** 2 + lmbda)
    return np.dot(np.dot(U,np.diag(d).dot(Vt)),Y) 
Example 43
Project: brain_language_nlp   Author: mtoneva   File: ridge_tools.py    MIT License 5 votes vote down vote up
def kernel_ridge_by_lambda_svd(X, Y, Xval, Yval, lambdas=np.array([0.1,1,10,100,1000])):
    error = np.zeros((lambdas.shape[0],Y.shape[1]))
    U, s, Vt = svd(X.T, full_matrices=False)
    for idx,lmbda in enumerate(lambdas):
        d = s / (s** 2 + lmbda)
        weights = np.dot(np.dot(U,np.diag(d).dot(Vt)),Y)
        error[idx] = 1 - R2(np.dot(Xval,weights),Yval)
    return error 
Example 44
Project: scikit-tensor-py3   Author: evertrol   File: rescal.py    GNU General Public License v3.0 5 votes vote down vote up
def _updateR(X, A, lmbdaR):
    rank = A.shape[1]
    U, S, Vt = svd(A, full_matrices=False)
    Shat = np.kron(S, S)
    Shat = (Shat / (Shat ** 2 + lmbdaR)).reshape(rank, rank)
    R = []
    for i in range(len(X)):
        Rn = Shat * np.dot(U.T, X[i].dot(U))
        Rn = np.dot(Vt.T, np.dot(Rn, Vt))
        R.append(Rn)
    return R


# ------------------ Update Z ------------------------------------------------ 
Example 45
Project: scikit-tensor-py3   Author: evertrol   File: rescal.py    GNU General Public License v3.0 5 votes vote down vote up
def orth(A):
    [U, _, Vt] = svd(A, full_matrices=0)
    return np.dot(U, Vt) 
Example 46
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b, tags):
        if 'size-0' in tags:
            assert_raises(LinAlgError, linalg.svd, a, 0)
            return

        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)) 
Example 47
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_types(self):
        def check(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))

        for dtype in [single, double, csingle, cdouble]:
            check(dtype) 
Example 48
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_0_size(self):
        # These raise errors currently
        # (which does not mean that it may not make sense)
        a = np.zeros((0, 0), dtype=np.complex64)
        assert_raises(linalg.LinAlgError, linalg.svd, a)
        a = np.zeros((0, 1), dtype=np.complex64)
        assert_raises(linalg.LinAlgError, linalg.svd, a)
        a = np.zeros((1, 0), dtype=np.complex64)
        assert_raises(linalg.LinAlgError, linalg.svd, a) 
Example 49
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b, tags):
        c = asarray(a)  # a might be a matrix
        if 'size-0' in tags:
            assert_raises(LinAlgError, linalg.cond, c)
            return

        # +-2 norms
        s = linalg.svd(c, compute_uv=False)
        assert_almost_equal(
            linalg.cond(a), s[..., 0] / s[..., -1],
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, 2), s[..., 0] / s[..., -1],
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, -2), s[..., -1] / s[..., 0],
            single_decimal=5, double_decimal=11)

        # Other norms
        cinv = np.linalg.inv(c)
        assert_almost_equal(
            linalg.cond(a, 1),
            abs(c).sum(-2).max(-1) * abs(cinv).sum(-2).max(-1),
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, -1),
            abs(c).sum(-2).min(-1) * abs(cinv).sum(-2).min(-1),
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, np.inf),
            abs(c).sum(-1).max(-1) * abs(cinv).sum(-1).max(-1),
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, -np.inf),
            abs(c).sum(-1).min(-1) * abs(cinv).sum(-1).min(-1),
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, 'fro'),
            np.sqrt((abs(c)**2).sum(-1).sum(-1)
                    * (abs(cinv)**2).sum(-1).sum(-1)),
            single_decimal=5, double_decimal=11) 
Example 50
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_basic_nonsvd(self):
        # Smoketest the non-svd norms
        A = array([[1., 0, 1], [0, -2., 0], [0, 0, 3.]])
        assert_almost_equal(linalg.cond(A, inf), 4)
        assert_almost_equal(linalg.cond(A, -inf), 2/3)
        assert_almost_equal(linalg.cond(A, 1), 4)
        assert_almost_equal(linalg.cond(A, -1), 0.5)
        assert_almost_equal(linalg.cond(A, 'fro'), np.sqrt(265 / 12)) 
Example 51
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_regression.py    MIT License 5 votes vote down vote up
def test_svd_build(self):
        # Ticket 627.
        a = array([[0., 1.], [1., 1.], [2., 1.], [3., 1.]])
        m, n = a.shape
        u, s, vh = linalg.svd(a)

        b = dot(transpose(u[:, n:]), a)

        assert_array_almost_equal(b, np.zeros((2, 2))) 
Example 52
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_regression.py    MIT License 5 votes vote down vote up
def test_large_svd_32bit(self):
        # See gh-4442, 64bit would require very large/slow matrices.
        x = np.eye(1000, 66)
        np.linalg.svd(x) 
Example 53
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_regression.py    MIT License 5 votes vote down vote up
def test_svd_no_uv(self):
        # gh-4733
        for shape in (3, 4), (4, 4), (4, 3):
            for t in float, complex:
                a = np.ones(shape, dtype=t)
                w = linalg.svd(a, compute_uv=False)
                c = np.count_nonzero(np.absolute(w) > 0.5)
                assert_equal(c, 1)
                assert_equal(np.linalg.matrix_rank(a), 1)
                assert_array_less(1, np.linalg.norm(a, ord=2)) 
Example 54
Project: MARRtino-2.0   Author: DaniAffCH   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
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, hermitian=self.hermitian)
        assert_equal(s.dtype, get_real_dtype(dtype)) 
Example 55
Project: MARRtino-2.0   Author: DaniAffCH   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example 56
Project: MARRtino-2.0   Author: DaniAffCH   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
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, hermitian=self.hermitian)
        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, hermitian=self.hermitian)
        assert_equal(u.shape, (0, 0))
        assert_equal(vh.shape, (4, 4))
        assert_equal(vh, np.eye(4)) 
Example 57
Project: MARRtino-2.0   Author: DaniAffCH   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
def do(self, a, b, tags):
        u, s, vt = linalg.svd(a, 0, hermitian=True)
        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)) 
Example 58
Project: MARRtino-2.0   Author: DaniAffCH   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
def do(self, a, b, tags):
        c = asarray(a)  # a might be a matrix
        if 'size-0' in tags:
            assert_raises(LinAlgError, linalg.cond, c)
            return

        # +-2 norms
        s = linalg.svd(c, compute_uv=False)
        assert_almost_equal(
            linalg.cond(a), s[..., 0] / s[..., -1],
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, 2), s[..., 0] / s[..., -1],
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, -2), s[..., -1] / s[..., 0],
            single_decimal=5, double_decimal=11)

        # Other norms
        cinv = np.linalg.inv(c)
        assert_almost_equal(
            linalg.cond(a, 1),
            abs(c).sum(-2).max(-1) * abs(cinv).sum(-2).max(-1),
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, -1),
            abs(c).sum(-2).min(-1) * abs(cinv).sum(-2).min(-1),
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, np.inf),
            abs(c).sum(-1).max(-1) * abs(cinv).sum(-1).max(-1),
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, -np.inf),
            abs(c).sum(-1).min(-1) * abs(cinv).sum(-1).min(-1),
            single_decimal=5, double_decimal=11)
        assert_almost_equal(
            linalg.cond(a, 'fro'),
            np.sqrt((abs(c)**2).sum(-1).sum(-1)
                    * (abs(cinv)**2).sum(-1).sum(-1)),
            single_decimal=5, double_decimal=11) 
Example 59
Project: MARRtino-2.0   Author: DaniAffCH   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
def do(self, a, b, tags):
        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
        if m == 0:
            assert_((x == 0).all())
        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 np.asarray(b).ndim == 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_(consistent_subclass(x, b))
        assert_(consistent_subclass(residuals, b)) 
Example 60
Project: MARRtino-2.0   Author: DaniAffCH   File: test_regression.py    GNU General Public License v3.0 5 votes vote down vote up
def test_svd_build(self):
        # Ticket 627.
        a = array([[0., 1.], [1., 1.], [2., 1.], [3., 1.]])
        m, n = a.shape
        u, s, vh = linalg.svd(a)

        b = dot(transpose(u[:, n:]), a)

        assert_array_almost_equal(b, np.zeros((2, 2))) 
Example 61
Project: MARRtino-2.0   Author: DaniAffCH   File: test_regression.py    GNU General Public License v3.0 5 votes vote down vote up
def test_large_svd_32bit(self):
        # See gh-4442, 64bit would require very large/slow matrices.
        x = np.eye(1000, 66)
        np.linalg.svd(x) 
Example 62
Project: MARRtino-2.0   Author: DaniAffCH   File: test_regression.py    GNU General Public License v3.0 5 votes vote down vote up
def test_svd_no_uv(self):
        # gh-4733
        for shape in (3, 4), (4, 4), (4, 3):
            for t in float, complex:
                a = np.ones(shape, dtype=t)
                w = linalg.svd(a, compute_uv=False)
                c = np.count_nonzero(np.absolute(w) > 0.5)
                assert_equal(c, 1)
                assert_equal(np.linalg.matrix_rank(a), 1)
                assert_array_less(1, np.linalg.norm(a, ord=2)) 
Example 63
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b):
        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_(imply(isinstance(a, matrix), isinstance(u, matrix)))
        assert_(imply(isinstance(a, matrix), isinstance(vt, matrix))) 
Example 64
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_types(self):
        def check(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))

        for dtype in [single, double, csingle, cdouble]:
            yield check, dtype 
Example 65
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b):
        c = asarray(a)  # a might be a matrix
        s = linalg.svd(c, compute_uv=False)
        old_assert_almost_equal(
            s[..., 0] / s[..., -1], linalg.cond(a), decimal=5) 
Example 66
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b):
        c = asarray(a)  # a might be a matrix
        s = linalg.svd(c, compute_uv=False)
        old_assert_almost_equal(
            s[..., 0] / s[..., -1], linalg.cond(a, 2), decimal=5) 
Example 67
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_regression.py    MIT License 5 votes vote down vote up
def test_large_svd_32bit(self):
        # See gh-4442, 64bit would require very large/slow matrices.
        x = np.eye(1000, 66)
        np.linalg.svd(x) 
Example 68
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_regression.py    MIT License 5 votes vote down vote up
def test_svd_no_uv(self):
        # gh-4733
        for shape in (3, 4), (4, 4), (4, 3):
            for t in float, complex:
                a = np.ones(shape, dtype=t)
                w = linalg.svd(a, compute_uv=False)
                c = np.count_nonzero(np.absolute(w) > 0.5)
                assert_equal(c, 1)
                assert_equal(np.linalg.matrix_rank(a), 1)
                assert_array_less(1, np.linalg.norm(a, ord=2)) 
Example 69
Project: lsh   Author: dongguosheng   File: itqlsh.py    MIT License 5 votes vote down vote up
def train(self, arr):
        '''
        Train PCA and R.
        '''
        if not isinstance(arr, np.ndarray):
            raise Exception("arr type is %s, arr must be numpy.ndarray." % str(type(arr)))
        if self.n_bit <= 0 or self.n_dim <= 0:
            raise Exception("n_bit: %d, n_dim: %d\n" % (self.n_bit, self.n_dim))
        n_sample = int(arr.shape[0] * self.sample_rate)
        print 'Sample Num: %d' % n_sample
        for i in range(self.n_table):
            index = np.random.choice(arr.shape[0], n_sample, replace=False)
            sample_arr = arr[index, :]
            self.pca(arr)
            R = np.random.randn(self.n_bit, self.n_bit)
            R, _ = np.linalg.qr(R)  # get orthogonal matrix
            V = np.dot(sample_arr, self.pca_list[-1])
            for j in range(self.n_iter):
                print_str = '%d(%d), table %d\r' % (j+1, self.n_iter, i+1)
                sys.stdout.write(print_str)
                sys.stdout.flush()
                B = np.sign(np.dot(V, R))
                U, _, V = la.svd(np.dot(B.T, V))
                R = np.dot(V.T, U.T)    # transpose V or not?
            self.R_list.append(R)
        print '\ntrain complete.' 
Example 70
Project: SUSTechNRL   Author: fuguoji   File: grarep.py    MIT License 5 votes vote down vote up
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)) 
Example 71
Project: SUSTechNRL   Author: fuguoji   File: tadw.py    MIT License 5 votes vote down vote up
def preprocessFeature(self):
        U, S, VT = la.svd(self.features)
        Ud = U[:, 0:200]
        Sd = S[0:200]
        self.features = np.array(Ud)*Sd.reshape(200) 
Example 72
Project: EqHazard   Author: mauroalberti   File: array_utils.py    GNU General Public License v2.0 5 votes vote down vote up
def xyz_svd( xyz_array ):
    # modified after: 
    # http://stackoverflow.com/questions/15959411/best-fit-plane-algorithms-why-different-results-solved

    try:
        return dict( result = svd( xyz_array ) )
    except:
        return dict( result = None ) 
Example 73
Project: ocelot   Author: ocelot-collab   File: orbit_correction.py    GNU General Public License v3.0 5 votes vote down vote up
def apply(self):
        # print resp_matrix
        if self.weights is None:
            self.weights = np.eye(len(self.orbit))
        #print(np.shape(self.weights), np.shape(self.resp_matrix))
        resp_matrix = np.dot(self.weights, self.resp_matrix)
        misallign = np.dot(self.weights, self.orbit)
        # resp_matrix = self.resp_matrix
        # misallign = self.orbit
        #U, s, V = svd(resp_matrix_w)

        U, s, V = svd(resp_matrix)
        # print (s)
        s_inv = np.zeros(len(s))
        s_max = max(s)
        for i in range(len(s)):
            #print("S[",i,"]=", s[i], "s max = ", s_max)
            if i < int(len(s)/2.):
                epsilon = self.epsilon_x
            else:
                epsilon = self.epsilon_y
            if s[i] < s_max * epsilon:
                s_inv[i] = 0.
            else:
                s_inv[i] = 1. / s[i]
        #print(s_inv)
        Sinv = np.zeros((np.shape(U)[0], np.shape(V)[0]))
        Sinv[:len(s), :len(s)] = np.diag(s_inv)
        Sinv = np.transpose(Sinv)
        A = np.dot(np.transpose(V), np.dot(Sinv, np.transpose(U)))
        #angle = np.dot(A, misallign_w)
        angle = np.dot(A, misallign)
        #print(A)
        logger.debug("max(abs(angle)) = " + str(np.max(np.abs(angle))) + " min(abs(angle)) = " + str(np.min(np.abs(angle))))
        return angle 
Example 74
Project: dmrg   Author: GiggleLiu   File: testcontract.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        nsite=6   #number of sites
        hndim=2
        l=0
        vec=random.random(hndim**nsite)   #a random state in form of 1D array.
        vec2=random.random(hndim**nsite)  #a random state in form of 1D array.

        mps=state2MPS(vec,sitedim=hndim,l=l,method='svd')     #parse the state into a <MPS> instance.
        mps2=state2MPS(vec2,sitedim=hndim,l=l,method='svd')     #parse the state into a <MPS> instance.

        j1,j2=0.5,0.2
        scfg=SpinSpaceConfig([1,2])
        I=OpUnitI(hndim=hndim)
        Sz=opunit_Sz(spaceconfig=scfg)
        Sp=opunit_Sp(spaceconfig=scfg)
        Sm=opunit_Sm(spaceconfig=scfg)
        wi=zeros((4,4),dtype='O')
        wi[0,0],wi[1,0],wi[2,1],wi[3,1:]=I,Sz,I,(j1*Sz,j2*Sz,I)
        WL=[deepcopy(wi) for i in xrange(nsite)]
        WL[0]=WL[0][3:4]
        WL[-1]=WL[-1][:,:1]
        mpo=WL2MPO(WL)

        self.mps,self.mps2=mps,mps2
        self.mpo=mpo
        self.vec,self.vec2=vec,vec2
        self.spaceconfig=scfg 
Example 75
Project: vnpy_crypto   Author: birforce   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b, tags):
        if 'size-0' in tags:
            assert_raises(LinAlgError, linalg.svd, a, 0)
            return

        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_(imply(isinstance(a, matrix), isinstance(u, matrix)))
        assert_(imply(isinstance(a, matrix), isinstance(vt, matrix))) 
Example 76
Project: vnpy_crypto   Author: birforce   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_types(self):
        def check(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))

        for dtype in [single, double, csingle, cdouble]:
            yield check, dtype 
Example 77
Project: Efficient_Augmentation   Author: mkuchnik   File: PSD_util.py    MIT License 4 votes vote down vote up
def nearestPD(A):
    """Find the nearest positive-definite matrix to input

    A Python/Numpy port of John D'Errico's `nearestSPD` MATLAB code [1], which
    credits [2].

    [1] https://www.mathworks.com/matlabcentral/fileexchange/42885-nearestspd

    [2] N.J. Higham, "Computing a nearest symmetric positive semidefinite
    matrix" (1988): https://doi.org/10.1016/0024-3795(88)90223-6
    """

    B = (A + A.T) / 2
    _, s, V = la.svd(B)

    H = np.dot(V.T, np.dot(np.diag(s), V))

    A2 = (B + H) / 2

    A3 = (A2 + A2.T) / 2

    if isPD(A3):
        return A3

    spacing = np.spacing(la.norm(A))
    # The above is different from [1]. It appears that MATLAB's `chol` Cholesky
    # decomposition will accept matrixes with exactly 0-eigenvalue, whereas
    # Numpy's will not. So where [1] uses `eps(mineig)` (where `eps` is Matlab
    # for `np.spacing`), we use the above definition. CAVEAT: our `spacing`
    # will be much larger than [1]'s `eps(mineig)`, since `mineig` is usually on
    # the order of 1e-16, and `eps(1e-16)` is on the order of 1e-34, whereas
    # `spacing` will, for Gaussian random matrixes of small dimension, be on
    # othe order of 1e-16. In practice, both ways converge, as the unit test
    # below suggests.
    I = np.eye(A.shape[0])
    k = 1
    while not isPD(A3):
        mineig = np.min(np.real(la.eigvals(A3)))
        A3 += I * (-mineig * k**2 + spacing)
        k += 1

    return A3 
Example 78
Project: brain_language_nlp   Author: mtoneva   File: ridge_tools.py    MIT License 4 votes vote down vote up
def cross_val_ridge(train_features,train_data, n_splits = 10,
                    lambdas = np.array([10**i for i in range(-6,10)]),
                    method = 'plain',
                    do_plot = False):

    ridge_1 = dict(plain = ridge_by_lambda,
                   svd = ridge_by_lambda_svd,
                   kernel_ridge = kernel_ridge_by_lambda,
                   kernel_ridge_svd = kernel_ridge_by_lambda_svd,
                   ridge_sk = ridge_by_lambda_sk)[method]
    ridge_2 = dict(plain = ridge,
                   svd = ridge_svd,
                   kernel_ridge = kernel_ridge,
                   kernel_ridge_svd = kernel_ridge_svd,
                   ridge_sk = ridge_sk)[method]

    n_voxels = train_data.shape[1]
    nL = lambdas.shape[0]
    r_cv = np.zeros((nL, train_data.shape[1]))

    kf = KFold(n_splits=n_splits)
    start_t = time.time()
    for icv, (trn, val) in enumerate(kf.split(train_data)):
        #print('ntrain = {}'.format(train_features[trn].shape[0]))
        cost = ridge_1(train_features[trn],train_data[trn],
                               train_features[val],train_data[val],
                               lambdas=lambdas)
        if do_plot:
            import matplotlib.pyplot as plt
            plt.figure()
            plt.imshow(cost,aspect = 'auto')
        r_cv += cost
        #if icv%3 ==0:
        #    print(icv)
        #print('average iteration length {}'.format((time.time()-start_t)/(icv+1)))
    if do_plot:
        plt.figure()
        plt.imshow(r_cv,aspect='auto',cmap = 'RdBu_r');

    argmin_lambda = np.argmin(r_cv,axis = 0)
    weights = np.zeros((train_features.shape[1],train_data.shape[1]))
    for idx_lambda in range(lambdas.shape[0]): # this is much faster than iterating over voxels!
        idx_vox = argmin_lambda == idx_lambda
        weights[:,idx_vox] = ridge_2(train_features, train_data[:,idx_vox],lambdas[idx_lambda])
    if do_plot:
        plt.figure()
        plt.imshow(weights,aspect='auto',cmap = 'RdBu_r',vmin = -0.5,vmax = 0.5);

    return weights, np.array([lambdas[i] for i in argmin_lambda]) 
Example 79
Project: lps-anchor-pos-estimator   Author: bitcraze   File: tm_ransac_more_cols.py    GNU General Public License v2.0 4 votes vote down vote up
def tm_ransac_more_cols(d, sol, sys):
    r_c = d.shape
    n = r_c[1]
    d2 = d ** 2

    trycols = setdiff(range(0, n), sol.cols)

    cl, dl = compactionmatrix(len(sol.rows))

    u, s, vh = linalg.svd(sol.Bhat[1:, 1:])
    u = u[:, 0:2]

    for ii in trycols:

        d2n = d2[sol.rows - 1, ii - 1]
        maxnrinl = 0
        for kk in range(0, sys.ransac_k2):

            okrows = ((isfinite(d2n)).astype(int)).nonzero()
            tmp = random.permutation(len(okrows))

            if len(tmp) >= 4:

                tryrows1 = okrows[tmp[0:3]]

                zz = linalg.inv(dl) * sol.Bhat[:, 0]
                ZZ_1 = concatenate((zeros(1, 3), u))
                ZZ = concatenate((ones(len(sol.rows), 1), ZZ_1), 1)
                ZZ0 = linalg.inv(ZZ[tryrows1, :]) * (
                    d2n[tryrows1, 1] - zz[tryrows1, 1])

                xx = linalg.inv(ZZ[tryrows1, :]) * (
                    d2n[tryrows1, 1] - zz[tryrows1, 1])

                a = (zz[okrows] + ZZ[:, okrows] * xx)
                b = d2n[okrows]
                inlids = where(abs(b - a) < sys.ransac_threshold2)

                if len(inlids) < maxnrinl:
                    maxnrinl = len(inlids)

                    tmpsol = structtype()
                    tmpsol.rows = sol.rows[tryrows1]
                    tmpsol.col = ii
                    tmpsol.Bhatn = ZZ0 * xx
                    tmpsol.inlrows = sol.rows[okrows[inlids]]

        if maxnrinl > sys.min_inliers2:
            sol.cols = concatenate((sol.cols, tmpsol.col), 1)
            sol.inlmatrix[tmpsol.inlrows, tmpsol.col] = ones(
                len(tmpsol.inlrows), 1)
            sol.Bhat = concatenate((sol.Bhat, tmpsol.Bhatn), 1)
            sol.dl = compactionmatrix(len(sol.cols))

    return sol 
Example 80
Project: lps-anchor-pos-estimator   Author: bitcraze   File: tm_ransac_more_rows.py    GNU General Public License v2.0 4 votes vote down vote up
def tm_ransac_more_rows(d, sol, sys):
    r_c = d.shape
    d2 = d ** 2
    m = r_c[0]

    tryrows = setdiff(range(0, m), sol.rows)
    cr, dr = compactionmatrix(len(sol.cols))
    u, s, vh = linalg.svd(sol.Bhat[2:, 2:])
    v = vh.T
    v = (v[:, 0:2]).conj().T

    for ii in tryrows:

        d2n = d2[ii - 1, sol.cols - 1]

        maxnrinl = 0

        for kk in range(1, sys.ransac_k2 + 1):

            okcols = ((isfinite(d2n)).astype(int)).nonzero()
            tmp = random.permutation(len(okcols))

            if len(tmp) >= 4:

                trycols1 = okcols[tmp[0:3]]

                zz = sol.Bhat[0, :] * linalg.inv(dr.conj().T)
                ZZ_con1 = concatenate((zeros(3, 1), v), 1)
                ZZ = concatenate((ones(1, len(sol.cols)), ZZ_con1))
                ZZ0_1 = concatenate((1, zeros(1, len(sol.cols) - 1)), 1)
                ZZ0_2 = concatenate((zeros(3, 1), v), 1)
                ZZ0 = concatenate((ZZ0_1, ZZ0_2))

                xx = (d2n[0, trycols1] - zz[0, trycols1]) * linalg.inv(
                    ZZ[:, trycols1])

                a = (zz[okcols] + xx * ZZ[:, okcols])
                b = d2n[okcols]
                inlids = where(abs(b - a) < sys.ransac_threshold2)

                if len(inlids) > maxnrinl:
                    maxnrinl = len(inlids)
                    tmpsol = structtype()
                    tmpsol.row = ii
                    tmpsol.cols = sol.cols[trycols1]
                    tmpsol.Bhatn = xx * ZZ0
                    tmpsol.inlcols = sol.cols[okcols[inlids]]

        if maxnrinl > sys.min_inliers2:
            sol.rows = concatenate((sol.rows, tmpsol.row), 1)
            sol.inlmatrix[tmpsol.row, tmpsol.inlcols] = ones(
                1, len(tmpsol.inlcols))
            sol.Bhat = concatenate((sol.Bhat, tmpsol.Bhatn))
            sol.dl = compactionmatrix(len(sol.rows))

    return sol