在Pythorch和Numpy中快速生成形状(1,1,256)和(10,1,256)的多个3D张量

2024-06-16 10:35:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为我自己的任务调整seq2seq模型,https://github.com/spro/practical-pytorch/blob/master/seq2seq-translation/seq2seq-translation.ipynb

在解码阶段我有两个张量

rnn_output: (1, 1, 256)       # time_step x batch_size x hidden_dimension
encoder_inputs: (10, 1, 256)  # seq_len   x batch_size x hidden_dimension

它们应该是多重的,以获得形状的注意力分数(在softmax之前)

^{pr2}$

最好的办法是什么?笔记本似乎使用了for循环,有没有比较好的通过矩阵乘法类的运算?在


Tags: https模型githubmastercomsizebatchpytorch
2条回答

使用^{}的示例:

import torch
from torch.autograd import Variable
import numpy as np

seq_len = 10
rnn_output = torch.rand((1, 1, 256))
encoder_outputs = torch.rand((seq_len, 1, 256))

# As computed in the tutorial:
attn_score = Variable(torch.zeros(seq_len))
for i in range(seq_len):
    attn_score[i] = rnn_output.squeeze().dot(encoder_outputs[i].squeeze())
    # note: the code would fail without the "squeeze()". I would assume the tensors in
    # the tutorial are actually (,256) and (10, 256)

# Alternative using batched matrix multiplication (bmm) with some data reformatting first:
attn_score_v2 = torch.bmm(rnn_output.expand(seq_len, 1, 256),
                          encoder_outputs.view(seq_len, 256, 1)).squeeze()

# ... Interestingly though, there are some numerical discrepancies between the 2 methods:
np.testing.assert_array_almost_equal(attn_score.data.numpy(), 
                                     attn_score_v2.data.numpy(), decimal=5)
# AssertionError: 
# Arrays are not almost equal to 5 decimals
# 
# (mismatch 30.0%)
#  x: array([60.32436, 69.04288, 72.04784, 70.19503, 71.75543, 67.45459,
#        63.01708, 71.70189, 63.07552, 67.48799], dtype=float32)
#  y: array([60.32434, 69.04287, 72.0478 , 70.19504, 71.7554 , 67.4546 ,
#        63.01709, 71.7019 , 63.07553, 67.488  ], dtype=float32)

没有使用pytorch的经验,但是像这样的东西能起作用吗?在

torch.einsum('ijk,abk->abc', (rnn_output, encoder_inputs))

它把点积放在最后一个轴上,然后再加上几个空轴。在

用纯numpy可以实现类似的功能(pytorch 0.4还没有...符号)

^{pr2}$

或使用np.tensordot

np.tensordot(rnn_output.numpy(), encoder_inputs.numpy(), axes=[2,2])

但在这里您将得到输出形状:(1, 1, 10, 1)

你可以通过挤压和重新膨胀来解决这个问题(几乎可以肯定,必须有更干净的方法来实现这一点

 np.tensordot(rnn_output.numpy(), encoder_inputs.numpy(), axes=[2,2]).squeeze()[..., None, None]

相关问题 更多 >