Skip to content

ENH: tools: closest matrix with given marginals #7444

Open

Description

@josef-pkt

I needed to correct a bivariate binned distribution to have uniform marginals.
(application is from binned copulas for checking results in #7408 )

Iterating works, trial and error

pc = ag / ag.sum()
for i in range(20):
    pc = pc / np.sqrt(pc.sum(0) * pc.sum(1)[:,None])
    pc /= pc.sum()
    print()
    print(pc.sum(0), pc.sum(1), pc.sum())

iteration idea is from
Dhillon, Inderjit S., and Joel A. Tropp. "Matrix nearness problems with Bregman divergences." SIAM Journal on Matrix Analysis and Applications 29, no. 4 (2008): 1120-1146.
https://authors.library.caltech.edu/9428/1/DHIsiamjmaa07.pdf

I didn't read it (too much numerical math for me)

p. 1133 section 5.1. Contingency tables with fixed marginals
mentions iterative Bregman projections and sounded similar to what I needed.
(that section was found by Google and the only part I was interested in)

(sqrt is from my earlier non-iterative trials)

Activity

  1. josef-pkt commented on May 11, 2021

    @josef-pkt
    MemberAuthor

    as function

    def nearest_matrix_margins(a, maxiter=10, tol=1e-8): #, margins0, margins1):
        """nearest matrix with uniform margins"""
        pc = a
        for i in range(maxiter):
    
            pc = pc / (pc.sum(0)) 
            pc = pc / (pc.sum(1)[:,None])
            pc /= pc.sum()
            if np.ptp(pc.sum(0)) < tol:
                if np.ptp(pc.sum(1)) < tol:
                    print(i)
                    break
        return pc
    

    for checking

    a = np.random.random(size=(4,4))
    a /= a.sum()
    print(a.sum(0))
    print(a.sum(1))
    print(a.sum())
    am = nearest_matrix_margins((a + a.T)/2, maxiter=50000, tol=1e-8)
    am = nearest_matrix_margins(a, maxiter=100, tol=1e-8)
    print(am.sum(0))
    print(am.sum(1))
    print(am.sum())
    
  2. josef-pkt commented on May 14, 2021

    @josef-pkt
    MemberAuthor

    The current version with uniform (not general) margins will be added to statsmodels.distributions.tools for now, PR #7254
    I don't know yet whether it will be useful for simulating contingency tables as in #3576

  3. josef-pkt commented on Feb 1, 2023

    @josef-pkt
    MemberAuthor

    #8642 updates function for dim > 2
    I didn't look at any references. It uses the same approach with iterative adjustment by margins along axes.

    I don't know anything about approximation properties, i.e. what approximation distance is minimized.

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

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions