Python numpy.linalg.lstsq() Examples

The following are 30 code examples of numpy.linalg.lstsq(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module numpy.linalg , or try the search function .
Example #1
Source File: costautoregressive.py    From ruptures with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def error(self, start, end):
        """Return the approximation cost on the segment [start:end].

        Args:
            start (int): start of the segment
            end (int): end of the segment

        Returns:
            float: segment cost

        Raises:
            NotEnoughPoints: when the segment is too short (less than ``'min_size'`` samples).
        """
        if end - start < self.min_size:
            raise NotEnoughPoints
        y, X = self.signal[start:end], self.covar[start:end]
        _, residual, _, _ = lstsq(X, y, rcond=None)
        return residual.sum() 
Example #2
Source File: test_linalg.py    From Computable with 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 = 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
Source File: test_linalg.py    From auto-alt-text-lambda-api with 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 #4
Source File: test_linalg.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_future_rcond(self):
        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
                      [0., 2.,  0.,  0.,  1.,  0.],
                      [1., 0.,  1.,  0.,  0.,  4.],
                      [0., 0.,  0.,  2.,  3.,  0.]]).T

        b = np.array([1, 0, 0, 0, 0, 0])
        with suppress_warnings() as sup:
            w = sup.record(FutureWarning, "`rcond` parameter will change")
            x, residuals, rank, s = linalg.lstsq(a, b)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
            assert_(rank == 3)
            # Warning should be raised exactly once (first command)
            assert_(len(w) == 1) 
Example #5
Source File: test_linalg.py    From lambda-packs with 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 #6
Source File: test_linalg.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_future_rcond(self):
        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
                      [0., 2.,  0.,  0.,  1.,  0.],
                      [1., 0.,  1.,  0.,  0.,  4.],
                      [0., 0.,  0.,  2.,  3.,  0.]]).T

        b = np.array([1, 0, 0, 0, 0, 0])
        with suppress_warnings() as sup:
            w = sup.record(FutureWarning, "`rcond` parameter will change")
            x, residuals, rank, s = linalg.lstsq(a, b)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
            assert_(rank == 3)
            # Warning should be raised exactly once (first command)
            assert_(len(w) == 1) 
Example #7
Source File: test_linalg.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def test_future_rcond(self):
        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
                      [0., 2.,  0.,  0.,  1.,  0.],
                      [1., 0.,  1.,  0.,  0.,  4.],
                      [0., 0.,  0.,  2.,  3.,  0.]]).T

        b = np.array([1, 0, 0, 0, 0, 0])
        with suppress_warnings() as sup:
            w = sup.record(FutureWarning, "`rcond` parameter will change")
            x, residuals, rank, s = linalg.lstsq(a, b)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
            assert_(rank == 3)
            # Warning should be raised exactly once (first command)
            assert_(len(w) == 1) 
Example #8
Source File: test_linalg.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_future_rcond(self):
        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
                      [0., 2.,  0.,  0.,  1.,  0.],
                      [1., 0.,  1.,  0.,  0.,  4.],
                      [0., 0.,  0.,  2.,  3.,  0.]]).T

        b = np.array([1, 0, 0, 0, 0, 0])
        with suppress_warnings() as sup:
            w = sup.record(FutureWarning, "`rcond` parameter will change")
            x, residuals, rank, s = linalg.lstsq(a, b)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
            assert_(rank == 3)
            # Warning should be raised exactly once (first command)
            assert_(len(w) == 1) 
Example #9
Source File: lms_solver.py    From prjxray with ISC License 6 votes vote down vote up
def solve_lms(all_tags, all_bits, segdata, bias=0.0):
    """
    Solves using direct least square solution (NumPy)

    Parameters
    ----------

    all_tags:
        List of considered tags.
    all_bits:
        List of considered bits.
    segdata:
        List of segdata used.
    bias:
        T.B.D.
    """

    # Build matrices
    A, B = build_matrices(all_tags, all_bits, segdata, bias)

    # Solve
    X, res, r, s = linalg.lstsq(A, B, rcond=None)

    return X, compute_error(A, B, X) 
Example #10
Source File: test_linalg.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_future_rcond(self):
        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
                      [0., 2.,  0.,  0.,  1.,  0.],
                      [1., 0.,  1.,  0.,  0.,  4.],
                      [0., 0.,  0.,  2.,  3.,  0.]]).T

        b = np.array([1, 0, 0, 0, 0, 0])
        with suppress_warnings() as sup:
            w = sup.record(FutureWarning, "`rcond` parameter will change")
            x, residuals, rank, s = linalg.lstsq(a, b)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
            assert_(rank == 3)
            # Warning should be raised exactly once (first command)
            assert_(len(w) == 1) 
