如何迭代一组张量并将每个组中的元素传递给一个函数?
Posted
技术标签:
【中文标题】如何迭代一组张量并将每个组中的元素传递给一个函数?【英文标题】:How to iterate over a group of tensor and pass the elements from each group to a function? 【发布时间】:2019-09-03 06:14:05 【问题描述】:假设你有 3 个相同大小的张量:
a = torch.randn(3,3)
a = ([[ 0.1945, 0.8583, 2.6479],
[-0.1000, 1.2136, -0.3706],
[-0.0094, 0.4279, -0.6840]])
b = torch.randn(3, 3)
b = ([[-1.1155, 0.2106, -0.2183],
[ 1.6610, -0.6953, 0.0052],
[-0.8955, 0.0953, -0.7737]])
c = torch.randn(3, 3)
c = ([[-0.2303, -0.3427, -0.4990],
[-1.1254, 0.4432, 0.3999],
[ 0.2489, -0.9459, -0.5576]])
在 Lua (torch7) 中,它们有 this 函数:
[self] map2(tensor1, tensor2, function(x, xt1, xt2))
将给定的function
应用于self
的所有元素。
我的问题是:
-
python(pytorch)中是否有类似的功能?
是否有任何 Pythonic 方法可以在不使用
for loop
和 indices
的情况下迭代 3 个张量并获取每个张量的相应元素?
例如:
0.1945 -1.1155 -0.2303
0.8583 0.2106 -0.3427
2.6479 -0.2183 -0.4990
-0.1000 1.6610 -1.1254
...
Edit_1:我也试过itertools.zip_longest和zip,但结果和我预想的不一样
【问题讨论】:
【参考方案1】:您可以使用 Python 的 map
函数,类似于您提到的。像这样:
>>> tensor_list = [torch.tensor([i, i, i]) for i in range(3)]
>>> list(map(lambda x: x**2, tensor_list))
[tensor([0, 0, 0]), tensor([1, 1, 1]), tensor([4, 4, 4])]
>>>
编辑:对于仅 PyTorch 的方法,您可以使用 torch.Tensor.apply_
(请注意,这会进行适当的更改并且不会返回新的张量)
>>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> x.apply_(lambda y: y ** 2)
tensor([[ 1, 4, 9],
[16, 25, 36],
[49, 64, 81]])
>>>
【讨论】:
以上是关于如何迭代一组张量并将每个组中的元素传递给一个函数?的主要内容,如果未能解决你的问题,请参考以下文章
如何从数据框中迭代值并将值传递给 Python 中的发送电子邮件函数
如何迭代列表中的每个元素并将其与另一个元素相加以找到一个数字?