如何使用Pytorch进行带约束优化的极大似然估计

mgdq6dx1  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(408)

我在研究Pytorch,我在试着构造一个代码来得到最大似然估计。
我想在优化过程中加入一些限制,以考虑参数限制(参数空间),但在pytorch.optim中,我们似乎没有这样的东西。
例如,我想得到一个正态分布的最大似然估计,其均值为mu,标准差为sigma,其中mu是一个真实的,sigma是一个正数。
这样,我想在我的代码中对sigma进行一个限制,使其始终为posti
这里我的代码:

  1. ##### PACKAGES
  2. import numpy as np
  3. from scipy.integrate import quad
  4. from scipy.optimize import minimize_scalar
  5. import torch
  6. from matplotlib import pyplot as plt
  7. import pandas as pd
  8. import math
  9. ##### SAMPLE
  10. np.random.seed(3)
  11. sample = np.random.normal(loc=5, scale=2, size=(1000, 1))
  12. ##### TENSORS
  13. X = torch.tensor(sample, dtype=torch.float64, requires_grad=False) ## X: sample
  14. mu_ = torch.tensor(np.array([0.5]), dtype=torch.float64, requires_grad=True) ## mu: mean
  15. s_ = torch.tensor(np.array([5]), dtype=torch.float64, requires_grad=True) ## s: standart desviation
  16. ##### OPTMIZATION METHOD: SGD
  17. learning_rate = 0.0002
  18. OPT_OBJ = torch.optim.SGD([mu_, s_], lr = learning_rate)
  19. ##### OPTIMAZTION METHOD
  20. for t in range(2000):
  21. NLL = X.size()[0]*s_.log()+((((X-mu_)/s_ ).pow(2))/2).sum() ## negative log-likelihood
  22. OPT_OBJ.zero_grad()
  23. NLL.backward()
  24. if t % 100 == 0:
  25. print("Log_Likehood: {}; Estimate mu: {}; Estimate sigma: {}".format(NLL.data.numpy(), mu_.data.numpy(), s_.data.numpy()))
  26. OPT_OBJ.step()
  27. print("True value of mu and sigma: {} e {}".format(5, 2))
s4chpxco

s4chpxco1#

您可以尝试使用torch.clamp()对Tensor设置约束(文档位于:https://pytorch.org/docs/stable/generated/torch.clamp.html)的数据。
否则,如果你只想保持标准差sigma为正值,ReLU函数会取0和输入元素之间的最大值(请参阅https://pytorch.org/docs/stable/generated/torch.nn.ReLU.html?highlight=torch%20nn%20relu#torch.nn.ReLU)。

相关问题