简体   繁体   English

PyTorch损失函数评估

[英]PyTorch loss function evaluation

I am trying to optimise a function ( fit ) using the acceleration of GPU in PyTorch . 我正在尝试使用PyTorchGPU的加速来优化功能( fit )。 This is the straight Python code, where I doing the evaluation of 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]. 变量的尺寸为: 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. 其中Pfit尺寸的数量, N是每个尺寸的长度。

I am aware that for loops should be avoided, so where it is my attempt to do it using PyTorch through torch.cuda.FloatTensor . 我知道应该避免for循环,因此我尝试通过torch.cuda.FloatTensor使用PyTorch进行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! 谢谢!

I guess you are getting size mismatch error at the following line. 我猜您在下一行收到大小不匹配错误。

e = z - h

In your example, z is a vector (2d tensor of shape Nx1 ) and h is a 2d tensor of shape NxP . 在您的示例中, z是向量(形状为Nx1的2d张量), h是形状为NxP的2d张量。 So, you can't directly subtract h from z . 因此,您不能直接从z减去h

You can do the following to avoid size mismatch error. 您可以执行以下操作以避免尺寸不匹配错误。

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

Here, z.expand(*h.size()) will convert the tensor z from Nx1 to NxP shape by duplicating the column vector P times. 在这里, z.expand(*h.size())通过将列向量复制P倍,将张量zNx1转换为NxP形状。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM