有没有办法将pytorch张量转换为tensorflow张量

wal*_*mid 6 attention-model pytorch mindsdb

https://github.com/taoshen58/BiBloSA/blob/ec67cbdc411278dd29e8888e9fd6451695efc26c/context_fusion/self_attn.py#L29

我需要使用上述链接中的 multi_Dimension_attention,该链接是在 TensorFlow 中实现的,但我使用的是 PyTorch,所以我可以将 Pytorch 张量转换为 TensorFlow 张量,还是必须在 PyTorch 中实现它。

我试图在这里使用的代码我必须将“rep_tensor”作为 TensorFlow 张量类型传递,但我有 PyTorch 张量

def multi_dimensional_attention(rep_tensor, rep_mask=None, scope=None,
                                keep_prob=1., is_train=None, wd=0., activation='elu',
                                tensor_dict=None, name=None):

    # bs, sl, vec = tf.shape(rep_tensor)[0], tf.shape(rep_tensor)[1], tf.shape(rep_tensor)[2]

    ivec = rep_tensor.shape[2]
    with tf.variable_scope(scope or 'multi_dimensional_attention'):
        map1 = bn_dense_layer(rep_tensor, ivec, True, 0., 'bn_dense_map1', activation,
                              False, wd, keep_prob, is_train)
        map2 = bn_dense_layer(map1, ivec, True, 0., 'bn_dense_map2', 'linear',
                              False, wd, keep_prob, is_train)
        # map2_masked = exp_mask_for_high_rank(map2, rep_mask)

        soft = tf.nn.softmax(map2, 1)  # bs,sl,vec
        attn_output = tf.reduce_sum(soft * rep_tensor, 1)  # bs, vec

        # save attn
        if tensor_dict is not None and name is not None:
            tensor_dict[name] = soft

        return attn_output

Run Code Online (Sandbox Code Playgroud)

Geo*_*rge 13

您可以将 pytorch 张量转换为 numpy 数组,并将其转换为 TensorFlow 张量,反之亦然:

import torch
import tensorflow as tf

pytorch_tensor = torch.zeros(10)
np_tensor = pytorch_tensor.numpy()
tf_tensor = tf.convert_to_tensor(np_tensor)
Run Code Online (Sandbox Code Playgroud)

话虽这么说,如果你想训练一个使用 pytorch 和 tensorflow 组合的模型,那么至少可以说,这会很尴尬、缓慢、有问题,并且需要很长时间才能编写。因为图书馆必须弄清楚如何反向传播成本。

因此,除非您拥有的 pytorch 注意力块经过预先训练,否则我建议您只使用一个库或另一个库,其中有大量示例可用于在任一库中实现您想要的任何内容,并且两者都有大量预训练模型。Tensorflow 通常要快一点,但速度差异并不那么显着,我上面介绍的那种“黑客”可能会使整个过程比独立使用任何一个库都要慢。