Suppose, I have a tensor of N*K, where N represents the number of a batch.
import torch
a = torch.Tensor(1000, 1)
dist = torch.Tensor(1000, 100)
points = torch.arange(100)
# for each a[i], I need to calculate the `distance loss` with each point.
for i in range(a.size(0)):
for j in range(points.size(0)):
dist[i][j] = 1/(0.1*torch.pow((a[i] - points[j]), 2) + 1e-8)
However, it is too slow using for-loop
. Does anyone have better solutions?
import torch
a = torch.randn(1000, 1)
a_clone = a.clone()
a = a.expand(1000, 100)
dist = torch.zeros(1000, 100)
p = torch.arange(100)
#p = torch.arange(100).view(100, 1)
p_clone = p.clone()
p = p.expand(1000, 100)
#p = p.expand(100, 1000).permute(1, 0)
loss = 1./(0.1*torch.pow((a-p), 2)+ 1e-5)
for i in range(a_clone.size(0)):
for j in range(p_clone.size(0)):
tmp = 1/(0.1*torch.pow((a_clone[i] - p_clone[j]), 2) + 1e-5)
dist[i, j] = tmp[0]
print dist.mean()
print loss.size()
print loss.mean()