加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何遍历一组张量并将每个组中的元素传递给函数?

发布时间:2020-12-17 17:41:47 所属栏目:Python 来源:网络整理
导读:假设您有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 = tor

假设您有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))

将给定的功能应用于自我的所有元素.

我的问题是:

> python(pytorch)中是否有任何类似的功能?
>是否有任何pythonic方法可以遍历3个张量并获取每个张量的各个元素,而无需使用for循环和索引?

例如:

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,但是结果与上面提到的不一样

最佳答案
您可以使用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]),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,9],[16,25,36],[49,64,81]])
>>> 

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读