Last active
June 29, 2019 14:13
-
-
Save papachristoumarios/3da173eba99ea9716ccf13f71a36ae91 to your computer and use it in GitHub Desktop.
Simple MLE of Exponential Variables with Pytorch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Simple MLE Estimator to demonstrate Pytorch optimization capabilities | |
This program estimates the parameter of an exponential random variable | |
using an MLE Estimator. | |
Author: Marios Papachristou | |
''' | |
import torch | |
import numpy as np | |
from torch.autograd import Variable | |
# Draw random samples | |
sample = np.random.randint(10, size=(10, 1)) | |
# Convert to Pytorch tensor | |
x = Variable(torch.from_numpy(sample)).type(torch.FloatTensor) | |
# Initialize Parameters | |
p = Variable(torch.rand(1), requires_grad=True) | |
# Initialize optimizer | |
optimizer = torch.optim.SGD([p], lr=0.0002) | |
for t in range(1500): | |
optimizer.zero_grad() | |
# Negative log likelihood of exponential NLL = -log (L | X_1, ..., X_n) | |
NLL = - (x.size()[0] * torch.log(p) - p * torch.sum(x)) | |
NLL.backward() | |
print('NLL', NLL, 'p', p) | |
optimizer.step() | |
print('Theoretical estimation', 1 / np.mean(sample)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment