【问题标题】:matmul function for vector with tensor multiplication in tensorflowtensorflow中具有张量乘法的向量的matmul函数
【发布时间】:2018-05-11 22:19:25
【问题描述】:

一般来说,当我们将一个维度为1*n 的向量v 与一个维度为m*n*k 的张量T 相乘时,我们期望得到一个维度为m*k/m*1*k 的矩阵/张量。这意味着我们的张量具有维度为n*k 的矩阵m 切片,并且v 与每个矩阵相乘,并将结果向量堆叠在一起。为了在tensorflow 中进行这种乘法运算,我提出了以下公式。我只是想知道是否有任何内置函数可以直接执行此标准乘法?

T = tf.Variable(tf.random_normal((m,n,k)), name="tensor") 
v = tf.Variable(tf.random_normal((1,n)), name="vector")  
c = tf.stack([v,v]) # m times, here set m=2
output = tf.matmul(c,T)

【问题讨论】:

    标签: tensorflow tensor vector-multiplication


    【解决方案1】:

    你可以这样做:

    tf.reduce_sum(tf.expand_dims(v,2)*T,1)
    

    代码:

    m, n, k = 2, 3, 4
    T = tf.Variable(tf.random_normal((m,n,k)), name="tensor") 
    v = tf.Variable(tf.random_normal((1,n)), name="vector")  
    
    
    c = tf.stack([v,v]) # m times, here set m=2    
    out1 = tf.matmul(c,T) 
    
    out2 = tf.reduce_sum(tf.expand_dims(v,2)*T,1)
    with tf.Session() as sess:
      sess.run(tf.global_variables_initializer())
      n_out1 = sess.run(out1) 
      n_out2 = sess.run(out2)
      #both n_out1 and n_out2 matches
    

    【讨论】:

      【解决方案2】:

      不确定是否有更好的方法,但听起来您可以像这样使用tf.map_fn

       output = tf.map_fn(lambda x: tf.matmul(v, x), T)
      

      【讨论】:

        猜你喜欢
        • 2017-08-21
        • 1970-01-01
        • 1970-01-01
        • 2019-04-11
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        • 2020-06-12
        • 2018-11-06
        相关资源
        最近更新 更多