Path: blob/master/site/en-snapshot/lattice/tutorials/custom_estimators.ipynb
25118 views
Copyright 2020 The TensorFlow Authors.
TF Lattice Custom Estimators
Warning: Estimators are not recommended for new code. Estimators run
v1. Session
-style code which is more difficult to write correctly, and can behave unexpectedly, especially when combined with TF 2 code. Estimators do fall under our [compatibility guarantees] (https://tensorflow.org/guide/versions), but they will not receive any additional features, and there will be no fixes other than to security vulnerabilities. See the migration guide for details.
Overview
You can use custom estimators to create arbitrarily monotonic models using TFL layers. This guide outlines the steps needed to create such estimators.
Setup
Installing TF Lattice package:
Importing required packages:
Downloading the UCI Statlog (Heart) dataset:
Setting the default values used for training in this guide:
Feature Columns
As for any other TF estimator, data needs to be passed to the estimator, which is typically via an input_fn and parsed using FeatureColumns.
Note that categorical features do not need to be wrapped by a dense feature column, since tfl.laysers.CategoricalCalibration
layer can directly consume category indices.
Creating input_fn
As for any other estimator, you can use input_fn to feed data to the model for training and evaluation.
Creating model_fn
There are several ways to create a custom estimator. Here we will construct a model_fn
that calls a Keras model on the parsed input tensors. To parse the input features, you can use tf.feature_column.input_layer
, tf.keras.layers.DenseFeatures
, or tfl.estimators.transform_features
. If you use the latter, you will not need to wrap categorical features with dense feature columns, and the resulting tensors will not be concatenated, which makes it easier to use the features in the calibration layers.
To construct a model, you can mix and match TFL layers or any other Keras layers. Here we create a calibrated lattice Keras model out of TFL layers and impose several monotonicity constraints. We then use the Keras model to create the custom estimator.
Training and Estimator
Using the model_fn
we can create and train the estimator.