Example #11
Source File: test_linalg.py    From pySINDy with MIT License 6 votes vote down vote up
def test_future_rcond(self):
        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
                      [0., 2.,  0.,  0.,  1.,  0.],
                      [1., 0.,  1.,  0.,  0.,  4.],
                      [0., 0.,  0.,  2.,  3.,  0.]]).T

        b = np.array([1, 0, 0, 0, 0, 0])
        with suppress_warnings() as sup:
            w = sup.record(FutureWarning, "`rcond` parameter will change")
            x, residuals, rank, s = linalg.lstsq(a, b)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
            assert_(rank == 3)
            # Warning should be raised exactly once (first command)
            assert_(len(w) == 1) 
Example #12
Source File: landmarks.py    From adience_align with MIT License 6 votes vote down vote up
def _compute_affine_transform_cvpy(refpoints, points, w = None): # Copied from the book
    if w == None:
        w = [1] * (len(points) * 2)
    assert(len(w) == 2*len(points))
    y = []
    for n, p in enumerate(refpoints):
        y += [p[0]/w[n*2], p[1]/w[n*2+1]]
    A = []
    for n, p in enumerate(points):
        A.extend([ [p[0]/w[n*2], p[1]/w[n*2], 0, 0, 1/w[n*2], 0], [0, 0, p[0]/w[n*2+1], p[1]/w[n*2+1], 0, 1/w[n*2+1]] ])
    
    lstsq = linalg.lstsq(A,y)
    h11, h12, h21, h22, dx, dy = lstsq[0]
    err = lstsq[1]

    R = np.array([[h11, h12, dx], [h21, h22, dy]])
    return R, err 
Example #13
Source File: test_linalg.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 6 votes vote down vote up
def test_future_rcond(self):
        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
                      [0., 2.,  0.,  0.,  1.,  0.],
                      [1., 0.,  1.,  0.,  0.,  4.],
                      [0., 0.,  0.,  2.,  3.,  0.]]).T

        b = np.array([1, 0, 0, 0, 0, 0])
        with suppress_warnings() as sup:
            w = sup.record(FutureWarning, "`rcond` parameter will change")
            x, residuals, rank, s = linalg.lstsq(a, b)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
            assert_(rank == 3)
            # Warning should be raised exactly once (first command)
            assert_(len(w) == 1) 
Example #14
Source File: test_linalg.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def test_future_rcond(self):
        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
                      [0., 2.,  0.,  0.,  1.,  0.],
                      [1., 0.,  1.,  0.,  0.,  4.],
                      [0., 0.,  0.,  2.,  3.,  0.]]).T

        b = np.array([1, 0, 0, 0, 0, 0])
        with suppress_warnings() as sup:
            w = sup.record(FutureWarning, "`rcond` parameter will change")
            x, residuals, rank, s = linalg.lstsq(a, b)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
            assert_(rank == 3)
            # Warning should be raised exactly once (first command)
            assert_(len(w) == 1) 
Example #15
Source File: test_linalg.py    From keras-lambda with 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 #16
Source File: test_linalg.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_empty_a_b(self, m, n, n_rhs):
        a = np.arange(m * n).reshape(m, n)
        b = np.ones((m, n_rhs))
        x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
        if m == 0:
            assert_((x == 0).all())
        assert_equal(x.shape, (n, n_rhs))
        assert_equal(residuals.shape, ((n_rhs,) if m > n else (0,)))
        if m > n and n_rhs > 0:
            # residuals are exactly the squared norms of b's columns
            r = b - np.dot(a, x)
            assert_almost_equal(residuals, (r * r).sum(axis=-2))
        assert_equal(rank, min(m, n))
        assert_equal(s.shape, (min(m, n),)) 
Example #17
Source File: test_linalg.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def do(self, a, b, tags):
        if 'size-0' in tags:
            assert_raises(LinAlgError, linalg.lstsq, a, b)
            return

        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 <= 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 #18
Source File: test_regression.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 5 votes vote down vote up
def test_lstsq_complex_larger_rhs(self):
        # gh-9891
        size = 20
        n_rhs = 70
        G = np.random.randn(size, size) + 1j * np.random.randn(size, size)
        u = np.random.randn(size, n_rhs) + 1j * np.random.randn(size, n_rhs)
        b = G.dot(u)
        # This should work without segmentation fault.
        u_lstsq, res, rank, sv = linalg.lstsq(G, b, rcond=None)
        # check results just in case
        assert_array_almost_equal(u_lstsq, u) 
