【问题标题】:Issue with embedding layer when serving a Tensorflow/Keras model with TF 2.0使用 TF 2.0 为 Tensorflow/Keras 模型提供嵌入层问题
【发布时间】:2020-01-23 05:51:59
【问题描述】:

我按照one of the TF beginner tutorial 中的步骤创建了一个简单的分类模型。它们是:

from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import feature_column
from tensorflow.keras import layers
from sklearn.model_selection import train_test_split

URL = 'https://storage.googleapis.com/applied-dl/heart.csv'
dataframe = pd.read_csv(URL)
dataframe.head()

train, test = train_test_split(dataframe, test_size=0.2)
train, val = train_test_split(train, test_size=0.2)

def df_to_dataset(dataframe, shuffle=True, batch_size=32):
  dataframe = dataframe.copy()
  labels = dataframe.pop('target')
  ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels))
  if shuffle:
    ds = ds.shuffle(buffer_size=len(dataframe))
  ds = ds.batch(batch_size)
  return ds

batch_size = 5 # A small batch sized is used for demonstration purposes
train_ds = df_to_dataset(train, batch_size=batch_size)
val_ds = df_to_dataset(val, shuffle=False, batch_size=batch_size)
test_ds = df_to_dataset(test, shuffle=False, batch_size=batch_size)

feature_columns = []
for header in ['age', 'trestbps', 'chol', 'thalach', 'oldpeak', 'slope', 'ca']:
  feature_columns.append(feature_column.numeric_column(header))
thal_embedding = feature_column.embedding_column(thal, dimension=8)
feature_columns.append(thal_embedding)

feature_layer = tf.keras.layers.DenseFeatures(feature_columns)

batch_size = 32
train_ds = df_to_dataset(train, batch_size=batch_size)
val_ds = df_to_dataset(val, shuffle=False, batch_size=batch_size)
test_ds = df_to_dataset(test, shuffle=False, batch_size=batch_size)


model = tf.keras.Sequential([
  feature_layer,
  layers.Dense(128, activation='relu'),
  layers.Dense(128, activation='relu'),
  layers.Dense(1, activation='sigmoid')
])

model.compile(optimizer='adam',
              loss='binary_crossentropy',
              metrics=['accuracy'],
              run_eagerly=True)

model.fit(train_ds,
          validation_data=val_ds,
          epochs=5)

我保存了模型:

model.save("model/", save_format='tf')

然后,我尝试使用此TF tutorial 为该模型提供服务。我执行以下操作:

docker pull tensorflow/serving
docker run -p 8501:8501 --mount type=bind,source=/path/to/model/,target=/models/model -e MODEL_NAME=mo

我尝试这样调用模型:

curl -d '{"inputs": {"age": [0], "trestbps": [0], "chol": [0], "thalach": [0], "oldpeak": [0], "slope": [1], "ca": [0], "exang": [0], "restecg": [0], "fbs": [0], "cp": [0], "sex": [0], "thal": ["normal"], "target": [0] }}' -X POST http://localhost:8501/v1/models/model:predict

我收到以下错误:

{ "error": "indices = 1 is not in [0, 1)\n\t [[{{node StatefulPartitionedCall_51/StatefulPartitionedCall/sequential/dense_features/thal_embedding/thal_embedding_weights/GatherV2}}]]" }

似乎与“thal”功能的嵌入层有关。但我不知道“indices = 1 is not in [0, 1)”是什么意思以及为什么会发生。

发生错误时,TF docker server 的日志如下:

2019-09-23 12:50:43.921721:W external/org_tensorflow/tensorflow/core/framework/op_kernel.cc:1502] OP_REQUIRES 在lookup_table_op.cc:952 失败:前提条件失败:表已初始化。

知道错误来自哪里以及如何修复它吗?

Python 版本:3.6

张量流版本:2.0.0-rc0

最新的 TensorFlow/serving(截至 2019 年 9 月 20 日)

模型签名:

signature_def['__saved_model_init_op']:
  The given SavedModel SignatureDef contains the following input(s):
  The given SavedModel SignatureDef contains the following output(s):
    outputs['__saved_model_init_op'] tensor_info:
        dtype: DT_INVALID
        shape: unknown_rank
        name: NoOp
  Method name is: 

