設定 Eval Saved Model

TensorFlow Model Analysis (TFMA) 可以將模型的評估圖匯出至名為 EvalSavedModel 的特殊 SavedModel。(請注意,使用的是評估圖,而非訓練或推論的圖。) EvalSavedModel 包含額外資訊,可讓 TFMA 以分散式方式針對大量資料和使用者定義的切片,計算模型中定義的相同評估指標。

修改現有模型

若要搭配 TFMA 使用現有模型,請先修改模型以匯出 EvalSavedModel。方法是新增對 tfma.export.export_eval_savedmodel 的呼叫,類似於 estimator.export_savedmodel。例如:

# Define, train and export your estimator as usual
estimator = tf.estimator.DNNClassifier(...)
estimator.train(...)
estimator.export_savedmodel(...)

# Also export the EvalSavedModel
tfma.export.export_eval_savedmodel(
  estimator=estimator, export_dir_base=export_dir,
  eval_input_receiver_fn=eval_input_receiver_fn)

eval_input_receiver_fn 必須定義,且類似於 estimator.export_savedmodelserving_input_receiver_fneval_input_receiver_fn 函式與 serving_input_receiver_fn 類似,會定義輸入預留位置範例、從範例剖析特徵,並傳回剖析的特徵。它會剖析並傳回標籤。

以下程式碼片段定義了 eval_input_receiver_fn 範例:

country = tf.feature_column.categorical_column_with_hash('country', 100)
language = tf.feature_column.categorical_column_with_hash('language', 100)
age = tf.feature_column.numeric_column('age')
label = tf.feature_column.numeric_column('label')

def eval_input_receiver_fn():
  serialized_tf_example = tf.compat.v1.placeholder(
      dtype=tf.string, shape=[None], name='input_example_placeholder')

  # This *must* be a dictionary containing a single key 'examples', which
  # points to the input placeholder.
  receiver_tensors = {'examples': serialized_tf_example}

  feature_spec =  tf.feature_column.make_parse_example_spec(
      [country, language, age, label])
  features = tf.io.parse_example(serialized_tf_example, feature_spec)

  return tfma.export.EvalInputReceiver(
    features=features,
    receiver_tensors=receiver_tensors,
    labels=features['label'])

在此範例中,您可以看到:

  • labels 也可以是字典。適用於多頭模型。
  • eval_input_receiver_fn 函式很可能與您的 serving_input_receiver_fn 函式相同。但在某些情況下,您可能想要定義其他特徵以進行切片。例如,您引入 age_category 特徵,將 age 特徵劃分為多個分組。然後您可以在 TFMA 中以此特徵進行切片,以協助瞭解模型的效能在不同年齡層類別中的差異。

新增匯出後指標

可以使用 add_metrics_callbacks 新增模型中未包含的其他指標。如需更多詳細資訊,請參閱 run_model_analysis 的 Python 說明。

端對端範例

試用功能齊全的端對端範例,其中採用 TensorFlow Transform 進行特徵預先處理、TensorFlow Estimators 進行訓練、TensorFlow Model Analysis 和 Jupyter 進行評估,以及 TensorFlow Serving 進行服務。

新增自訂匯出後指標

如果您想要在 TFMA 中新增自己的自訂匯出後指標,請查看此處的文件。