简体   繁体   English

如何在PyTorch中生成具有不同向量的新Tensor?

[英]How to generate a new Tensor with different vectors in PyTorch?

I want to generate new a○b vector with a and b (○ means element wise multiply). 我想用ab生成新的a○b向量(○表示元素明智的相乘)。 My code is below, but the performance looks bad because of for . 我的代码在下面,但是由于for ,性能看起来很差。 Are there any efficient way? 有什么有效的方法吗?

a = torch.rand(batch_size, a_len, hid_dim)
b = torch.rand(batch_size, b_len, hid_dim)
# a_elmwise_mul_b = torch.zeros(batch_size, a_len, b_len, hid_dim)
for sample in range(batch_size):
    for ai in range(a_len):
        for bi in range(b_len):
            a_elmwise_mul_b[sample, ai, bi] = torch.mul(a[sample, ai], b[sample, bi])

Update 更新

I updated my code refer to Ahmad! 我更新了我的代码以参考Ahmad! Thank you. 谢谢。

N = 16
hid_dim = 50
a_seq_len = 10
b_seq_len = 20
a = torch.randn(N, a_seq_len, hid_dim)
b = torch.randn(N, b_seq_len, hid_dim)
shape = (N, a_seq_len, b_seq_len, hid_dim)

a_dash = a.unsqueeze(2) # (N, a_len, 1,     hid_dim)
b_dash = b.unsqueeze(1) # (N, 1,     b_len, hid_dim)
a_dash = a_dash.expand(shape)
b_dash = b_dash.expand(shape)
print(a_dash.size(), b_dash.size())
mul = a_dash * b_dash
print(mul.size())
----------
torch.Size([16, 10, 20, 50]) torch.Size([16, 10, 20, 50])
torch.Size([16, 10, 20, 50])

From your problem definition, it looks like you want to multiply two tensors, say A and B of shape AxE and BxE and want to get a tensor of shape AxBxE . 从问题定义来看,您似乎想乘以两个张量,例如ABAxEBxE形状,并想要获得一个AxBxE形状的张量。 It means you want to multiply, each row of tensor A with the whole tensor B . 这意味着您想将张量A每一行与整个张量B相乘。 If it is correct, then we don't call it element-wise multiplication. 如果是正确的,那么我们就不称其为逐元素乘法。

You can accomplish your goal as follows. 您可以如下实现目标。

import torch

# batch_size = 16, a_len = 10, b_len = 20, hid_dim = 50
a = torch.rand(16, 10, 50)
b = torch.rand(16, 20, 50)

c = a.unsqueeze(2).expand(*a.size()[:-1], b.size(1), a.size()[-1])
d = b.unsqueeze(1).expand(b.size()[0], a.size(1), *b.size()[1:])
print(c.size(), d.size())
print(c.size(), d.size())

mul = c * d       # shape of c, d: 16 x 10 x 20 x 50
print(mul.size()) # 16 x 10 x 20 x 50

Here, mul tensor is your desired result. 在这里, mul张是你想要的结果。 Just to clarify, the above two lines realted to c and d computation, are equivalent to: 为了澄清起见,以上针对cd计算的两行等效于:

c = a.unsqueeze(2).expand(a.size(0), a.size(1), b.size(1), a.size(2))
d = b.unsqueeze(1).expand(b.size(0), a.size(1), b.size(1), b.size(2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM