# Optimization¶

It is often useful to construct a distribution $$d^\prime$$ which is consistent with some marginal aspects of $$d$$, but otherwise optimizes some information measure. For example, perhaps we are interested in constructing a distribution which matches pairwise marginals with another, but otherwise has maximum entropy:

In [1]: from dit.algorithms.distribution_optimizers import MaxEntOptimizer

In [2]: xor = dit.example_dists.Xor()

In [3]: meo = MaxEntOptimizer(xor, [[0,1], [0,2], [1,2]])

In [4]: meo.optimize()
Out[4]:
fun: -3.0000018341614596
jac: array([-2.99999976, -2.9999997 , -3.00000024, -2.99999973, -3.00000012,
-3.00000018, -3.00000012, -2.99999964])
message: 'Optimization terminated successfully.'
nfev: 971
nit: 88
njev: 88
status: 0
success: True
x: array([0.12500008, 0.12500006, 0.12500006, 0.12500008, 0.12500011,
0.12500008, 0.12500007, 0.12500007])

In [5]: dp = meo.construct_dist()

In [6]: print(dp)
Class:          Distribution
Alphabet:       ('0', '1') for all rvs
Base:           linear
Outcome Class:  str
Outcome Length: 3
RV Names:       None

x     p(x)
000   1642501/13140009
001   1/8
010   4675599/37404791
011   1267414/10139311
100   972504/7780031
101   1293763/10350105
110   1549238/12393905
111   1/8


## Helper Functions¶

There are three special functions to handle common optimization problems:

In [7]: from dit.algorithms import maxent_dist, marginal_maxent_dists


The first is maximum entropy distributions with specific fixed marginals. It encapsulates the steps run above:

In [8]: print(maxent_dist(xor, [[0,1], [0,2], [1,2]]))
Class:          Distribution
Alphabet:       ('0', '1') for all rvs
Base:           linear
Outcome Class:  str
Outcome Length: 3
RV Names:       None

x     p(x)
000   577384/4619073
001   662802/5302415
010   1212736/9701887
011   934178/7473425
100   561224/4489791
101   626234/5009873
110   880251/7042009
111   704154/5633231


The second constructs several maximum entropy distributions, each with all subsets of variables of a particular size fixed:

In [9]: k0, k1, k2, k3 = marginal_maxent_dists(xor)


where k0 is the maxent dist corresponding the same alphabets as xor; k1 fixes $$p(x_0)$$, $$p(x_1)$$, and $$p(x_2)$$; k2 fixes $$p(x_0, x_1)$$, $$p(x_0, x_2)$$, and $$p(x_1, x_2)$$ (as in the maxent_dist example above), and finally k3 fixes $$p(x_0, x_1, x_2)$$ (e.g. is the distribution we started with).