使用tf.autograph.to_code()函数,将导入的notebook中的代码转换为可在当前环境下运行的代码。示例代码如下:
import tensorflow as tf
def foo(x):
if x > 0:
return x
else:
return -x
#将foo函数定义保存在另一个notebook文件中,文件名为"foo.ipynb"
#加载notebook文件
notebook = tf.notebook.load("foo.ipynb")
#获取其中定义的函数
foo_from_notebook = notebook.cells[0].outputs[0].text
#将导入的代码转换为当前环境下可运行的代码
foo_converted = tf.autograph.to_code(foo_from_notebook)
#执行转换后的代码
exec(foo_converted)
#测试转换后的代码
print(foo(5))
上一篇:Autograd行为澄清