Skip to content

linear restriction, overparameterized models and patsy #2359

Open

Description

@josef-pkt

Patsy currently does not provide an factor/categorical encoding that does not drop columns that are already linear dependent available in "earlier" factor columns
pydata/patsy#60
pydata/patsy#42
(discussed with Nathaniel at pycon 2015)

I ran into this while looking at a stackoverflow question
http://stackoverflow.com/questions/29261018/how-to-add-sum-to-zero-constraint-to-glm-in-python
Two problems there, patsy does create full dummy sets and statsmodels doesn't implement fit_constrained for all models.

Activity

  1. added this to the 0.8 milestone on Apr 15, 2015
  2. modified the milestones: 0.8, 0.15 on Jun 22, 2022
  3. josef-pkt commented on Jun 22, 2022

    @josef-pkt
    MemberAuthor

    Nathaniel showed a way to use custom encoding
    https://stackoverflow.com/questions/46832637/one-hot-encoding-in-patsy/46870306#46870306

    need to try this out for fit_constrained

    Alternatively, if you really want an over-parameterized model, then if you scroll down further on the docs page you linked to, it tells you how to define arbitrary custom encoding schemes.
    
    import numpy as np
    from patsy import ContrastMatrix
    
    class FullRankOneHot(object):
        def __init__(self, reference=0):
            self.reference = reference
    
        # Called to generate a full-rank encoding
        def code_with_intercept(self, levels):
            return ContrastMatrix(np.eye(len(levels)),
                                  ["[My.%s]" % (level,) for level in levels])
    
        # Called to generate a non-full-rank encoding. But we don't care,
        # we do what we want, and return a full-rank encoding anyway.
        # Take that, patsy.
        def code_without_intercept(self, levels):
            return self.code_with_intercept(levels)
    
    Then you can use it like: y ~ 1 + C(a, FullRankOneHot).
    
  4. stanmart commented on Aug 7, 2023

    @stanmart

    AFAIK formulaic provides support for this with the ensure_full_rank=False andspans_intercept=False parameters.

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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions