【问题标题】:3-D batch matrix multiplication without knowing batch size不知道批量大小的 3-D 批量矩阵乘法
【发布时间】:2018-06-19 05:47:12
【问题描述】:

我目前正在编写一个 tensorflow 程序,该程序需要将一批 2-D 张量(形状为 [None,...] 的 3-D 张量)与 2-D 矩阵 W 相乘。这需要将W 转换为 3-D 矩阵,这需要知道批量大小。

我无法做到这一点; tf.batch_matmul 不再可用,x.get_shape().as_list()[0] 返回 None,这对于整形/平铺操作无效。有什么建议?我见过有人用config.cfg.batch_size,但我不知道那是什么。

【问题讨论】:

    标签: arrays tensorflow machine-learning neural-network matrix-multiplication


    【解决方案1】:

    解决方案是使用tf.shape(在运行时返回形状)和tf.tile(接受动态形状)的组合。

    x = tf.placeholder(shape=[None, 2, 3], dtype=tf.float32)
    W = tf.Variable(initial_value=np.ones([3, 4]), dtype=tf.float32)
    print(x.shape)                # Dynamic shape: (?, 2, 3)
    
    batch_size = tf.shape(x)[0]   # A tensor that gets the batch size at runtime
    W_expand = tf.expand_dims(W, axis=0)
    W_tile = tf.tile(W_expand, multiples=[batch_size, 1, 1])
    result = tf.matmul(x, W_tile) # Can multiply now!
    
    with tf.Session() as sess:
      sess.run(tf.global_variables_initializer())
      feed_dict = {x: np.ones([10, 2, 3])}
      print(sess.run(batch_size, feed_dict=feed_dict))    # 10
      print(sess.run(result, feed_dict=feed_dict).shape)  # (10, 2, 4)
    

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多