-
Notifications
You must be signed in to change notification settings - Fork 0
/
1.gaussian_loglikelihood.py
52 lines (38 loc) · 1.42 KB
/
1.gaussian_loglikelihood.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import torch
import numpy as np
"""
Exercise 1.1: Diagonal Gaussian Likelihood
Write a function that takes in PyTorch Tensors for the means and
log stds of a batch of diagonal Gaussian distributions, along with a
PyTorch Tensor for (previously-generated) samples from those
distributions, and returns a Tensor containing the log
likelihoods of those samples.
"""
def gaussian_likelihood(x, mu, log_std):
"""
Args:
x: Tensor with shape [batch, dim]
mu: Tensor with shape [batch, dim]
log_std: Tensor with shape [batch, dim] or [dim]
Returns:
Tensor with shape [batch]
"""
tmp = (x - mu) ** 2 / torch.exp(log_std) ** 2 + 2 * log_std + np.log(2 * np.pi)
return -tmp.sum(axis=-1) / 2
if __name__ == "__main__":
"""
Run this file to verify your solution.
"""
from spinup.exercises.pytorch.problem_set_1_solutions import exercise1_1_soln
from spinup.exercises.common import print_result
batch_size = 32
dim = 10
x = torch.rand(batch_size, dim)
mu = torch.rand(batch_size, dim)
log_std = torch.rand(dim)
your_gaussian_likelihood = gaussian_likelihood(x, mu, log_std)
true_gaussian_likelihood = exercise1_1_soln.gaussian_likelihood(x, mu, log_std)
your_result = your_gaussian_likelihood.detach().numpy()
true_result = true_gaussian_likelihood.detach().numpy()
correct = np.allclose(your_result, true_result)
print_result(correct)