Python TF2-tf.1函数和类变量中断
我使用的是tensorflow 2.3,如果我在类中存储值而不是返回值,那么类中的tf.function就会出现问题 比如说Python TF2-tf.1函数和类变量中断,python,tensorflow,tensorflow2.0,Python,Tensorflow,Tensorflow2.0,我使用的是tensorflow 2.3,如果我在类中存储值而不是返回值,那么类中的tf.function就会出现问题 比如说 将tensorflow导入为tf 课堂测试: 定义初始化(自): self.count=tf.convert_为_张量(0) @功能 def增量(自身): self.count+=1 返回自计数 t=测试() 计数=t.增量() count==t.count 创建以下错误 TypeError: An op outside of the function building
将tensorflow导入为tf
课堂测试:
定义初始化(自):
self.count=tf.convert_为_张量(0)
@功能
def增量(自身):
self.count+=1
返回自计数
t=测试()
计数=t.增量()
count==t.count
创建以下错误
TypeError: An op outside of the function building code is being passed
a "Graph" tensor. It is possible to have Graph tensors
leak out of the function building context by including a
tf.init_scope in your function building code.
For example, the following function will fail:
@tf.function
def has_init_scope():
my_constant = tf.constant(1.)
with tf.init_scope():
added = my_constant * 2
The graph tensor has name: add:0
当我检查count和t.count的值时,我看到
- 计数:
- t、 计数:
如何修复此问题,使t.count存储相同的值?您可以使用tf.Variable
class Test:
def __init__(self):
# self.count = tf.convert_to_tensor(0)
self.count = tf.Variable(0)
@tf.function
def incr(self):
self.count.assign_add(1)
return self.count
t = Test()
count = t.incr()
print(count) #tf.Tensor(1, shape=(), dtype=int32)
count = t.count
print(count)#<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=1>
这段代码只是一个简化的示例,我正在寻找一些解决我需要更新类变量的其他情况的方法。如果您解释一下为什么要修复它,也许会有所帮助
variable.assign
可能足够通用,但使用张量时一切都很好,直到我在类之外创建了一个类,当您使用图形上下文时,您无法获得张量的(numpy)值。张量总是指图形的一部分,没有它的值。@你找到了一个通用的解决方案吗?
count = tf.constant(0)
print(count)# count is eager_tensor : tf.Tensor(0, shape=(), dtype=int32)
@tf.function
def incr():
global count # we use count tensor inside graph contect
count+=1
return count
c = incr()
print(count)# now count is graph_tensor :Tensor("add:0", shape=(),dtype=int32)