maplemaple
maplemaple

Reputation: 1725

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,...) e.g.

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).

Upvotes: 0

Views: 687

Answers (2)

yanarp
yanarp

Reputation: 175

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])

Upvotes: 1

CypherX
CypherX

Reputation: 7353

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

Upvotes: 0

Related Questions