TensorFlow报错无py_func属性,使用tf.compat.v1.py_func仍无效如何解决
问题根因
tf.py_func是TensorFlow 1.x版本的原生API,TensorFlow 2.x正式版本中已经完全移除了该接口,仅在兼容层保留了tf.compat.v1.py_func,如果直接调用会抛出属性不存在的错误。如果已经尝试用兼容层接口仍报错,一般是2.x默认开启了Eager Execution模式导致的兼容问题,或者存在返回值类型不匹配的问题。
修复方案
- 方案1:适配TensorFlow 2.x兼容层
首先在代码导入TensorFlow后的最开头添加关闭Eager Execution的配置:
import tensorflow as tf tf.compat.v1.disable_eager_execution()
再将代码中所有tf.py_func替换为tf.compat.v1.py_func,参数保持不变即可:
neighbour_idx = tf.compat.v1.py_func(DP.knn_search, [batch_xyz, batch_xyz, cfg.k_n], tf.int32) up_i = tf.compat.v1.py_func(DP.knn_search, [sub_points, batch_xyz, 1], tf.int32)
如果修改后仍有报错,检查DP.knn_search函数的返回值numpy数组类型是否和声明的tf.int32完全匹配,类型不匹配也会触发运行时错误。
- 方案2:使用2.x原生替代接口(更推荐长期使用)
直接将所有tf.py_func替换为2.x原生的tf.numpy_function,该接口是官方指定的tf.py_func替代实现,天然适配Eager Execution模式,不需要额外关闭2.x行为,参数和原接口完全兼容:
neighbour_idx = tf.numpy_function(DP.knn_search, [batch_xyz, batch_xyz, cfg.k_n], tf.int32) up_i = tf.numpy_function(DP.knn_search, [sub_points, batch_xyz, 1], tf.int32)
注意:tf.numpy_function返回的Tensor默认没有固定shape信息,如果后续操作依赖固定shape,可以手动调用set_shape方法给返回值设置shape,避免后续图编译报错。
内容的提问来源于stack exchange,提问作者youssef
相关产品推荐
相关产品推荐

