Skip to main content
 首页 » 编程设计

python之在 tensorflow 中使用自定义操作构建图形

2024年10月24日37jyk

我正在尝试探索将 tensorflow 与自定义操作结合使用。我构建了一个简单的开关操作并按照 tensorflow 文档中的建议对其进行了验证。现在我正在尝试构建图形,然后在 tensorflow 中调用 run() 方法 session 。下面是我的代码。我收到以下错误。有人可以帮助我应该怎么做才能解决它。每次向 /user_ops/ 添加新的自定义操作时,是否都需要重新安装 tensorflow?

import tensorflow as tf  
 
# Create a Constant op that produce integer value 
input1 = tf.constant(10) 
 
# Create another op that produce an integer value 
input2 = tf.constant(5) 
 
# Create op that produce 0 or 1 as the control input in a switch 
input3 = tf.constant(1) 
 
# Create a switch op that takes input1 and input2 as inputs and input3 as  
# the control input to produce an output 
out = tf.user_ops.simple_switch(input1, input2, input3) 
 
 
# Launch a default graph 
sess = tf.Session() 
 
# Call the 'run()' method and get the result 
result = sess.run(out) 
print(result) 
 
 
# Close the Session when we're done! 
sess.close() 

在 python 解释器中执行时出现以下错误:

Traceback (most recent call last): File "tensorflow-switch.py", line 14, in out = tf.simple_switch(input1, input2, input3) AttributeError: 'module' object has no attribute 'simple_switch'

请您参考如下方法:

在 adding a user-defined op 之后(在 TensorFlow 0.6.0 或更早版本中),要在 Python 解释器中使用它,您必须从源存储库重新安装。最简单的方法是 build and install a PIP package使用巴泽尔。 (单元测试会通过,因为运行 bazel test 会导致重建 TensorFlow,并在运行测试时使用重建的版本。)

注意:此功能是实验性的,用于添加用户定义操作的改进工作流程正在开发中。