PyTorch 损失函数评估

PyTorch loss function evaluation

我正在尝试使用 PyTorchGPU 的加速度优化函数 (fit)。这是直接的 Python 代码,我在其中计算 fit:

import numpy as np 
...
for j in range(P):
    e[:,j] = z - h[:,j];
    fit[j] = 1/(sqrt(2*pi)*sigma*N)*np.sum(exp(-(e[:,j]**2)/(2*sigma**2))); 

The dimension of the variables are: z[Nx1], h[NxP], e[NxP], fit[1xP]. where P is the number of dimension of fit and N is the length of each dimension.

I am aware that for loops should be avoided, so where it is my attempt to do it using PyTorch through torch.cuda.FloatTensor.

import torch 
dtype = torch.cuda.FloatTensor
e     = z - h;
fit   = 1/(torch.sqrt(2*pi)*sigma*N)*torch.sum(torch.exp(-(torch.pw(e,2))/(2*torch.pow(sigma,2)))); 

Unfortunately it is not working. What is wrong? Thank you!

我猜你在下一行收到大小不匹配错误。

e = z - h

在您的示例中,z 是一个向量(形状为 Nx1 的二维张量),h 是形状为 NxP 的二维张量。所以,你不能直接从 z.

中减去 h

您可以执行以下操作以避免大小不匹配错误。

e = z.expand(*h.size()) - h

此处,z.expand(*h.size()) 将通过复制列向量 P 次,将张量 zNx1 转换为 NxP 形状。