![]() |
Linear classifier model.
Inherits From: Estimator
tf.compat.v1.estimator.LinearClassifier(
feature_columns, model_dir=None, n_classes=2, weight_column=None,
label_vocabulary=None, optimizer='Ftrl', config=None, partitioner=None,
warm_start_from=None, loss_reduction=tf.compat.v1.losses.Reduction.SUM,
sparse_combiner='sum'
)
Train a linear model to classify instances into one of multiple possible classes. When number of possible classes is 2, this is binary classification.
Example:
categorical_column_a = categorical_column_with_hash_bucket(...)
categorical_column_b = categorical_column_with_hash_bucket(...)
categorical_feature_a_x_categorical_feature_b = crossed_column(...)
# Estimator using the default optimizer.
estimator = tf.estimator.LinearClassifier(
feature_columns=[categorical_column_a,
categorical_feature_a_x_categorical_feature_b])
# Or estimator using the FTRL optimizer with regularization.
estimator = tf.estimator.LinearClassifier(
feature_columns=[categorical_column_a,
categorical_feature_a_x_categorical_feature_b],
optimizer=tf.keras.optimizers.Ftrl(
learning_rate=0.1,
l1_regularization_strength=0.001
))
# Or estimator using an optimizer with a learning rate decay.
estimator = tf.estimator.LinearClassifier(
feature_columns=[categorical_column_a,
categorical_feature_a_x_categorical_feature_b],
optimizer=lambda: tf.keras.optimizers.Ftrl(
learning_rate=tf.exponential_decay(
learning_rate=0.1,
global_step=tf.get_global_step(),
decay_steps=10000,
decay_rate=0.96))
# Or estimator with warm-starting from a previous checkpoint.
estimator = tf.estimator.LinearClassifier(
feature_columns=[categorical_column_a,
categorical_feature_a_x_categorical_feature_b],
warm_start_from="/path/to/checkpoint/dir")
# Input builders
def input_fn_train:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_eval:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_predict:
# Returns tf.data.Dataset of (x, None) tuple.
pass
estimator.train(input_fn=input_fn_train)
metrics = estimator.evaluate(input_fn=input_fn_eval)
predictions = estimator.predict(input_fn=input_fn_predict)
Input of train
and evaluate
should have following features,
otherwise there will be a KeyError
:
- if
weight_column
is notNone
, a feature withkey=weight_column
whose value is aTensor
. - for each
column
infeature_columns
:- if
column
is aSparseColumn
, a feature withkey=column.name
whosevalue
is aSparseTensor
. - if
column
is aWeightedSparseColumn
, two features: the first withkey
the id column name, the second withkey
the weight column name. Both features'value
must be aSparseTensor
. - if
column
is aRealValuedColumn
, a feature withkey=column.name
whosevalue
is aTensor
.
- if
Loss is calculated by using softmax cross entropy.
Args | |
---|---|
model_fn
|
Model function. Follows the signature:
|
model_dir
|
Directory to save model parameters, graph and etc. This can
also be used to load checkpoints from the directory into an estimator to
continue training a previously saved model. If PathLike object, the
path will be resolved. If None , the model_dir in config will be used
if set. If both are set, they must be same. If both are None , a
temporary directory will be used.
|
config
|
estimator.RunConfig configuration object.
|
params
|
dict of hyper parameters that will be passed into model_fn .
Keys are names of parameters, values are basic python types.
|
warm_start_from
|
Optional string filepath to a checkpoint or SavedModel to
warm-start from, or a tf.estimator.WarmStartSettings object to fully
configure warm-starting. If None, only TRAINABLE variables are
warm-started. If the string filepath is provided instead of a
tf.estimator.WarmStartSettings , then all variables are warm-started,
and it is assumed that vocabularies and tf.Tensor names are unchanged.
|
Raises | |
---|---|
ValueError
|
parameters of model_fn don't match params .
|
ValueError
|
if this is called via a subclass and if that class overrides
a member of Estimator .
|
Eager Compatibility
Estimators can be used while eager execution is enabled. Note that input_fn
and all hooks are executed inside a graph context, so they have to be written
to be compatible with graph mode. Note that input_fn
code using tf.data
generally works in both graph and eager modes.
Attributes | |
---|---|
config
|
|
model_dir
|
|
model_fn
|
Returns the model_fn which is bound to self.params .
|
params
|
Methods
eval_dir
eval_dir(
name=None
)
Shows the directory name where evaluation metrics are dumped.
Args | |
---|---|
name
|
Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
Returns | |
---|---|
A string which is the path of directory contains evaluation metrics. |
evaluate
evaluate(
input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
Evaluates the model given evaluation data input_fn
.
For each step, calls input_fn
, which returns one batch of data.
Evaluates until:
steps
batches are processed, orinput_fn
raises an end-of-input exception (tf.errors.OutOfRangeError
orStopIteration
).
Args | |
---|---|
input_fn
|
A function that constructs the input data for evaluation. See
Premade Estimators
for more information. The function should construct and return one of
the following:
|
steps
|
Number of steps for which to evaluate model. If None , evaluates
until input_fn raises an end-of-input exception.
|
hooks
|
List of tf.train.SessionRunHook subclass instances. Used for
callbacks inside the evaluation call.
|
checkpoint_path
|
Path of a specific checkpoint to evaluate. If None , the
latest checkpoint in model_dir is used. If there are no checkpoints
in model_dir , evaluation is run with newly initialized Variables
instead of ones restored from checkpoint.
|
name
|
Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
Returns | |
---|---|
A dict containing the evaluation metrics specified in model_fn keyed by
name, as well as an entry global_step which contains the value of the
global step for which this evaluation was performed. For canned
estimators, the dict contains the loss (mean loss per mini-batch) and
the average_loss (mean loss per sample). Canned classifiers also return
the accuracy . Canned regressors also return the label/mean and the
prediction/mean .
|
Raises | |
---|---|
ValueError
|
If steps <= 0 .
|
experimental_export_all_saved_models
experimental_export_all_saved_models(
export_dir_base, input_receiver_fn_map, assets_extra=None, as_text=False,
checkpoint_path=None
)
Exports a SavedModel
with tf.MetaGraphDefs
for each requested mode.
For each mode passed in via the input_receiver_fn_map
,
this method builds a new graph by calling the input_receiver_fn
to obtain
feature and label Tensor
s. Next, this method calls the Estimator
's
model_fn
in the passed mode to generate the model graph based on
those features and labels, and restores the given checkpoint
(or, lacking that, the most recent checkpoint) into the graph.
Only one of the modes is used for saving variables to the SavedModel
(order of preference: tf.estimator.ModeKeys.TRAIN
,
tf.estimator.ModeKeys.EVAL
, then
tf.estimator.ModeKeys.PREDICT
), such that up to three
tf.MetaGraphDefs
are saved with a single set of variables in a single
SavedModel
directory.
For the variables and tf.MetaGraphDefs
, a timestamped export directory
below export_dir_base
, and writes a SavedModel
into it containing the
tf.MetaGraphDef
for the given mode and its associated signatures.
For prediction, the exported MetaGraphDef
will provide one SignatureDef
for each element of the export_outputs
dict returned from the model_fn