在 TensorFlow 中,如何在非本地方法中对方法本地的张量进行就地更改?

How to make in-place changes to a tensor local to a method in a method it is not local to, in TensorFlow?

我们知道在python中,数据是按名称跨方法传递的。假设我有一个列表 a,它是方法 m1() 的本地列表,我想将它传递给另一个方法并在其他方法中对其进行一些更改并保留这些更改, 那么它就非常简单了,可以按如下方式完成:

def m1(a):
   a.append(5)
def m2():
   a = [1, 2, 3, 4]
   print('Before: ', a) # Output= Before: [1, 2, 3, 4]
   m1(a)
   print('After: ', a) # Output= After: [1, 2, 3, 4, 5]
m2()

如果 a 是一个张量,如何做同样的事情?我想做类似

的事情
def m1(t1):
  t2 = tf.constant([[[7, 4], [8, 4]], [[2, 10], [15, 11]]])
  tf.concat([t1, t2], axis = -1)


def m2():
  t1 = tf.constant([[[1, 2], [2, 3]], [[4, 4], [5, 3]]])
  se = tf.Session()
  print('Before: ', se.run(t1)) # Output = Before: [[[1, 2], [2, 3]], [[4, 4], [5, 3]]]
  m1(t1)
  print('After: ', se.run(t1))  #Actual Output = After : [[[1, 2], [2, 3]], [[4, 4], [5, 3]]] | Desired Output = After : [[[1, 2, 7, 4], [2, 3, 8, 4]], [[4, 4, 2, 10], [5, 3, 15, 11]]]

m2()

tf.concat 实际上是 returns 串联的张量,并没有在适当的位置进行,因为张量流基本上是在图中添加新节点。所以,这个新的张量被添加到图中。

此代码有效:

import tensorflow as tf

def m1(t1):
  t2 = tf.constant([[[7, 4], [8, 4]], [[2, 10], [15, 11]]])
  return tf.concat([t1, t2], axis = -1)

def m2():
  t1 = tf.constant([[[1, 2], [2, 3]], [[4, 4], [5, 3]]])
  se = tf.Session()
  print('Before: ', se.run(t1)) # Output = Before: [[[1, 2], [2, 3]], [[4, 4], [5, 3]]]
  t1 = m1(t1)
  print('After: ', se.run(t1))  #Actual Output = After : [[[1, 2], [2, 3]], [[4, 4], [5, 3]]] | Desired Output = After : [[[1, 2, 7, 4], [2, 3, 8, 4]], [[4, 4, 2, 10], [5, 3, 15, 11]]]

m2()

它给出以下输出:

('Before: ', array([[[1, 2],
        [2, 3]],

       [[4, 4],
        [5, 3]]], dtype=int32))
('After: ', array([[[ 1,  2,  7,  4],
        [ 2,  3,  8,  4]],

       [[ 4,  4,  2, 10],
        [ 5,  3, 15, 11]]], dtype=int32))

参考这个tf.concat