【问题标题】:How do I add only certain columns to a tensor in tensorflow?如何仅将某些列添加到张量流中的张量?
【发布时间】:2022-01-06 20:06:39
【问题描述】:

考虑下面的代码:

import tensorflow as tf

test=tf.constant([[[100., 2., -30.],[-4,5,6]], [[4., 5., 6.],[-7,8,9]]]) # matrix

print(test)

test1=tf.constant([[[100.]],[[  8.]]])

print(test1)

将 test1 添加到 test 的前两列时,我们会得到以下输出:

print(test[:,:,0:2]+test1)

我不想将 test1 变量添加到测试变量的最后一列,但同时我想在输出中包含测试变量的最后一列不变:

[[[200. 102., -30.]
  [ 96. 105., 6.]]

 [[ 12.  13., 6]
  [  1.  16., 9]]]

如何快速编写代码?

【问题讨论】:

    标签: python tensorflow tensorflow2.0 tensor addition


    【解决方案1】:

    最简单的选择就是使用tf.concat

    import tensorflow as tf
    
    test = tf.constant([[[100., 2., -30.],[-4,5,6]], [[4., 5., 6.],[-7,8,9]]]) # matrix
    test1 = tf.constant([[[100.]],[[  8.]]])
    
    print(tf.concat([test[:,:,0:2] + test1, test[:,:,2:]], axis=-1))
    
    tf.Tensor(
    [[[200. 102. -30.]
      [ 96. 105.   6.]]
    
     [[ 12.  13.   6.]
      [  1.  16.   9.]]], shape=(2, 2, 3), dtype=float32)
    

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 2018-09-15
      • 2019-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-05
      • 2018-01-17
      • 1970-01-01
      相关资源
      最近更新 更多