> For the complete documentation index, see [llms.txt](https://kerasnoone.gitbook.io/garnet/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kerasnoone.gitbook.io/garnet/gong-cheng-zhan/wang-luo-kuang-jia/tensorflow-serving/shi-jian-wen-ti/tablenotinitialized-cuo-wu.md).

# 使用feature\_columns出现Table not initialized错误

## 问题出现原因

在做推荐项目的排序模型时, 使用到了很多特征, 为了方便, 使用了`tf.feature_columns`模块去声明特征, 然后结合`tf.keras.layers.DenseFeatures`将特征和输入结合起来, 得到拼接在一起碾平的输入, 后面再接其他网络.

使用`tf.feature_columns`和`tf.keras.layers.DenseFeatures`会在生成的DenseLayer内部生成**查询表**(table), 例如`embedding_columns`会生成embedding矩阵. 在训练和预测之前, 需要先初始化这些table.

因此在训练之前, 需要先调用初始化op:

```python
sess = keras.backend.get_session()
sess,run(tf.tables_initialzer())
```

然后再执行训练过程.

为了优化推理阶段的时效, 以及考虑模型的定时更新, 我们在项目中使用了tensorflow-serving部署模型. 但在模型训练好, 保存, 并使用docker加载模型启动tensorflow-serving服务之后, 客户端去调用接口获取推理结果时, 遇到了报错的问题:

```
Failed precondition: Table not initialized.
```

## 解决方法

看来如同训练一样, 在tensorflow-serving加载模型之后, 也要进行一次tables\_initialzer操作, 才能正常进行推理.

但tensorflow-serving加载模型, 启动服务的过程并不涉及任何用户代码, 无法像训练时一样, 增加两行代码来完成初始化.

正确的解决方法是在使用`saved_model`模块保存模型时, 就指明初始化op操作:

```python
builder.add_meta_graph_and_variables(
        session,
        [tf.saved_model.tag_constants.SERVING],
        signature_def_map={tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: prediction_signature},
        main_op=tf.tables_initializer())
```

## 参考资料

* [How to build index\_table\_from\_file on serving? #1303](https://github.com/tensorflow/serving/issues/1303)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kerasnoone.gitbook.io/garnet/gong-cheng-zhan/wang-luo-kuang-jia/tensorflow-serving/shi-jian-wen-ti/tablenotinitialized-cuo-wu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
