'only one element tensors can be converted

I was trying to speed up the code for calculating the distance by this code

    points = genfromtxt(path, delimiter='\t', usecols=[0, 1])
    max_id = len(points)
    points =torch.tensor(points)
    d = pd.DataFrame(np.zeros((max_id, max_id)))  
    dis = torch.cdist(points,points) 
    n = 0
    for i in range(max_id):
        print(i)
        for j in range(i + 1, max_id):
            d.at[i, j] = dis[n]
            d.at[j, i] = d.at[i, j]
            n += 1

i got

d.at[i, j] = dis[n]
ValueError: only one element tensors can be converted to Python scalars


Solution 1:[1]

import torch
points = torch.randint(1,5,(4,2)).float() # You already have this 
print(points)
dis = torch.cdist(points,points)
print(dis)

Output

tensor([[2., 1.],
        [1., 2.],
        [3., 4.],
        [4., 4.]])
tensor([[0.0000, 1.4142, 3.1623, 3.6056],
        [1.4142, 0.0000, 2.8284, 3.6056],
        [3.1623, 2.8284, 0.0000, 1.0000],
        [3.6056, 3.6056, 1.0000, 0.0000]])

Here is a snippet to help you understand how to work with cdist. It is returning the scalar distance already. You don't need to do anything extra. You already have the dis matrix here.

You want the dis tensor to be in numpy array you can simply call numpy() function.

dis_np = dis.numpy()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user2736738