Example #19
Source File: test_linalg.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def do(self, a, b, tags):
        if 'size-0' in tags:
            assert_raises(LinAlgError, linalg.lstsq, a, b)
            return

        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 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_(imply(isinstance(b, matrix), isinstance(x, matrix)))
        assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix))) 
Example #20
Source File: pymtcnn.py    From pymtcnn with GNU General Public License v3.0 5 votes vote down vote up
def findNonreflectiveSimilarity(self, uv, xy, options=None):
        options = {'K': 2}

        K = options['K']
        M = xy.shape[0]
        x = xy[:, 0].reshape((-1, 1))
        y = xy[:, 1].reshape((-1, 1))

        tmp1 = np.hstack((x, y, np.ones((M, 1)), np.zeros((M, 1))))
        tmp2 = np.hstack((y, -x, np.zeros((M, 1)), np.ones((M, 1))))
        X = np.vstack((tmp1, tmp2))

        u = uv[:, 0].reshape((-1, 1))
        v = uv[:, 1].reshape((-1, 1))
        U = np.vstack((u, v))

        if rank(X) >= 2 * K:
            r, _, _, _ = lstsq(X, U, rcond=-1)
            r = np.squeeze(r)
        else:
            raise Exception('cp2tform:twoUniquePointsReq')
        sc = r[0]
        ss = r[1]
        tx = r[2]
        ty = r[3]

        Tinv = np.array([
            [sc, -ss, 0],
            [ss, sc, 0],
            [tx, ty, 1]
        ])

        T = inv(Tinv)
        T[:, 2] = np.array([0, 0, 1])
        return T, Tinv 
Example #21
Source File: emass.py    From pylada-light with GNU General Public License v3.0 5 votes vote down vote up
def fit_directions(self, orders=None):
        """ Returns fit for computed directions.

            When dealing with degenerate states, it is better to look at each
            computed direction separately, since the order of bands might depend on
            the direction (in which case it is difficult to construct a tensor).
        """
        from numpy import dot, concatenate, pi
        from numpy.linalg import inv, lstsq
        from math import factorial
        from ..error import ValueError

        orders = self._orders(orders)
        if 2 not in orders:
            raise ValueError('Cannot compute effective masses without second order term.')

        results = []
        breakpoints = self.breakpoints
        recipcell = inv(self.structure.cell).T * 2e0 * pi / self.structure.scale
        for start, end, direction in zip(breakpoints[:-1],
                                         breakpoints[1:],
                                         self.directions):
            kpoints = self.kpoints[start:end]
            x = dot(direction, dot(recipcell, kpoints.T))
            measurements = self.eigenvalues[start:end].copy()
            parameters = concatenate([x[:, None]**i / factorial(i) for i in orders], axis=1)
            fit = lstsq(parameters, measurements)
            results.append(fit[0])

        return results 
Example #22
Source File: emass.py    From pylada-light with GNU General Public License v3.0 5 votes vote down vote up
def emass(self, orders=None):
        """ Computes effective mass for each direction. """
        from numpy import dot, concatenate, pi, array
        from numpy.linalg import inv, lstsq
        from math import factorial
        from quantities import angstrom, emass, h_bar
        from ..error import ValueError

        orders = self._orders(orders)
        if 2 not in orders:
            raise ValueError('Cannot compute effective masses without second order term.')

        results = []
        breakpoints = self.breakpoints
        recipcell = inv(self.structure.cell).T * 2e0 * pi / self.structure.scale
        for start, end, direction in zip(breakpoints[:-1],
                                         breakpoints[1:],
                                         self.directions):
            kpoints = self.kpoints[start:end]
            x = dot(direction, dot(recipcell, kpoints.T))
            measurements = self.eigenvalues[start:end].copy()
            parameters = concatenate([x[:, None]**i / factorial(i) for i in orders], axis=1)
            fit = lstsq(parameters, measurements)
            results.append(fit[0][orders.index(2)])

        result = (array(results) * self.eigenvalues.units * angstrom**2 / h_bar**2)
        return 1. / result.rescale(1 / emass) 
Example #23
Source File: test_regression.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_lstsq_complex_larger_rhs(self):
        # gh-9891
        size = 20
        n_rhs = 70
        G = np.random.randn(size, size) + 1j * np.random.randn(size, size)
        u = np.random.randn(size, n_rhs) + 1j * np.random.randn(size, n_rhs)
        b = G.dot(u)
        # This should work without segmentation fault.
        u_lstsq, res, rank, sv = linalg.lstsq(G, b, rcond=None)
        # check results just in case
        assert_array_almost_equal(u_lstsq, u) 
