在张量流中,如何在一个方法中对一个方法局部的张量进行局部的改变?

2024-03-29 10:30:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我们知道,在python中,数据是通过名称跨方法传递的。假设我有一个lista,它是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是张量,怎么做?我想做点什么

^{pr2}$

Tags: 数据方法名称outputdef方式printafter
1条回答
网友
1楼 · 发布于 2024-03-29 10:30:09

tf.concat实际上返回连接的张量,而不是就地执行,因为tensorflow基本上是在图中添加新节点。所以,这个新的张量被添加到图中。在

此代码起作用:

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()

输出如下:

^{pr2}$

参考这个tf.concat

相关问题 更多 >