如何解决如何使用TensorFlow v2进行数据流编程?
我找不到有关如何使用TensorFlow v2进行基本数据流编程的适当文档。我可以在网上找到许多有关TensorFlow v1的资源,但是现在已经弃用了他们解释的许多行为。例如,以下python代码在TensorFlow v1中可以正常工作:
import tensorflow as tf
# Define some helper functions
def func1(a,b):
return a+b # Or any manipulation of the arguments
def func2(a,b):
return a*b
def func3(a,b):
return a-b
# Define a graph; (a,b)-->e,(c,d)-->f,(e,f)-->g
a = tf.placeholder(tf.float64)
b = tf.placeholder(tf.float64)
c = tf.placeholder(tf.float64)
d = tf.placeholder(tf.float64)
e = tf.py_func(func1,[a,b],tf.float64)
f = tf.py_func(func2,[c,d],tf.float64)
g = tf.py_func(func3,[e,f],tf.float64)
# Execute in a session
sess1 = tf.Session()
res = sess1.run([g],feed_dict={a:1,b:2,c:3,d:4})
print(res) # = [-9.0]
这里,我已经将一些python函数转换为tensorflow操作;我定义了一个图,其中g
依赖于e
,而f
依赖于a,b,c,d
;最后,我执行了一个会话并为a,d
提供了输入。
我还可以避免提供所有输入,而是选择中间节点:
sess2 = tf.Session()
res = sess2.run([g],f:12})
print(res) # = [-9.0]
在这里,我已经提供了f
,而不是其依赖项c,d
。
在TensorFlow v2中(除了导入tensorflow.compat.v1
之外,这样的事情如何工作? TensorFlow v2甚至被认为可以做这样的事情还是仅仅是机器学习?
注意:这以某种方式连接到this question,后者处理的问题要复杂得多。
解决方法
据我了解,TF 2.0的main motivation摆脱了先定义所有数据流然后在最后调用它的旧样式。他们想改用更蟒蛇的做事方式。
其中一个重要部分是用pythonic方式定义函数,然后用@tf.function
装饰它们,以使tensorflow生成图形并提高性能。
在TF2中,不建议使用"kitchen sink"方法将所有内容放到大图中,然后根据您的需要运行会话。
在您的示例中,这看起来像
import tensorflow as tf
# Define some helper functions
def func1(a,b):
return a+b # Or any manipulation of the arguments
def func2(a,b):
return a*b
def func3(a,b):
return a-b
如果您只需要一个大型功能,那就足够了:
# define combined tf function,the decorated ensures a graph is generated.
@tf.function
def tf2_function(a,b,c,d):
e = func1(a,b)
f = func2(c,d)
g = func3(e,f)
return g
e,f,g = tf2_function(1,2,3,4) # -9
但是,如果您需要获取中间值或提供中间值的选项,那么最好的选择是将函数拆分为两个较小的函数as is recommended by the TF-developers。
@tf.function
def get_f(a,d)
return f
@tf.function
def get_g_from_e_f(e,f):
g = func3(e,f)
return g
您也不需要用@tf.function
装饰每个函数,通常用它来装饰较大,更昂贵的函数就足够了,所有称为buy them的函数也将转换为图形。
但是,是的,没有真正的方法可以在TF2中提供不同的值并从图形中获得不同的输出来完成您在TF1.x中可以做的事情。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。