Pythorch损失函数评估

2024-04-24 07:21:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用PyTorch中的GPU的加速度来优化函数(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.

^{pr2}$

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


Tags: oftheforgpuisnpitpytorch
1条回答
网友
1楼 · 发布于 2024-04-24 07:21:30

我猜您在下面的行中得到了大小不匹配的错误。在

e = z - h

在您的例子中,z是一个向量(形状Nx1的二维张量,h是形状NxP的二维张量。所以,不能直接从z中减去h。在

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

^{pr2}$

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

相关问题 更多 >