Skip to content

ENH: create sparse dummy matrix #2771

Open

Description

@josef-pkt

Useful for sparse regression with fixed effects or categorical variables.

see
#2710 sparse support in models
#2568 absorbing fixed effects

opening to park my draft version, that I had misplaced, discussion scipy-user around nov 30, 2011
see first comment.
I don't find the script for sparse cluster robust sandwich covariance.

Activity

  1. josef-pkt commented on Jan 17, 2016

    @josef-pkt
    MemberAuthor

    "E:\Josef\work-oth2\work-oth2_moved\try_sparse_dummy.py"

    # -*- coding: utf-8 -*-
    """
    Created on Tue Nov 29 15:44:53 2011
    
    Author: Josef Perktold, recipe by Nathaniel Smith, scipy user mailing list
    
    
    Note:
    this needs checking for corner cases, e.g.
    what if a category level has zero elements? This can happen with subset
        selection even if the original groups where defined as arange.
    
    
    """
    
    import numpy as np
    from scipy import sparse
    
    def dummy_sparse(groups):
        '''create a sparse indicator from a group array with integer labels
    
        Parameters
        ----------
        groups: ndarray, int, 1d (nobs,)
            an array of group indicators for each observation. Group levels are assumed
            to be defined as consecutive integers, i.e. range(n_groups) where
            n_groups is the number of group levels.
    
        Returns
        -------
        indi : ndarray, int8, 2d (nobs, n_groups)
            an indicator array with one row per observation, that has 1 in the 
            column of the group level for that observation
    
        Examples
        --------
    
        >>> g = np.array([0, 0, 2, 1, 1, 2, 0])
        >>> indi = dummy_sparse(g)
        >>> indi
        <7x3 sparse matrix of type '<type 'numpy.int8'>'
            with 7 stored elements in Compressed Sparse Row format>
        >>> indi.todense()
        matrix([[1, 0, 0],
                [1, 0, 0],
                [0, 0, 1],
                [0, 1, 0],
                [0, 1, 0],
                [0, 0, 1],
                [1, 0, 0]], dtype=int8)
    
    
        current behavior with missing groups
        >>> g = np.array([0, 0, 2, 0, 2, 0])
        >>> indi = dummy_sparse(g)
        >>> indi.todense()
        matrix([[1, 0, 0],
                [1, 0, 0],
                [0, 0, 1],
                [1, 0, 0],
                [0, 0, 1],
                [1, 0, 0]], dtype=int8)
    
        '''
    
        indptr = np.arange(len(groups)+1)
        data = np.ones(len(groups), dtype=np.int8)
        indi = sparse.csr_matrix((data, g, indptr))
    
        return indi
    
    g = np.array([0, 0, 1, 2, 1, 1, 2, 0])
    u = range(3)
    indptr = np.arange(len(g)+1)
    data = np.ones(len(g), dtype=np.int8)
    a = sparse.csr_matrix((data, g, indptr))
    print a.todense()
    print np.all(a.todense() == (g[:,None] == np.arange(3)).astype(int))
    
    x = np.arange(len(g)*3).reshape(len(g), 3, order='F')
    
    print 'group means'
    print x.T * a
    print np.dot(x.T, g[:,None] == np.arange(3))
    print np.array([np.bincount(g, weights=x[:,col]) for col in range(3)])
    for cat in u:
        print x[g==cat].sum(0)
    for cat in u: x[g==cat].sum(0)
    
    cc = sparse.csr_matrix([[0, 1, 0, 1, 0, 0, 0, 0, 0],
                [1, 0, 1, 0, 1, 0, 0, 0, 0],
                [0, 1, 0, 0, 0, 1, 0, 0, 0],
                [1, 0, 0, 0, 1, 0, 1, 0, 0],
                [0, 1, 0, 1, 0, 1, 0, 1, 0],
                [0, 0, 1, 0, 1, 0, 0, 0, 1],
                [0, 0, 0, 1, 0, 0, 0, 1, 0],
                [0, 0, 0, 0, 1, 0, 1, 0, 1],
                [0, 0, 0, 0, 0, 1, 0, 1, 0]])
    
  2. added this to the 0.10 milestone on Oct 4, 2017
  3. jbrockmendel commented on Sep 2, 2018

    @jbrockmendel
    Contributor

    Doesn’t pd.get_dummies do,this?

  4. josef-pkt commented on Sep 2, 2018

    @josef-pkt
    MemberAuthor

    last time I checked those were dense in pandas.

  5. jbrockmendel commented on Sep 2, 2018

    @jbrockmendel
    Contributor

    Looks like pd.get_dummies has a sparse kwarg that defaults to False. That returns a SparseDataFrame, which has a to_coo method. I'm not familiar enough with scipy.sparse to know if/how useful that is.

  6. josef-pkt commented on Sep 2, 2018

    @josef-pkt
    MemberAuthor

    It's a bit like using pandas categorical, for which we also have our own code and which is also provided through the formula interface by patsy.
    When those parts were introduced in pandas I was against using it in statsmodels. After several years of stabilizing and optimizing it in pandas, it can provide a better alternative than our home made numpy solution.

    Just based on a quick search SparseDataFrame might not yet be ready for us yet
    https://github.com/pandas-dev/pandas/issues/16773
    For our specific usecase dummy_sparse should be the fastest solution (originally suggested by Nathaniel Smith on a mailing list).
    That doesn't mean that some sparse handling wouldn't benefit from additional support from pandas.

  7. jbrockmendel commented on Sep 2, 2018

    @jbrockmendel
    Contributor

    Just based on a quick search SparseDataFrame might not yet be ready for us yet

    Yah, SparseDataFrame doesn't get a ton of use. Tom has a big PR in the works that might improve things there; I'll keep an eye on it and update if anything useful comes up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions