0

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

2 Answers 2

1

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])
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.