[英]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我遇到了将 torch.tensor 的 python 矩阵转换为 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, ...)
.例如, M
是一个(n,m)
矩阵,每个元素M[i][j]
是一个具有相同大小(p, q, r, ...)
。 How to convert python list of list M
to a torch.tensor with size (n,m,p,q,r,...)
eg如何将列表M
的 python 列表转换为大小为(n,m,p,q,r,...)
例如
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)
.如何将M
以上转换为尺寸为(5,10,3,4)
的 torch.tensor。
Try torch.stack()
to stack a list of tensors on the first dimension.尝试torch.stack()
在第一维上堆叠张量列表。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.