在函数中载入并返回SavedModel Signature

在函数中载入SavedModel时要注意TensorFlow的这个BUG

在函数中载入并返回SavedModel Signature

封面图片:KS KYUNG

昨天尝试在项目中使用自己训练的TensorFlow人脸检测器替换OpenCV的人脸检测器时遇到了麻烦。

为了让代码更加易懂,我构造了一个人脸检测器类,并在类初始化函数中尝试载入以SavedModel格式储存的模型。简化代码如下:

def __init__(self, saved_model):
	# Load the SavedModel object.
	imported = tf.saved_model.load(saved_model)
	self._predict_fn = imported.signatures["serving_default"]
简化后的初始化代码

结果在实际使用时,TensorFlow报错

AssertionError: Called a function referencing variables which have been deleted. This likely means that function-local variables were created and not referenced elsewhere in the program. This is generally a mistake; consider storing variables in an object attribute on first call.

或者

FailedPreconditionError: Error while reading resource variable _AnonymousVar30 from Container: localhost. This could mean that the variable was uninitialized.

一开始百思不得其解,后来搜索后发现这是一个TensorFlow的BUG。当函数执行完毕后,imported 对象被回收了,但是TensorFlow仍然需要它。在官方修复这个BUG之前,解决办法是手动追踪该对象。

self._predict_fn._backref_to_saved_model = imported
当前的解决方案

该解决方案来自issue 46708的作者,可以在这里围观

Using the function signatures loaded from a SavedModel requires the original trackable object be kept in scope. · Issue #46708 · tensorflow/tensorflow
System information Have I written custom code (as opposed to using a stock example script provided in TensorFlow): Yes OS Platform and Distribution (e.g., Linux Ubuntu 16.04): macOS 10.15.7 TensorF...
现场围观该BUG