我有一个torch tensors
的列表
list_tensor = [tensor([[1, 2, 3],
[3, 4, 5]]),
tensor([[4, 5, 6],
[6, 4, 3]]),
tensor([[4, 2, 1],
[3, 3, 1]]),
tensor([[1, 4, 5],
[3, 1, 0]]),
tensor([[1, 3, 3],
[2, 2, 2]])]
我想在这个集合上做一个交叉验证,所以我想考虑四个张量作为训练,并保留一个用于测试-我想在len(list_tensor)
时间内这样做。
所以我想做点什么,
for num in range(1, len(list_tensor) + 1):
train_x = torch.cat((list_tensor[:num], list_tensor[num:]))
问题是我不能将列表用于torch.cat
操作,因为list_tensor[:num]
和list_tensor[num:]
都返回列表。例如,对于num = 1
,
list_tensor[:num] = [tensor([[1, 2, 3], [3, 4, 5]])]
list_tensor[num:] = [tensor([[4, 5, 6], [6, 4, 3]]), tensor([[4, 2, 1],[3, 3, 1]]), tensor([[1, 4, 5],
[3, 1, 0]]), tensor([[1, 3, 3], [2, 2, 2]])]
如何对此执行torch.cat?
发布于 2020-07-06 05:30:05
我在没有使用reduce
的情况下找到了一个解决办法。
train_x = torch.cat((torch.cat(list_tensor[:num+1]),torch.cat(list_tensor[num+1:])))
基本上连接了单个列表中的所有张量,这将返回一个torch.tensor
对象,然后在这两个对象上使用torch.cat
。
发布于 2020-07-03 00:36:59
您可以使用reduce
import torch as T
from functools import reduce
reduce(lambda x,y: T.cat((x,y)), list_tensor[:-1])
基本思想是将concat运算符应用于列表中的所有张量,最后一个张量除外,并继续聚合结果。你可以阅读更多的here。
https://stackoverflow.com/questions/62706747
复制