Python numpy.asmatrix() Examples

The following are 30 code examples for showing how to use numpy.asmatrix(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: DualFisheye   Author: ooterness   File: fisheye.py    License: MIT License 6 votes vote down vote up
def add_pixels(self, uv_px, img1d, weight=None):
        # Lookup row & column for each in-bounds coordinate.
        mask = self.get_mask(uv_px)
        xx = uv_px[0,mask]
        yy = uv_px[1,mask]
        # Update matrix according to assigned weight.
        if weight is None:
            img1d[mask] = self.img[yy,xx]
        elif np.isscalar(weight):
            img1d[mask] += self.img[yy,xx] * weight
        else:
            w1 = np.asmatrix(weight, dtype='float32')
            w3 = w1.transpose() * np.ones((1,3))
            img1d[mask] += np.multiply(self.img[yy,xx], w3[mask])


# A panorama image made from several FisheyeImage sources.
# TODO: Add support for supersampled anti-aliasing filters. 
Example 2
Project: vadnet   Author: hcmlab   File: model.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def transform(info, sin, sout, sxtra, board, opts, vars): 
     
    if vars['loaded']:	

        sess = vars['sess']
        x = vars['x']
        y = vars['y']
        ph_n_shuffle = vars['ph_n_shuffle']
        ph_n_repeat = vars['ph_n_repeat']
        ph_n_batch = vars['ph_n_batch']
        init = vars['init']
        logits = vars['logits']

        input = np.asmatrix(sin).reshape(-1, x.shape[1]) 

        dummy = np.zeros((input.shape[0],), dtype=np.int32)
        sess.run(init, feed_dict = { x : input, y : dummy, ph_n_shuffle : 1, ph_n_repeat : 1, ph_n_batch : input.shape[0] })    
        output = sess.run(logits)    
        output = np.mean(output, axis=0)

        for i in range(sout.dim):
            sout[i] = output[i] 
Example 3
Project: chowmein   Author: xiaohan2012   File: label_ranker.py    License: MIT License 6 votes vote down vote up
def label_relevance_score(self,
                              topic_models,
                              pmi_w2l):
        """
        Calculate the relevance scores between each label and each topic

        Parameters:
        ---------------
        topic_models: numpy.ndarray(#topics, #words)
           the topic models

        pmi_w2l: numpy.ndarray(#words, #labels)
           the Point-wise Mutual Information(PMI) table of
           the form, PMI(w, l | C)
        
        Returns;
        -------------
        numpy.ndarray, shape (#topics, #labels)
            the scores of each label on each topic
        """
        assert topic_models.shape[1] == pmi_w2l.shape[0]
        return np.asarray(np.asmatrix(topic_models) *
                          np.asmatrix(pmi_w2l)) 
Example 4
Project: lambda-packs   Author: ryfeus   File: test_shape_base.py    License: MIT License 6 votes vote down vote up
def test_return_type(self):
        a = np.ones([2, 2])
        m = np.asmatrix(a)
        assert_equal(type(kron(a, a)), np.ndarray)
        assert_equal(type(kron(m, m)), np.matrix)
        assert_equal(type(kron(a, m)), np.matrix)
        assert_equal(type(kron(m, a)), np.matrix)

        class myarray(np.ndarray):
            __array_priority__ = 0.0

        ma = myarray(a.shape, a.dtype, a.data)
        assert_equal(type(kron(a, a)), np.ndarray)
        assert_equal(type(kron(ma, ma)), myarray)
        assert_equal(type(kron(a, ma)), np.ndarray)
        assert_equal(type(kron(ma, a)), myarray) 
Example 5
Project: sfa-numpy   Author: spatialaudio   File: util.py    License: MIT License 6 votes vote down vote up
def coherence_of_columns(A):
    """Mutual coherence of columns of A.

    Parameters
    ----------
    A : array_like
        Input matrix.
    p : int, optional
        p-th norm.

    Returns
    -------
    array_like
        Mutual coherence of columns of A.
    """
    A = np.asmatrix(A)
    _, N = A.shape
    A = A * np.asmatrix(np.diag(1/norm_of_columns(A)))
    Gram_A = A.H*A
    for j in range(N):
        Gram_A[j, j] = 0
    return np.max(np.abs(Gram_A)) 
Example 6
Project: tensortrade   Author: tensortrade-org   File: heston.py    License: Apache License 2.0 5 votes vote down vote up
def get_correlated_geometric_brownian_motions(params: ModelParameters,
                                              correlation_matrix: np.array,
                                              n: int):
    """
    Constructs a basket of correlated asset paths using the Cholesky
    decomposition method.

    Arguments:
        params : ModelParameters
            The parameters for the stochastic model.
        correlation_matrix : np.array
            An n x n correlation matrix.
        n : int
            Number of assets (number of paths to return)

    Returns:
        n correlated log return geometric brownian motion processes
    """
    decomposition = sp.linalg.cholesky(correlation_matrix, lower=False)
    uncorrelated_paths = []
    sqrt_delta_sigma = np.sqrt(params.all_delta) * params.all_sigma
    # Construct uncorrelated paths to convert into correlated paths
    for i in range(params.all_time):
        uncorrelated_random_numbers = []
        for j in range(n):
            uncorrelated_random_numbers.append(random.normalvariate(0, sqrt_delta_sigma))
        uncorrelated_paths.append(np.array(uncorrelated_random_numbers))
    uncorrelated_matrix = np.asmatrix(uncorrelated_paths)
    correlated_matrix = uncorrelated_matrix * decomposition
    assert isinstance(correlated_matrix, np.matrix)
    # The rest of this method just extracts paths from the matrix
    extracted_paths = []
    for i in range(1, n + 1):
        extracted_paths.append([])
    for j in range(0, len(correlated_matrix) * n - n, n):
        for i in range(n):
            extracted_paths[i].append(correlated_matrix.item(j + i))
    return extracted_paths 
Example 7
Project: recruit   Author: Frank-qlu   File: test_interaction.py    License: Apache License 2.0 5 votes vote down vote up
def test_fancy_indexing():
    # The matrix class messes with the shape. While this is always
    # weird (getitem is not used, it does not have setitem nor knows
    # about fancy indexing), this tests gh-3110
    # 2018-04-29: moved here from core.tests.test_index.
    m = np.matrix([[1, 2], [3, 4]])

    assert_(isinstance(m[[0, 1, 0], :], np.matrix))

    # gh-3110. Note the transpose currently because matrices do *not*
    # support dimension fixing for fancy indexing correctly.
    x = np.asmatrix(np.arange(50).reshape(5, 10))
    assert_equal(x[:2, np.array(-1)], x[:2, -1].T) 
Example 8
Project: recruit   Author: Frank-qlu   File: test_defmatrix.py    License: Apache License 2.0 5 votes vote down vote up
def test_asmatrix(self):
        A = np.arange(100).reshape(10, 10)
        mA = asmatrix(A)
        A[0, 0] = -10
        assert_(A[0, 0] == mA[0, 0]) 
Example 9
Project: recruit   Author: Frank-qlu   File: test_defmatrix.py    License: Apache License 2.0 5 votes vote down vote up
def test_basic(self):
        x = asmatrix(np.zeros((3, 2), float))
        y = np.zeros((3, 1), float)
        y[:, 0] = [0.8, 0.2, 0.3]
        x[:, 1] = y > 0.5
        assert_equal(x, [[0, 1], [0, 0], [0, 0]]) 
Example 10
Project: recruit   Author: Frank-qlu   File: test_defmatrix.py    License: Apache License 2.0 5 votes vote down vote up
def test_scalar_indexing(self):
        x = asmatrix(np.zeros((3, 2), float))
        assert_equal(x[0, 0], x[0][0]) 
Example 11
Project: recruit   Author: Frank-qlu   File: test_defmatrix.py    License: Apache License 2.0 5 votes vote down vote up
def test_row_column_indexing(self):
        x = asmatrix(np.eye(2))
        assert_array_equal(x[0,:], [[1, 0]])
        assert_array_equal(x[1,:], [[0, 1]])
        assert_array_equal(x[:, 0], [[1], [0]])
        assert_array_equal(x[:, 1], [[0], [1]]) 
Example 12
Project: recruit   Author: Frank-qlu   File: test_defmatrix.py    License: Apache License 2.0 5 votes vote down vote up
def test_boolean_indexing(self):
        A = np.arange(6)
        A.shape = (3, 2)
        x = asmatrix(A)
        assert_array_equal(x[:, np.array([True, False])], x[:, 0])
        assert_array_equal(x[np.array([True, False, False]),:], x[0,:]) 
Example 13
Project: recruit   Author: Frank-qlu   File: test_regression.py    License: Apache License 2.0 5 votes vote down vote up
def test_matrix_std_argmax(self):
        # Ticket #83
        x = np.asmatrix(np.random.uniform(0, 1, (3, 3)))
        assert_equal(x.std().shape, ())
        assert_equal(x.argmax().shape, ()) 
Example 14
Project: qcqp   Author: cvxgrp   File: qcqp.py    License: MIT License 5 votes vote down vote up
def improve_admm(x0, prob, *args, **kwargs):
    num_iters = kwargs.get('num_iters', 1000)
    viol_lim = kwargs.get('viol_lim', 1e4)
    tol = kwargs.get('tol', 1e-2)
    rho = kwargs.get('rho', None)
    phase1 = kwargs.get('phase1', True)

    if rho is not None:
        lmb0, P0Q = map(np.asmatrix, LA.eigh(prob.f0.P.todense()))
        lmb_min = np.min(lmb0)
        if lmb_min + prob.m*rho < 0:
            logging.error("rho parameter is too small, z-update not convex.")
            logging.error("Minimum possible value of rho: %.3f\n", -lmb_min/prob.m)
            logging.error("Given value of rho: %.3f\n", rho)
            raise Exception("rho parameter is too small, need at least %.3f." % rho)

    # TODO: find a reasonable auto parameter
    if rho is None:
        lmb0, P0Q = map(np.asmatrix, LA.eigh(prob.f0.P.todense()))
        lmb_min = np.min(lmb0)
        lmb_max = np.max(lmb0)
        if lmb_min < 0: rho = 2.*(1.-lmb_min)/prob.m
        else: rho = 1./prob.m
        rho *= 50.
        logging.warning("Automatically setting rho to %.3f", rho)

    if phase1:
        x1 = prob.better(x0, admm_phase1(x0, prob, tol, num_iters))
    else:
        x1 = x0
    x2 = prob.better(x1, admm_phase2(x1, prob, rho, tol, num_iters, viol_lim))
    return x2 
Example 15
Project: lambda-packs   Author: ryfeus   File: compressed.py    License: MIT License 5 votes vote down vote up
def sum(self, axis=None, dtype=None, out=None):
        """Sum the matrix over the given axis.  If the axis is None, sum
        over both rows and columns, returning a scalar.
        """
        # The spmatrix base class already does axis=0 and axis=1 efficiently
        # so we only do the case axis=None here
        if (not hasattr(self, 'blocksize') and
                    axis in self._swap(((1, -1), (0, 2)))[0]):
            # faster than multiplication for large minor axis in CSC/CSR
            res_dtype = get_sum_dtype(self.dtype)
            ret = np.zeros(len(self.indptr) - 1, dtype=res_dtype)

            major_index, value = self._minor_reduce(np.add)
            ret[major_index] = value
            ret = np.asmatrix(ret)
            if axis % 2 == 1:
                ret = ret.T

            if out is not None and out.shape != ret.shape:
                raise ValueError('dimensions do not match')

            return ret.sum(axis=(), dtype=dtype, out=out)
        # spmatrix will handle the remaining situations when axis
        # is in {None, -1, 0, 1}
        else:
            return spmatrix.sum(self, axis=axis, dtype=dtype, out=out) 
Example 16
Project: lambda-packs   Author: ryfeus   File: data.py    License: MIT License 5 votes vote down vote up
def _arg_min_or_max_axis(self, axis, op, compare):
        if self.shape[axis] == 0:
            raise ValueError("Can't apply the operation along a zero-sized "
                             "dimension.")

        if axis < 0:
            axis += 2

        zero = self.dtype.type(0)

        mat = self.tocsc() if axis == 0 else self.tocsr()
        mat.sum_duplicates()

        ret_size, line_size = mat._swap(mat.shape)
        ret = np.zeros(ret_size, dtype=int)

        nz_lines, = np.nonzero(np.diff(mat.indptr))
        for i in nz_lines:
            p, q = mat.indptr[i:i + 2]
            data = mat.data[p:q]
            indices = mat.indices[p:q]
            am = op(data)
            m = data[am]
            if compare(m, zero) or q - p == line_size:
                ret[i] = indices[am]
            else:
                zero_ind = _find_missing_index(indices, line_size)
                if m == zero:
                    ret[i] = min(am, zero_ind)
                else:
                    ret[i] = zero_ind

        if axis == 1:
            ret = ret.reshape(-1, 1)

        return np.asmatrix(ret) 
Example 17
Project: lambda-packs   Author: ryfeus   File: test_defmatrix.py    License: MIT License 5 votes vote down vote up
def test_asmatrix(self):
        A = np.arange(100).reshape(10, 10)
        mA = asmatrix(A)
        A[0, 0] = -10
        assert_(A[0, 0] == mA[0, 0]) 
Example 18
Project: lambda-packs   Author: ryfeus   File: test_defmatrix.py    License: MIT License 5 votes vote down vote up
def test_basic(self):
        x = asmatrix(np.zeros((3, 2), float))
        y = np.zeros((3, 1), float)
        y[:, 0] = [0.8, 0.2, 0.3]
        x[:, 1] = y > 0.5
        assert_equal(x, [[0, 1], [0, 0], [0, 0]]) 
Example 19
Project: lambda-packs   Author: ryfeus   File: test_defmatrix.py    License: MIT License 5 votes vote down vote up
def test_row_column_indexing(self):
        x = asmatrix(np.eye(2))
        assert_array_equal(x[0,:], [[1, 0]])
        assert_array_equal(x[1,:], [[0, 1]])
        assert_array_equal(x[:, 0], [[1], [0]])
        assert_array_equal(x[:, 1], [[0], [1]]) 
Example 20
Project: lambda-packs   Author: ryfeus   File: test_defmatrix.py    License: MIT License 5 votes vote down vote up
def test_boolean_indexing(self):
        A = np.arange(6)
        A.shape = (3, 2)
        x = asmatrix(A)
        assert_array_equal(x[:, np.array([True, False])], x[:, 0])
        assert_array_equal(x[np.array([True, False, False]),:], x[0,:]) 
Example 21
Project: lambda-packs   Author: ryfeus   File: test_defmatrix.py    License: MIT License 5 votes vote down vote up
def test_list_indexing(self):
        A = np.arange(6)
        A.shape = (3, 2)
        x = asmatrix(A)
        assert_array_equal(x[:, [1, 0]], x[:, ::-1])
        assert_array_equal(x[[2, 1, 0],:], x[::-1,:]) 
Example 22
Project: lambda-packs   Author: ryfeus   File: test_regression.py    License: MIT License 5 votes vote down vote up
def test_matrix_std_argmax(self,level=rlevel):
        # Ticket #83
        x = np.asmatrix(np.random.uniform(0, 1, (3, 3)))
        self.assertEqual(x.std().shape, ())
        self.assertEqual(x.argmax().shape, ()) 
Example 23
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: matlib.py    License: MIT License 5 votes vote down vote up
def eye(n,M=None, k=0, dtype=float):
    """
    Return a matrix with ones on the diagonal and zeros elsewhere.

    Parameters
    ----------
    n : int
        Number of rows in the output.
    M : int, optional
        Number of columns in the output, defaults to `n`.
    k : int, optional
        Index of the diagonal: 0 refers to the main diagonal,
        a positive value refers to an upper diagonal,
        and a negative value to a lower diagonal.
    dtype : dtype, optional
        Data-type of the returned matrix.

    Returns
    -------
    I : matrix
        A `n` x `M` matrix where all elements are equal to zero,
        except for the `k`-th diagonal, whose values are equal to one.

    See Also
    --------
    numpy.eye : Equivalent array function.
    identity : Square identity matrix.

    Examples
    --------
    >>> import numpy.matlib
    >>> np.matlib.eye(3, k=1, dtype=float)
    matrix([[ 0.,  1.,  0.],
            [ 0.,  0.,  1.],
            [ 0.,  0.,  0.]])

    """
    return asmatrix(np.eye(n, M, k, dtype)) 
Example 24
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_defmatrix.py    License: MIT License 5 votes vote down vote up
def test_asmatrix(self):
        A = np.arange(100).reshape(10, 10)
        mA = asmatrix(A)
        A[0, 0] = -10
        assert_(A[0, 0] == mA[0, 0]) 
Example 25
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_defmatrix.py    License: MIT License 5 votes vote down vote up
def test_scalar_indexing(self):
        x = asmatrix(np.zeros((3, 2), float))
        assert_equal(x[0, 0], x[0][0]) 
Example 26
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_defmatrix.py    License: MIT License 5 votes vote down vote up
def test_row_column_indexing(self):
        x = asmatrix(np.eye(2))
        assert_array_equal(x[0,:], [[1, 0]])
        assert_array_equal(x[1,:], [[0, 1]])
        assert_array_equal(x[:, 0], [[1], [0]])
        assert_array_equal(x[:, 1], [[0], [1]]) 
Example 27
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_defmatrix.py    License: MIT License 5 votes vote down vote up
def test_boolean_indexing(self):
        A = np.arange(6)
        A.shape = (3, 2)
        x = asmatrix(A)
        assert_array_equal(x[:, np.array([True, False])], x[:, 0])
        assert_array_equal(x[np.array([True, False, False]),:], x[0,:]) 
Example 28
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_defmatrix.py    License: MIT License 5 votes vote down vote up
def test_list_indexing(self):
        A = np.arange(6)
        A.shape = (3, 2)
        x = asmatrix(A)
        assert_array_equal(x[:, [1, 0]], x[:, ::-1])
        assert_array_equal(x[[2, 1, 0],:], x[::-1,:]) 
Example 29
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_regression.py    License: MIT License 5 votes vote down vote up
def test_matrix_std_argmax(self,level=rlevel):
        # Ticket #83
        x = np.asmatrix(np.random.uniform(0, 1, (3, 3)))
        self.assertEqual(x.std().shape, ())
        self.assertEqual(x.argmax().shape, ()) 
Example 30
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_indexing.py    License: MIT License 5 votes vote down vote up
def test_matrix_fancy(self):
        # The matrix class messes with the shape. While this is always
        # weird (getitem is not used, it does not have setitem nor knows
        # about fancy indexing), this tests gh-3110
        m = np.matrix([[1, 2], [3, 4]])

        assert_(isinstance(m[[0,1,0], :], np.matrix))

        # gh-3110. Note the transpose currently because matrices do *not*
        # support dimension fixing for fancy indexing correctly.
        x = np.asmatrix(np.arange(50).reshape(5,10))
        assert_equal(x[:2, np.array(-1)], x[:2, -1].T)