> ## Content Index
> Fetch the complete content index at: https://yinguobing.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# 在函数中载入并返回SavedModel Signature
- URL: https://yinguobing.com/blog/load-function-signatures-from-a-savedmodel/
- Published: 2021-03-09T07:49:00.000Z
- Updated: 2021-03-09T07:49:00.000Z
- Description: 在函数中载入SavedModel时要注意TensorFlow的这个BUG
- Author: 尹国冰
- Tags: TensorFlow

封面图片：[KS KYUNG](https://unsplash.com/@mygallery?utm%5Fsource=unsplash&utm%5Fmedium=referral&utm%5Fcontent=creditCopyText)

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

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

```python3
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之前，解决办法是手动追踪该对象。

```python
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/tensorflowSystem 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...![](https://github.githubassets.com/favicons/favicon.svg)GitHubtensorflow![](https://avatars.githubusercontent.com/u/15658638?s=400&v=4)](https://github.com/tensorflow/tensorflow/issues/46708?ref=yinguobing.com)

现场围观该BUG