signature_def['serving_default']:
  The given SavedModel SignatureDef contains the following input(s):
    inputs['age'] tensor_info:
        dtype: DT_INT32
        shape: (-1, 1)
        name: serving_default_age:0
    inputs['ca'] tensor_info:
        dtype: DT_INT32
        shape: (-1, 1)
        name: serving_default_ca:0
    inputs['chol'] tensor_info:
        dtype: DT_INT32
        shape: (-1, 1)
        name: serving_default_chol:0
    inputs['cp'] tensor_info:
        dtype: DT_INT32
        shape: (-1, 1)
        name: serving_default_cp:0
    inputs['exang'] tensor_info:
        dtype: DT_INT32
        shape: (-1, 1)
        name: serving_default_exang:0
    inputs['fbs'] tensor_info:
        dtype: DT_INT32
        shape: (-1, 1)
        name: serving_default_fbs:0
    inputs['oldpeak'] tensor_info:
        dtype: DT_FLOAT
        shape: (-1, 1)
        name: serving_default_oldpeak:0
    inputs['restecg'] tensor_info:
        dtype: DT_INT32
        shape: (-1, 1)
        name: serving_default_restecg:0
    inputs['sex'] tensor_info:
        dtype: DT_INT32
        shape: (-1, 1)
        name: serving_default_sex:0
    inputs['slope'] tensor_info:
        dtype: DT_INT32
        shape: (-1, 1)
        name: serving_default_slope:0
    inputs['thal'] tensor_info:
        dtype: DT_STRING
        shape: (-1, 1)
        name: serving_default_thal:0
    inputs['thalach'] tensor_info:
        dtype: DT_INT32
        shape: (-1, 1)
        name: serving_default_thalach:0
    inputs['trestbps'] tensor_info:
        dtype: DT_INT32
        shape: (-1, 1)
        name: serving_default_trestbps:0
  The given SavedModel SignatureDef contains the following output(s):
    outputs['output_1'] tensor_info:
        dtype: DT_FLOAT
        shape: (-1, 1)
        name: StatefulPartitionedCall:0
  Method name is: tensorflow/serving/predict

【问题讨论】:

  • 我也遇到了同样的问题...“indices = 1 is not in [0, 1)\n\t [[{{node StatefulPartitionedCall/StatefulPartitionedCall/sequential/dense_features/clientId_embedding/ clientId_embedding_weights/GatherV2}}]]"
  • 这可能与 tensorflow/serving:latest is 1.14.0 有关吗?
  • 不确定这是否相关... "请注意,在 CPU 上,如果发现超出范围的索引,则会返回错误。" tensorflow.org/api_docs/cc/class/tensorflow/ops/gather-v2
  • “thal”在哪里定义,你在这里使用它... thal_embedding = feature_column.embedding_column(thal, dimension=8)
  • 如果您传递为... "thal": [["normal"]] 而不是 "thal": ["normal"] 是否有效?我将 "clientId": 123 更改为 "clientId": [123] 并且问题对我来说消失了。仍在弄清楚为什么:)

标签: python tensorflow keras python-3.6 tensorflow-serving


【解决方案1】:

我也在尝试提供一个包含嵌入层、lstm 层等的模型,但我遇到了一些其他错误。我什至在 TF 上提出了issue

无论如何,我在您的代码中看到的问题在于您用于为 Docker 提供服务的已保存模型的类型。如果您阅读here,它会说以下几点-

A SavedModel to serve

这不是 keras model.save 而是另一个 TF API,here 是描述从 keras 训练模型创建 SavedModel 的方式。试一试,让我们知道结果。

【讨论】:

    【解决方案2】:

    我也遇到过同样的问题。改成如下格式。

    curl -d '{"inputs": {"age": [[0]], "trestbps": [[0]], "chol": [[0]], "thalach": [[0]], "oldpeak": [[0]], "slope": [[1]], "ca": [[0]], "exang": [[0]], "restecg": [[0]], "fbs": [[0]], "cp": [[0]], "sex": [[0]], "thal": [["normal"]], "target": [[0]] }}' -X POST http://localhost:8501/v1/models/model:predict
    

    注意:全部改为 [["normal"]] 或 [[0]]

    【讨论】:

      【解决方案3】:

      问题似乎与您发送的格式有关。您可以发布模型的签名吗? 由于声誉低,无法将其发布为评论。

      【讨论】:

      • 感谢您的帮助。我添加了模型的签名。
      猜你喜欢
      • 2021-04-25
      • 2019-04-21
      • 1970-01-01
      • 2019-01-09
      • 2021-01-25
      • 2019-05-14
      • 2020-03-02
      • 2020-04-10
      • 2019-08-30
      相关资源
      最近更新 更多