简体   繁体   中英

How to convert a matrix of torch.tensor to a larger tensor?

I meet a problem to convert a python matrix of torch.tensor to a torch.tensor

For example, M is an (n,m) matrix, with each element M[i][j] is a torch.tensor with same size (p, q, r, ...) . How to convert python list of list M to a torch.tensor with size (n,m,p,q,r,...) eg

M = []
for i in range(5):
    row = []
    for j in range(10):
        row.append(torch.rand(3,4))
    M.append(row)

How to convert above M to a torch.tensor with size (5,10,3,4) .

Try torch.stack() to stack a list of tensors on the first dimension.

import torch

M = []
for i in range(5):
    row = []
    for j in range(10):
        row.append(torch.rand(3,4))
    row = torch.stack(row)
    M.append(row)
M = torch.stack(M)

print(M.size())
# torch.Size([5, 10, 3, 4])

Try this.

ref = np.arange(3*4*5).reshape(3,4,5) # numpy array
values = [ref.copy()+i for i in range(6)] # List of numpy arrays
b = torch.from_numpy(np.array(values)) # torch-array from List of numpy arrays

References

  1. Converting NumPy Array to Torch Tensor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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