【问题标题】:Most efficient way to do this slice based multiplication in Tensorflow在 Tensorflow 中进行这种基于切片的乘法的最有效方法
【发布时间】:2017-11-12 19:42:33
【问题描述】:

我正在尝试执行将二维矩阵的切片乘以常数的操作。

例如,如果我想将除前 2 列之外的所有内容相乘

要在 numpy 中执行此操作,可以这样做:

a = np.array([[0,7,4],
              [1,6,4],
              [0,2,4],
              [4,2,7]])
a[:, 2:] = 2.0*a[:, 2:]

>> a
>> array([[ 0,  7,  8],
          [ 1,  6,  8],
          [ 0,  2,  8],
          [ 4,  2, 14]])

但是,至少从我搜索到的内容来看,tensorflow 目前还没有直接的方法来做到这一点。

我当前的解决方案是创建 a 最初作为两个单独的张量 a1 和 a2,将第二个张量乘以 2.0,然后将它们跨轴 = 1 连接。操作很简单,这是可能的。但是我有两个问题

  1. 这是最有效的方法吗
  2. 是否有更好(通用/高效)的方法来执行此操作,以使功能更接近 numpy 的切片魔法(也许 https://www.tensorflow.org/api_docs/python/tf/scatter_

【问题讨论】:

    标签: numpy tensorflow slice


    【解决方案1】:

    一种选择是执行逐项乘法,如下所示:

    import tensorflow as tf
    
    a = tf.Variable(initial_value=[[0,7,4],[1,6,4],[0,2,4],[4,2,7]])
    b = tf.mul(a,[1,1,2])
    
    s=tf.InteractiveSession()
    s.run(tf.global_variables_initializer())
    b.eval()
    

    这会打印出来

    array([[ 0,  7,  8],
           [ 1,  6,  8],
           [ 0,  2,  8],
           [ 4,  2, 14]])
    

    更一般地说,如果a 有更多列,您可以这样做:

    import tensorflow as tf
    
    a = tf.Variable(initial_value=[[0,7,4],[1,6,4],[0,2,4],[4,2,7]])
    b = tf.mul(a,[1,1]+[2 for i in range(a.get_shape()[1]-2)])
    
    s=tf.InteractiveSession()
    s.run(tf.global_variables_initializer())
    b.eval()
    

    或者如果你的矩阵有很多列,你可以替换

    b = tf.mul(a,[1,1]+[2 for i in range(a.get_shape()[1]-2)])
    

    import numpy as np
    b = tf.mul(a,np.concatenate((np.array([1,1]),2*np.ones(a.get_shape()[1]-2))))
    

    【讨论】:

    • 嗨 Miriam,感谢您的选择。如何将其推广到可变的二维? IE。如果 a.shape = (N,D)。需要定义 [1,1,2,2,2,2......2]
    • @miriamfaber 感谢您的更新!它看起来不错(虽然 tf.mul 是 tf.matmul)我想知道您是否有任何理由将 numpy 用于常量数组而不是 tensorflow 等效项
    • @undercurrent 你也可以使用 tf.ones,我只是忘记了它的存在。请注意,tf.matmul 和 tf.mul 并不相同。前者是通常的矩阵乘法,而后者是逐项乘积。在我的回答中,我使用了后者
    • 啊哈,感谢您的澄清。回复:matmul(哎呀!)我的意思是写 tf.multiply()
    猜你喜欢
    • 1970-01-01
    • 2017-07-17
    • 2019-06-29
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 2012-09-27
    • 2021-04-25
    • 2020-08-29
    相关资源
    最近更新 更多