【发布时间】:2022-09-26 02:05:57
【问题描述】:
我正在研究 Pytorch,我正在尝试构建一个代码来获得最大似然估计。
我想在优化过程中加入一些限制来考虑参数限制(参数空间),但看起来在 pytorch.optim 中我们没有这样的东西。
例如,我想获得具有平均 mu 和标准差 sigma 的正态分布的最大似然估计,其中 mu 是实数,sigma 是正数。
这样,我想在我的代码中限制 sigma 始终是一个 posti
这是我的代码:
##### PACKAGES
import numpy as np
from scipy.integrate import quad
from scipy.optimize import minimize_scalar
import torch
from matplotlib import pyplot as plt
import pandas as pd
import math
##### SAMPLE
np.random.seed(3)
sample = np.random.normal(loc=5, scale=2, size=(1000, 1))
##### TENSORS
X = torch.tensor(sample, dtype=torch.float64, requires_grad=False) ## X: sample
mu_ = torch.tensor(np.array([0.5]), dtype=torch.float64, requires_grad=True) ## mu: mean
s_ = torch.tensor(np.array([5]), dtype=torch.float64, requires_grad=True) ## s: standart desviation
##### OPTMIZATION METHOD: SGD
learning_rate = 0.0002
OPT_OBJ = torch.optim.SGD([mu_, s_], lr = learning_rate)
##### OPTIMAZTION METHOD
for t in range(2000):
NLL = X.size()[0]*s_.log()+((((X-mu_)/s_ ).pow(2))/2).sum() ## negative log-likelihood
OPT_OBJ.zero_grad()
NLL.backward()
if t % 100 == 0:
print(\"Log_Likehood: {}; Estimate mu: {}; Estimate sigma: {}\".format(NLL.data.numpy(), mu_.data.numpy(), s_.data.numpy()))
OPT_OBJ.step()
print(\"True value of mu and sigma: {} e {}\".format(5, 2))
标签: python optimization pytorch restriction mle