Tensor and numpy dimension conversion

1. Convert numpy to tensor (shared memory)

Use torch.from_numpy() to convert numpy to tensor

import numpy as np
import torch
n = np.random.randn(224, 224, 3)
print(n.shape)
t = torch.from_numpy(n)
print(t.shape)

(224, 224, 3)
torch.Size([224, 224, 3])

2. tensor to numpy (shared memory)

Use .numpy() to convert to numpy

a = torch.randn(3,4,5)
print(a.shape)
b = a.numpy()
print(b.shape)

torch.Size([3, 4, 5])
(3, 4, 5)

Guess you like

Origin blog.csdn.net/m0_59967951/article/details/126531628