我正在运行一个程序,在这个程序中,中间步骤返回一个张量(比如T)。张量不包含参数,而只是实数。
我想对T使用一个指数形式的参数,让我们将这个参数命名为x,所以中间步骤现在应该返回T^x。
我试图训练模型,但在第一次向后传递之后,x的值变成了nan。
如果我使用乘法而不是幂运算,也就是Tx而不是T^x,那么没有任何nan值,训练就会进行得很好。
是否可以在PyTorch中将参数作为指数传递?如果是,那么我如何训练x?
发布于 2021-10-17 14:10:10
导入手电筒导入torch.nn作为nn导入torch.distributions作为dd
log_std = nn.Parameter(torch.Tensor(1)) #将参数的对数定义为nn.Parameter,这是我们要优化的均值= nn.Parameter(torch.Tensor(1)) #一个正常参数
optim = torch.optim.SGD(log_std,mean,lr=0.001) #标准优化器目标= dd.Normal(5,5) #要匹配的目标分布
对于范围(50)内的i: optim.zero_grad()
std = torch.exp(log_std) # Define the transformation we want to apply to the parameter to using it in the distribution
dist = dd.Normal(loc=mean, scale=std) # Define the distribution.
samples = dist.rsample((1000,)) # Sample our model, note no reference to log_std
cost = -(target.log_prob(samples) - dist.log_prob(samples)).sum() # KL divergence cost metric
cost.backward()
optim.step()
print(i)
print(mean, std, cost)
print()https://stackoverflow.com/questions/69604902
复制相似问题