记录tensorflow中有关autograph的坑
tensorflow 2.0 之前使用session构建计算图,构建过程非常复杂,把 python 变得和 C++ 一样复杂。
tensorflow 2.0 之后引入autograph,只需要在函数声明前加上 tf.function,就可以将我们的函数自动转为计算图。看起来比 session 要更接近 python,但转计算图过程中的错误非常难定位找到原因。
但是不使用计算图,直接运行 python 代码,效率极低。我尝试将 tensorflow 2.0 之前的代码转为 tensorflow2.0之后的版本,起初只是把 session构建的计算图转为了简单的python函数,效率低了十几倍。
下面记录一下,我使用 autograph 遇到的坑。
问题 1
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.
- 发生场景:定义类函数为 autograph,autograph 中使用了类成员,其类型为 python 的 list,并且在 autograph 中该成员被重复赋值。
- 解决办法:使用局部变量的 python list。
- 为什么:autograph 中也有重复赋值的其他类成员,但都是 tensorflow的tensor类型。