Example #24
Source File: mixed.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def initialize(self):
        S = sum([np.dot(unit.X.T, unit.X) for unit in self.units])
        Y = sum([np.dot(unit.X.T, unit.Y) for unit in self.units])
        self.a = L.lstsq(S, Y)[0]

        D = 0
        t = 0
        sigmasq = 0
        for unit in self.units:
            unit.r = unit.Y - np.dot(unit.X, self.a)
            if self.q > 1:
                unit.b = L.lstsq(unit.Z, unit.r)[0]
            else:
                Z = unit.Z.reshape((unit.Z.shape[0], 1))
                unit.b = L.lstsq(Z, unit.r)[0]

            sigmasq += (np.power(unit.Y, 2).sum() -
                        (self.a * np.dot(unit.X.T, unit.Y)).sum() -
                        (unit.b * np.dot(unit.Z.T, unit.r)).sum())
            D += np.multiply.outer(unit.b, unit.b)
            t += L.pinv(np.dot(unit.Z.T, unit.Z))

        #TODO: JP added df_resid check
        self.df_resid = (self.N - (self.m - 1) * self.q - self.p)
        sigmasq /= (self.N - (self.m - 1) * self.q - self.p)
        self.sigma = np.sqrt(sigmasq)
        self.D = (D - sigmasq * t) / self.m 
Example #25
Source File: montage.py    From wonambi with GNU General Public License v3.0 5 votes vote down vote up
def compute_average_regress(x, idx_chan):
    """Take the mean across channels and regress out the mean from each channel

    Parameters
    ----------
    x : ndarray
        2d array with channels on one dimension
    idx_chan:
        which axis contains channels

    Returns
    -------
    ndarray
        same as x, but with the mean being regressed out
    """
    if x.ndim != 2:
        raise ValueError(f'The number of dimensions must be 2, not {x.ndim}')

    x = moveaxis(x, idx_chan, 0)  # move axis to the front
    avg = mean(x, axis=0)

    x_o = []
    for i in range(x.shape[0]):
        r = lstsq(avg[:, None], x[i, :][:, None], rcond=0)[0]
        x_o.append(
            x[i, :] - r[0, 0] * avg
            )
    return moveaxis(asarray(x_o), 0, idx_chan) 
Example #26
Source File: test_linalg.py    From ImageFusion with MIT License 5 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 #27
Source File: pyeeg.py    From OpenNFB with GNU General Public License v3.0 5 votes vote down vote up
def hfd(X, Kmax):
	""" Compute Hjorth Fractal Dimension of a time series X, kmax
	 is an HFD parameter
	"""
	L = [];
	x = []
	N = len(X)
	for k in xrange(1,Kmax):
		Lk = []
		for m in xrange(0,k):
			Lmk = 0
			for i in xrange(1,int(floor((N-m)/k))):
				Lmk += abs(X[m+i*k] - X[m+i*k-k])
			Lmk = Lmk*(N - 1)/floor((N - m) / float(k)) / k
			Lk.append(Lmk)
		L.append(log(mean(Lk)))
		x.append([log(float(1) / k), 1])
	
	(p, r1, r2, s)=lstsq(x, L)
	return p[0] 
Example #28
Source File: perf_metric.py    From sureal with Apache License 2.0 5 votes vote down vote up
def sigmoid_adjust(xs, ys):
        ys_max = np.max(ys) + 0.1
        ys_min = np.min(ys) - 0.1

        # normalize to [0, 1]
        ys = list((np.array(ys) - ys_min) / (ys_max - ys_min))

        zs = -np.log(1.0 / np.array(ys).T - 1.0)
        Y_mtx = np.matrix((np.ones(len(ys)), zs)).T
        x_vec = np.matrix(xs).T
        a_b = lstsq(Y_mtx, x_vec, rcond=1)[0]
        a = a_b.item(0)
        b = a_b.item(1)

        xs = 1.0 / (1.0 + np.exp(- (np.array(xs) - a) / b))

        # denormalize
        xs = xs * (ys_max - ys_min) + ys_min

        return xs 
Example #29
Source File: test_linalg.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def do(self, a, b, tags):
        if 'size-0' in tags:
            assert_raises(LinAlgError, linalg.lstsq, a, b)
            return

        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 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_(imply(isinstance(b, matrix), isinstance(x, matrix)))
        assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix))) 
Example #30
Source File: test_linalg.py    From coffeegrindsize with 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))