【问题标题】:Is there any way to convert pytorch tensor to tensorflow tensor有什么方法可以将 pytorch 张量转换为 tensorflow 张量
【发布时间】:2020-06-28 12:17:29
【问题描述】:

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

我需要使用上面链接中在 TensorFlow 中实现的 mulit_dimensional_attention,但我正在使用 PyTorch,所以我可以将 Pytorch Tensor 转换为 TensorFlow Tensor,或者我必须在 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

【问题讨论】:

    标签: pytorch attention-model mindsdb


    【解决方案1】:

    您可以将 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)
    

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

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

    【讨论】:

      猜你喜欢
      • 2022-10-17
      • 2020-08-05
      • 2019-07-29
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多