You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
ENH: tools: closest matrix with given marginals #7444
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)
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())
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
Activity
josef-pkt commentedon May 11, 2021
as function
for checking
josef-pkt commentedon May 14, 2021
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
josef-pkt commentedon Feb 1, 2023
#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.