Let's say that we have 100 samples from a Bernoulli distribution:
import torch
import numpy as np
from torch.autograd import Variable
sample = np.array([ 1., 1., 0., 1., 1., 1., 0., 1., 1., 1., 1., 1., 1.,
1., 0., 1., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
1., 1., 1., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
1., 1., 1., 0., 1., 1., 1., 0., 1., 1., 0., 1., 1.,
1., 0., 1., 0., 1., 1., 0., 1., 1., 0., 1., 1., 1.,
1., 1., 1., 1., 0., 0., 1., 1., 1., 1., 0., 0., 1.,
0., 1., 1., 1., 1., 0., 0., 1., 1., 1., 1., 0., 1.,
0., 1., 1., 0., 1., 0., 1., 0., 0., 1., 1., 1., 0.,
0., 1., 1., 1., 1., 0., 1., 1., 1., 1., 1., 0., 1.,
0., 1., 1., 1., 1., 1., 0., 1., 0., 0., 1., 1., 1.,
0., 1., 1., 1., 0., 1., 1., 1., 0., 0., 1., 1., 1.,
1., 1., 0., 0., 1., 1., 0., 1., 1., 0., 1., 0., 1.,
1., 1., 1., 0., 1., 0., 1., 1., 1., 1., 0., 0., 1.,
0., 1., 1., 1., 1., 1., 1., 0., 1., 1., 1., 0., 1.,
1., 1., 1., 0., 1., 1., 1., 0., 0., 0., 1., 1., 1.,
1., 0., 1., 0., 1.])
np.mean(sample)
Let's now define the probability p
of generating 1, and put the sample into a PyTorch Variable
:
x = Variable(torch.from_numpy(sample)).type(torch.FloatTensor)
p = Variable(torch.rand(1), requires_grad=True)
We are ready to learn the model using maximum likelihood:
learning_rate = 0.00002
for t in range(1000):
NLL = -torch.sum(torch.log(x*p + (1-x)*(1-p)) )
NLL.backward()
if t % 100 == 0:
print("loglik =", NLL.data.numpy(), "p =", p.data.numpy(), "dL/dp = ", p.grad.data.numpy())
p.data -= learning_rate * p.grad.data
p.grad.data.zero_()