5.1 Maximum likelihood estimation

5.1 Maximum likelihood estimation#

mode = "svg"

import matplotlib

font = {'family' : 'Dejavu Sans',
        'weight' : 'normal',
        'size'   : 20}

matplotlib.rc('font', **font)

import matplotlib
from matplotlib import pyplot as plt
from graspologic.simulations import er_np

p = 0.3
A = er_np(n=50, p=p)
import numpy as np
from graspologic.models import EREstimator

model = EREstimator(directed=False, loops=False)
model.fit(A)
# obtain the estimate from the fit model
phat = model.p_
print("Difference between phat and p: {:.3f}".format(phat - p))
Difference between phat and p: -0.010
from graspologic.simulations import sbm

nks = [50, 50]
B = np.array([[0.6, 0.1], 
              [0.1, 0.4]])

A, z = sbm(n=nks, p=B, return_labels=True)
from graspologic.models import SBMEstimator
from graphbook_code import heatmap

model = SBMEstimator(directed=False, loops=False)
model.fit(A, y=z)
Bhat = model.block_p_
import os

fig, axs = plt.subplots(1, 3, figsize=(15, 5), gridspec_kw={"width_ratios": [1, 1.27, 1.27]})
# plot the block matrix vs estimate
heatmap(B, title="(A) $B$ true block matrix", vmin=0, vmax=1, ax=axs[0],
        xtitle="Community", xticks=[0.5, 1.5], xticklabels=[1, 2],
        ytitle="Community", yticks=[0.5, 1.5], yticklabels=[1, 2], annot=True, fmt=".3f", cbar=False)
heatmap(Bhat, title="(B) $\hat B$ estimate of block matrix", vmin=0, vmax=1, ax=axs[1],
        xtitle="Community", xticks=[0.5, 1.5], xticklabels=[1, 2],
        ytitle="Community", yticks=[0.5, 1.5], yticklabels=[1, 2], annot=True, fmt=".3f", legend_title="Probability")
heatmap(np.abs(Bhat - B), title="(C) $|\hat B - B|$", vmin=0, vmax=1, ax=axs[2],
        xtitle="Community", xticks=[0.5, 1.5], xticklabels=[1, 2],
        ytitle="Community", yticks=[0.5, 1.5], yticklabels=[1, 2], annot=True, fmt=".3f", legend_title="Abs. Diff.")

fig.tight_layout()

os.makedirs("Figures", exist_ok=True)
fname = "sbm_est"
if mode != "png":
    os.makedirs(f"Figures/{mode:s}", exist_ok=True)
    fig.savefig(f"Figures/{mode:s}/{fname:s}.{mode:s}")

os.makedirs("Figures/png", exist_ok=True)
fig.savefig(f"Figures/png/{fname:s}.png")
<>:8: SyntaxWarning: invalid escape sequence '\h'
<>:11: SyntaxWarning: invalid escape sequence '\h'
<>:8: SyntaxWarning: invalid escape sequence '\h'
<>:11: SyntaxWarning: invalid escape sequence '\h'
/tmp/ipykernel_4142/2317088039.py:8: SyntaxWarning: invalid escape sequence '\h'
  heatmap(Bhat, title="(B) $\hat B$ estimate of block matrix", vmin=0, vmax=1, ax=axs[1],
/tmp/ipykernel_4142/2317088039.py:11: SyntaxWarning: invalid escape sequence '\h'
  heatmap(np.abs(Bhat - B), title="(C) $|\hat B - B|$", vmin=0, vmax=1, ax=axs[2],
../../_images/7511ab5aa69cabd44d59ea1ded19bd8731f425e28f38da8372bab4538f12850a.png