[英]PyTorch loss function evaluation
I am trying to optimise a function ( fit
) using the acceleration of GPU
in PyTorch
. 我正在尝试使用
PyTorch
中GPU
的加速来优化功能( 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]。 whereP
is the number of dimension offit
andN
is the length of each dimension.其中
P
是fit
尺寸的数量,N
是每个尺寸的长度。I am aware that
for
loops should be avoided, so where it is my attempt to do it usingPyTorch
throughtorch.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
倍,将张量z
从Nx1
转换为NxP
形状。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.