tf.einsum       View source on GitHub    Tensor contraction over specified indices and outer product.  View aliases  Main aliases
tf.linalg.einsum Compat aliases for migration See Migration guide for more details. tf.compat.v1.einsum, tf.compat.v1.linalg.einsum
tf.einsum(
    equation, *inputs, **kwargs
)
 Einsum allows defining Tensors by defining their element-wise computation. This computation is defined by equation, a shorthand form based on Einstein summation. As an example, consider multiplying two matrices A and B to form a matrix C. The elements of C are given by:  $$ C_{i,k} = \sum_j A_{i,j} B_{j,k} $$  or C[i,k] = sum_j A[i,j] * B[j,k]
 The corresponding einsum equation is: ij,jk->ik
 In general, to convert the element-wise equation into the equation string, use the following procedure (intermediate strings for matrix multiplication example provided in parentheses):  remove variable names, brackets, and commas, (ik = sum_j ij * jk) replace "*" with ",", (ik = sum_j ij , jk) drop summation signs, and (ik = ij, jk) move the output to the right, while replacing "=" with "->". (ij,jk->ik)
Note: If the output indices are not specified repeated indices are summed. So ij,jk->ik can be simplified to ij,jk.
 Many common operations can be expressed in this way. For example: Matrix multiplication
m0 = tf.random.normal(shape=[2, 3])
m1 = tf.random.normal(shape=[3, 5])
e = tf.einsum('ij,jk->ik', m0, m1)
# output[i,k] = sum_j m0[i,j] * m1[j, k]
print(e.shape)
(2, 5)
 Repeated indices are summed if the output indices are not specified.
e = tf.einsum('ij,jk', m0, m1)  # output[i,k] = sum_j m0[i,j] * m1[j, k]
print(e.shape)
(2, 5)
 Dot product
u = tf.random.normal(shape=[5])
v = tf.random.normal(shape=[5])
e = tf.einsum('i,i->', u, v)  # output = sum_i u[i]*v[i]
print(e.shape)
()
 Outer product
u = tf.random.normal(shape=[3])
v = tf.random.normal(shape=[5])
e = tf.einsum('i,j->ij', u, v)  # output[i,j] = u[i]*v[j]
print(e.shape)
(3, 5)
 Transpose
m = tf.ones(2,3)
e = tf.einsum('ij->ji', m0)  # output[j,i] = m0[i,j]
print(e.shape)
(3, 2)
 Diag
m = tf.reshape(tf.range(9), [3,3])
diag = tf.einsum('ii->i', m)
print(diag.shape)
(3,)
 Trace
# Repeated indices are summed.
trace = tf.einsum('ii', m)  # output[j,i] = trace(m) = sum_i m[i, i]
assert trace == sum(diag)
print(trace.shape)
()
 Batch matrix multiplication
s = tf.random.normal(shape=[7,5,3])
t = tf.random.normal(shape=[7,3,2])
e = tf.einsum('bij,bjk->bik', s, t)
# output[a,i,k] = sum_j s[a,i,j] * t[a, j, k]
print(e.shape)
(7, 5, 2)
 This method does not support broadcasting on named-axes. All axes with matching labels should have the same length. If you have length-1 axes, use tf.squeseze or tf.reshape to eliminate them. To write code that is agnostic to the number of indices in the input use an ellipsis. The ellipsis is a placeholder for "whatever other indices fit here". For example, to perform a NumPy-style broadcasting-batch-matrix multiplication where the matrix multiply acts on the last two axes of the input, use:
s = tf.random.normal(shape=[11, 7, 5, 3])
t = tf.random.normal(shape=[11, 7, 3, 2])
e =  tf.einsum('...ij,...jk->...ik', s, t)
print(e.shape)
(11, 7, 5, 2)
 Einsum will broadcast over axes covered by the ellipsis.
s = tf.random.normal(shape=[11, 1, 5, 3])
t = tf.random.normal(shape=[1, 7, 3, 2])
e =  tf.einsum('...ij,...jk->...ik', s, t)
print(e.shape)
(11, 7, 5, 2)

 Args
  equation   a str describing the contraction, in the same format as numpy.einsum.
  *inputs   the inputs to contract (each one a Tensor), whose shapes should be consistent with equation.
  **kwargs    optimize: Optimization strategy to use to find contraction path using opt_einsum. Must be 'greedy', 'optimal', 'branch-2', 'branch-all' or 'auto'. (optional, default: 'greedy'). name: A name for the operation (optional).

 Returns   The contracted Tensor, with shape determined by equation.

 Raises
  ValueError   If  the format of equation is incorrect, number of inputs or their shapes are inconsistent with equation.


tf.ensure_shape     View source on GitHub    Updates the shape of a tensor and checks at runtime that the shape holds.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.ensure_shape
tf.ensure_shape(
    x, shape, name=None
)
 For example:
@tf.function(input_signature=[tf.TensorSpec(shape=None, dtype=tf.float32)])
def f(tensor):
  return tf.ensure_shape(tensor, [3, 3])

f(tf.zeros([3, 3])) # Passes
<tf.Tensor: shape=(3, 3), dtype=float32, numpy=
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]], dtype=float32)>
f([1, 2, 3]) # fails
Traceback (most recent call last):

InvalidArgumentError:  Shape of tensor x [3] is not compatible with expected shape [3,3].
 The above example raises tf.errors.InvalidArgumentError, because the shape (3,) is not compatible with the shape (None, 3, 3) With eager execution this is a shape assertion, that returns the input:
x = tf.constant([1,2,3])
print(x.shape)
(3,)
x = tf.ensure_shape(x, [3])
x = tf.ensure_shape(x, [5])
Traceback (most recent call last):

tf.errors.InvalidArgumentError: Shape of tensor dummy_input [3] is not
  compatible with expected shape [5]. [Op:EnsureShape]
 Inside a tf.function or v1.Graph context it checks both the buildtime and runtime shapes. This is stricter than tf.Tensor.set_shape which only checks the buildtime shape.
Note: This differs from tf.Tensor.set_shape in that it sets the static shape of the resulting tensor and enforces it at runtime, raising an error if the tensor's runtime shape is incompatible with the specified shape. tf.Tensor.set_shape sets the static shape of the tensor without enforcing it at runtime, which may result in inconsistencies between the statically-known shape of tensors and the runtime value of tensors.
 For example, of loading images of a known size:
@tf.function
def decode_image(png):
  image = tf.image.decode_png(png, channels=3)
  # the `print` executes during tracing.
  print("Initial shape: ", image.shape)
  image = tf.ensure_shape(image,[28, 28, 3])
  print("Final shape: ", image.shape)
  return image
 When tracing a function, no ops are being executed, shapes may be unknown. See the Concrete Functions Guide for details.
concrete_decode = decode_image.get_concrete_function(
    tf.TensorSpec([], dtype=tf.string))
Initial shape:  (None, None, 3)
Final shape:  (28, 28, 3)

image = tf.random.uniform(maxval=255, shape=[28, 28, 3], dtype=tf.int32)
image = tf.cast(image,tf.uint8)
png = tf.image.encode_png(image)
image2 = concrete_decode(png)
print(image2.shape)
(28, 28, 3)

image = tf.concat([image,image], axis=0)
print(image.shape)
(56, 28, 3)
png = tf.image.encode_png(image)
image2 = concrete_decode(png)
Traceback (most recent call last):

tf.errors.InvalidArgumentError:  Shape of tensor DecodePng [56,28,3] is not
  compatible with expected shape [28,28,3].
 Caution: if you don't use the result of tf.ensure_shape the check may not run.
@tf.function
def bad_decode_image(png):
  image = tf.image.decode_png(png, channels=3)
  # the `print` executes during tracing.
  print("Initial shape: ", image.shape)
  # BAD: forgot to use the returned tensor.
  tf.ensure_shape(image,[28, 28, 3])
  print("Final shape: ", image.shape)
  return image

image = bad_decode_image(png)
Initial shape:  (None, None, 3)
Final shape:  (None, None, 3)
print(image.shape)
(56, 28, 3)

 Args
  x   A Tensor.
  shape   A TensorShape representing the shape of this tensor, a TensorShapeProto, a list, a tuple, or None.
  name   A name for this operation (optional). Defaults to "EnsureShape".

 Returns   A Tensor. Has the same type and contents as x.

 Raises
  tf.errors.InvalidArgumentError   If shape is incompatible with the shape of x.


Module: tf.errors Exception types for TensorFlow errors. Classes class AbortedError: The operation was aborted, typically due to a concurrent action. class AlreadyExistsError: Raised when an entity that we attempted to create already exists. class CancelledError: Raised when an operation or step is cancelled. class DataLossError: Raised when unrecoverable data loss or corruption is encountered. class DeadlineExceededError: Raised when a deadline expires before an operation could complete. class FailedPreconditionError: Operation was rejected because the system is not in a state to execute it. class InternalError: Raised when the system experiences an internal error. class InvalidArgumentError: Raised when an operation receives an invalid argument. class NotFoundError: Raised when a requested entity (e.g., a file or directory) was not found. class OpError: A generic error that is raised when TensorFlow execution fails. class OperatorNotAllowedInGraphError: An error is raised for unsupported operator in Graph execution. class OutOfRangeError: Raised when an operation iterates past the valid input range. class PermissionDeniedError: Raised when the caller does not have permission to run an operation. class ResourceExhaustedError: Some resource has been exhausted. class UnauthenticatedError: The request does not have valid authentication credentials. class UnavailableError: Raised when the runtime is currently unavailable. class UnimplementedError: Raised when an operation has not been implemented. class UnknownError: Unknown error.

 Other Members
  ABORTED   10
  ALREADY_EXISTS   6
  CANCELLED   1
  DATA_LOSS   15
  DEADLINE_EXCEEDED   4
  FAILED_PRECONDITION   9
  INTERNAL   13
  INVALID_ARGUMENT   3
  NOT_FOUND   5
  OK   0
  OUT_OF_RANGE   11
  PERMISSION_DENIED   7
  RESOURCE_EXHAUSTED   8
  UNAUTHENTICATED   16
  UNAVAILABLE   14
  UNIMPLEMENTED   12
  UNKNOWN   2


tf.errors.AbortedError     View source on GitHub    The operation was aborted, typically due to a concurrent action. Inherits From: OpError  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.errors.AbortedError
tf.errors.AbortedError(
    node_def, op, message
)
 For example, running a tf.QueueBase.enqueue operation may raise AbortedError if a tf.QueueBase.close operation previously ran.

 Attributes
  error_code   The integer error code that describes the error.
  message   The error message that describes the error.
  node_def   The NodeDef proto representing the op that failed.
  op   The operation that failed, if known.
Note: If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no corresponding tf.Operation object. In that case, this will return None, and you should instead use the tf.errors.OpError.node_def to discover information about the op.


tf.errors.AlreadyExistsError     View source on GitHub    Raised when an entity that we attempted to create already exists. Inherits From: OpError  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.errors.AlreadyExistsError
tf.errors.AlreadyExistsError(
    node_def, op, message
)
 For example, running an operation that saves a file (e.g. tf.train.Saver.save) could potentially raise this exception if an explicit filename for an existing file was passed.

 Attributes
  error_code   The integer error code that describes the error.
  message   The error message that describes the error.
  node_def   The NodeDef proto representing the op that failed.
  op   The operation that failed, if known.
Note: If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no corresponding tf.Operation object. In that case, this will return None, and you should instead use the tf.errors.OpError.node_def to discover information about the op.


tf.errors.CancelledError     View source on GitHub    Raised when an operation or step is cancelled. Inherits From: OpError  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.errors.CancelledError
tf.errors.CancelledError(
    node_def, op, message
)
 For example, a long-running operation (e.g. tf.QueueBase.enqueue may be cancelled by running another operation (e.g. tf.QueueBase.close, or by tf.Session.close. A step that is running such a long-running operation will fail by raising CancelledError.

 Attributes
  error_code   The integer error code that describes the error.
  message   The error message that describes the error.
  node_def   The NodeDef proto representing the op that failed.
  op   The operation that failed, if known.
Note: If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no corresponding tf.Operation object. In that case, this will return None, and you should instead use the tf.errors.OpError.node_def to discover information about the op.


tf.errors.DataLossError     View source on GitHub    Raised when unrecoverable data loss or corruption is encountered. Inherits From: OpError  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.errors.DataLossError
tf.errors.DataLossError(
    node_def, op, message
)
 For example, this may be raised by running a tf.WholeFileReader.read operation, if the file is truncated while it is being read.

 Attributes
  error_code   The integer error code that describes the error.
  message   The error message that describes the error.
  node_def   The NodeDef proto representing the op that failed.
  op   The operation that failed, if known.
Note: If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no corresponding tf.Operation object. In that case, this will return None, and you should instead use the tf.errors.OpError.node_def to discover information about the op.


tf.errors.DeadlineExceededError     View source on GitHub    Raised when a deadline expires before an operation could complete. Inherits From: OpError  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.errors.DeadlineExceededError
tf.errors.DeadlineExceededError(
    node_def, op, message
)
 This exception is not currently used.

 Attributes
  error_code   The integer error code that describes the error.
  message   The error message that describes the error.
  node_def   The NodeDef proto representing the op that failed.
  op   The operation that failed, if known.
Note: If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no corresponding tf.Operation object. In that case, this will return None, and you should instead use the tf.errors.OpError.node_def to discover information about the op.


tf.errors.FailedPreconditionError     View source on GitHub    Operation was rejected because the system is not in a state to execute it. Inherits From: OpError  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.errors.FailedPreconditionError
tf.errors.FailedPreconditionError(
    node_def, op, message
)
 This exception is most commonly raised when running an operation that reads a tf.Variable before it has been initialized.

 Attributes
  error_code   The integer error code that describes the error.
  message   The error message that describes the error.
  node_def   The NodeDef proto representing the op that failed.
  op   The operation that failed, if known.
Note: If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no corresponding tf.Operation object. In that case, this will return None, and you should instead use the tf.errors.OpError.node_def to discover information about the op.


tf.errors.InternalError     View source on GitHub    Raised when the system experiences an internal error. Inherits From: OpError  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.errors.InternalError
tf.errors.InternalError(
    node_def, op, message
)
 This exception is raised when some invariant expected by the runtime has been broken. Catching this exception is not recommended.

 Attributes
  error_code   The integer error code that describes the error.
  message   The error message that describes the error.
  node_def   The NodeDef proto representing the op that failed.
  op   The operation that failed, if known.
Note: If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no corresponding tf.Operation object. In that case, this will return None, and you should instead use the tf.errors.OpError.node_def to discover information about the op.


tf.errors.InvalidArgumentError     View source on GitHub    Raised when an operation receives an invalid argument. Inherits From: OpError  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.errors.InvalidArgumentError
tf.errors.InvalidArgumentError(
    node_def, op, message
)
 This may occur, for example, if an operation receives an input tensor that has an invalid value or shape. For example, the tf.matmul op will raise this error if it receives an input that is not a matrix, and the tf.reshape op will raise this error if the new shape does not match the number of elements in the input tensor.

 Attributes
  error_code   The integer error code that describes the error.
  message   The error message that describes the error.
  node_def   The NodeDef proto representing the op that failed.
  op   The operation that failed, if known.
Note: If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no corresponding tf.Operation object. In that case, this will return None, and you should instead use the tf.errors.OpError.node_def to discover information about the op.


tf.errors.NotFoundError     View source on GitHub    Raised when a requested entity (e.g., a file or directory) was not found. Inherits From: OpError  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.errors.NotFoundError
tf.errors.NotFoundError(
    node_def, op, message
)
 For example, running the tf.WholeFileReader.read operation could raise NotFoundError if it receives the name of a file that does not exist.

 Attributes
  error_code   The integer error code that describes the error.
  message   The error message that describes the error.
  node_def   The NodeDef proto representing the op that failed.
  op   The operation that failed, if known.
Note: If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no corresponding tf.Operation object. In that case, this will return None, and you should instead use the tf.errors.OpError.node_def to discover information about the op.


tf.errors.OperatorNotAllowedInGraphError An error is raised for unsupported operator in Graph execution.
tf.errors.OperatorNotAllowedInGraphError(
    *args, **kwargs
)
 For example, using a tf.Tensor as a Python bool in Graph execution is not allowed.


tf.errors.OpError     View source on GitHub    A generic error that is raised when TensorFlow execution fails.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.OpError, tf.compat.v1.errors.OpError
tf.errors.OpError(
    node_def, op, message, error_code
)
 Whenever possible, the session will raise a more specific subclass of OpError from the tf.errors module.

 Args
  node_def   The node_def_pb2.NodeDef proto representing the op that failed, if known; otherwise None.
  op   The ops.Operation that failed, if known; otherwise None.
  message   The message string describing the failure.
  error_code   The error_codes_pb2.Code describing the error.

 Attributes
  error_code   The integer error code that describes the error.
  message   The error message that describes the error.
  node_def   The NodeDef proto representing the op that failed.
  op   The operation that failed, if known.
Note: If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no corresponding tf.Operation object. In that case, this will return None, and you should instead use the tf.errors.OpError.node_def to discover information about the op.


tf.errors.OutOfRangeError     View source on GitHub    Raised when an operation iterates past the valid input range. Inherits From: OpError  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.errors.OutOfRangeError
tf.errors.OutOfRangeError(
    node_def, op, message
)
 This exception is raised in "end-of-file" conditions, such as when a tf.QueueBase.dequeue operation is blocked on an empty queue, and a tf.QueueBase.close operation executes.

 Attributes
  error_code   The integer error code that describes the error.
  message   The error message that describes the error.
  node_def   The NodeDef proto representing the op that failed.
  op   The operation that failed, if known.
Note: If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no corresponding tf.Operation object. In that case, this will return None, and you should instead use the tf.errors.OpError.node_def to discover information about the op.


tf.errors.PermissionDeniedError     View source on GitHub    Raised when the caller does not have permission to run an operation. Inherits From: OpError  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.errors.PermissionDeniedError
tf.errors.PermissionDeniedError(
    node_def, op, message
)
 For example, running the tf.WholeFileReader.read operation could raise PermissionDeniedError if it receives the name of a file for which the user does not have the read file permission.

 Attributes
  error_code   The integer error code that describes the error.
  message   The error message that describes the error.
  node_def   The NodeDef proto representing the op that failed.
  op   The operation that failed, if known.
Note: If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no corresponding tf.Operation object. In that case, this will return None, and you should instead use the tf.errors.OpError.node_def to discover information about the op.


tf.errors.ResourceExhaustedError     View source on GitHub    Some resource has been exhausted. Inherits From: OpError  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.errors.ResourceExhaustedError
tf.errors.ResourceExhaustedError(
    node_def, op, message
)
 For example, this error might be raised if a per-user quota is exhausted, or perhaps the entire file system is out of space.

 Attributes
  error_code   The integer error code that describes the error.
  message   The error message that describes the error.
  node_def   The NodeDef proto representing the op that failed.
  op   The operation that failed, if known.
Note: If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no corresponding tf.Operation object. In that case, this will return None, and you should instead use the tf.errors.OpError.node_def to discover information about the op.


tf.errors.UnauthenticatedError     View source on GitHub    The request does not have valid authentication credentials. Inherits From: OpError  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.errors.UnauthenticatedError
tf.errors.UnauthenticatedError(
    node_def, op, message
)
 This exception is not currently used.

 Attributes
  error_code   The integer error code that describes the error.
  message   The error message that describes the error.
  node_def   The NodeDef proto representing the op that failed.
  op   The operation that failed, if known.
Note: If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no corresponding tf.Operation object. In that case, this will return None, and you should instead use the tf.errors.OpError.node_def to discover information about the op.


tf.errors.UnavailableError     View source on GitHub    Raised when the runtime is currently unavailable. Inherits From: OpError  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.errors.UnavailableError
tf.errors.UnavailableError(
    node_def, op, message
)
 This exception is not currently used.

 Attributes
  error_code   The integer error code that describes the error.
  message   The error message that describes the error.
  node_def   The NodeDef proto representing the op that failed.
  op   The operation that failed, if known.
Note: If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no corresponding tf.Operation object. In that case, this will return None, and you should instead use the tf.errors.OpError.node_def to discover information about the op.


tf.errors.UnimplementedError     View source on GitHub    Raised when an operation has not been implemented. Inherits From: OpError  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.errors.UnimplementedError
tf.errors.UnimplementedError(
    node_def, op, message
)
 Some operations may raise this error when passed otherwise-valid arguments that it does not currently support. For example, running the tf.nn.max_pool2d operation would raise this error if pooling was requested on the batch dimension, because this is not yet supported.

 Attributes
  error_code   The integer error code that describes the error.
  message   The error message that describes the error.
  node_def   The NodeDef proto representing the op that failed.
  op   The operation that failed, if known.
Note: If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no corresponding tf.Operation object. In that case, this will return None, and you should instead use the tf.errors.OpError.node_def to discover information about the op.


tf.errors.UnknownError     View source on GitHub    Unknown error. Inherits From: OpError  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.errors.UnknownError
tf.errors.UnknownError(
    node_def, op, message, error_code=UNKNOWN
)
 An example of where this error may be returned is if a Status value received from another address space belongs to an error-space that is not known to this address space. Also, errors raised by APIs that do not return enough error information may be converted to this error.

 Attributes
  error_code   The integer error code that describes the error.
  message   The error message that describes the error.
  node_def   The NodeDef proto representing the op that failed.
  op   The operation that failed, if known.
Note: If the failed op was synthesized at runtime, e.g. a Send or Recv op, there will be no corresponding tf.Operation object. In that case, this will return None, and you should instead use the tf.errors.OpError.node_def to discover information about the op.


Module: tf.estimator Estimator: High level tools for working with models. Modules experimental module: Public API for tf.estimator.experimental namespace. export module: All public utility methods for exporting Estimator to SavedModel. Classes class BaselineClassifier: A classifier that can establish a simple baseline. class BaselineEstimator: An estimator that can establish a simple baseline. class BaselineRegressor: A regressor that can establish a simple baseline. class BestExporter: This class exports the serving graph and checkpoints of the best models. class BinaryClassHead: Creates a Head for single label binary classification. class BoostedTreesClassifier: A Classifier for Tensorflow Boosted Trees models. class BoostedTreesEstimator: An Estimator for Tensorflow Boosted Trees models. class BoostedTreesRegressor: A Regressor for Tensorflow Boosted Trees models. class CheckpointSaverHook: Saves checkpoints every N steps or seconds. class CheckpointSaverListener: Interface for listeners that take action before or after checkpoint save. class DNNClassifier: A classifier for TensorFlow DNN models. class DNNEstimator: An estimator for TensorFlow DNN models with user-specified head. class DNNLinearCombinedClassifier: An estimator for TensorFlow Linear and DNN joined classification models. class DNNLinearCombinedEstimator: An estimator for TensorFlow Linear and DNN joined models with custom head. class DNNLinearCombinedRegressor: An estimator for TensorFlow Linear and DNN joined models for regression. class DNNRegressor: A regressor for TensorFlow DNN models. class Estimator: Estimator class to train and evaluate TensorFlow models. class EstimatorSpec: Ops and objects returned from a model_fn and passed to an Estimator. class EvalSpec: Configuration for the "eval" part for the train_and_evaluate call. class Exporter: A class representing a type of model export. class FeedFnHook: Runs feed_fn and sets the feed_dict accordingly. class FinalExporter: This class exports the serving graph and checkpoints at the end. class FinalOpsHook: A hook which evaluates Tensors at the end of a session. class GlobalStepWaiterHook: Delays execution until global step reaches wait_until_step. class Head: Interface for the head/top of a model. class LatestExporter: This class regularly exports the serving graph and checkpoints. class LinearClassifier: Linear classifier model. class LinearEstimator: An estimator for TensorFlow linear models with user-specified head. class LinearRegressor: An estimator for TensorFlow Linear regression problems. class LoggingTensorHook: Prints the given tensors every N local steps, every N seconds, or at end. class LogisticRegressionHead: Creates a Head for logistic regression. class ModeKeys: Standard names for Estimator model modes. class MultiClassHead: Creates a Head for multi class classification. class MultiHead: Creates a Head for multi-objective learning. class MultiLabelHead: Creates a Head for multi-label classification. class NanLossDuringTrainingError: Unspecified run-time error. class NanTensorHook: Monitors the loss tensor and stops training if loss is NaN. class PoissonRegressionHead: Creates a Head for poisson regression using tf.nn.log_poisson_loss. class ProfilerHook: Captures CPU/GPU profiling information every N steps or seconds. class RegressionHead: Creates a Head for regression using the mean_squared_error loss. class RunConfig: This class specifies the configurations for an Estimator run. class SecondOrStepTimer: Timer that triggers at most once every N seconds or once every N steps. class SessionRunArgs: Represents arguments to be added to a Session.run() call. class SessionRunContext: Provides information about the session.run() call being made. class SessionRunHook: Hook to extend calls to MonitoredSession.run(). class SessionRunValues: Contains the results of Session.run(). class StepCounterHook: Hook that counts steps per second. class StopAtStepHook: Hook that requests stop at a specified step. class SummarySaverHook: Saves summaries every N steps. class TrainSpec: Configuration for the "train" part for the train_and_evaluate call. class VocabInfo: Vocabulary information for warm-starting. class WarmStartSettings: Settings for warm-starting in tf.estimator.Estimators. Functions add_metrics(...): Creates a new tf.estimator.Estimator which has given metrics. classifier_parse_example_spec(...): Generates parsing spec for tf.parse_example to be used with classifiers. regressor_parse_example_spec(...): Generates parsing spec for tf.parse_example to be used with regressors. train_and_evaluate(...): Train and evaluate the estimator.


tf.estimator.add_metrics     View source on GitHub    Creates a new tf.estimator.Estimator which has given metrics.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.add_metrics
tf.estimator.add_metrics(
    estimator, metric_fn
)
 Example: def my_auc(labels, predictions):
  auc_metric = tf.keras.metrics.AUC(name="my_auc")
  auc_metric.update_state(y_true=labels, y_pred=predictions['logistic'])
  return {'auc': auc_metric}

estimator = tf.estimator.DNNClassifier(...)
estimator = tf.estimator.add_metrics(estimator, my_auc)
estimator.train(...)
estimator.evaluate(...)
 Example usage of custom metric which uses features: def my_auc(labels, predictions, features):
  auc_metric = tf.keras.metrics.AUC(name="my_auc")
  auc_metric.update_state(y_true=labels, y_pred=predictions['logistic'],
                          sample_weight=features['weight'])
  return {'auc': auc_metric}

estimator = tf.estimator.DNNClassifier(...)
estimator = tf.estimator.add_metrics(estimator, my_auc)
estimator.train(...)
estimator.evaluate(...)

 Args
  estimator   A tf.estimator.Estimator object.
  metric_fn   A function which should obey the following signature:  Args: can only have following four arguments in any order: predictions: Predictions Tensor or dict of Tensor created by given estimator. features: Input dict of Tensor objects created by input_fn which is given to estimator.evaluate as an argument. labels: Labels Tensor or dict of Tensor created by input_fn which is given to estimator.evaluate as an argument. config: config attribute of the estimator. Returns: Dict of metric results keyed by name. Final metrics are a union of this and estimator's existing metrics. If there is a name conflict between this and estimators existing metrics, this will override the existing one. The values of the dict are the results of calling a metric function, namely a (metric_tensor, update_op) tuple.

 Returns   A new tf.estimator.Estimator which has a union of original metrics with given ones.


tf.estimator.BaselineClassifier     View source on GitHub    A classifier that can establish a simple baseline. Inherits From: Estimator, Estimator
tf.estimator.BaselineClassifier(
    model_dir=None, n_classes=2, weight_column=None, label_vocabulary=None,
    optimizer='Ftrl', config=None,
    loss_reduction=losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE
)
 This classifier ignores feature values and will learn to predict the average value of each label. For single-label problems, this will predict the probability distribution of the classes as seen in the labels. For multi-label problems, this will predict the fraction of examples that are positive for each class. Example:
# Build BaselineClassifier
classifier = tf.estimator.BaselineClassifier(n_classes=3)

# 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

# Fit model.
classifier.train(input_fn=input_fn_train)

# Evaluate cross entropy between the test and train labels.
loss = classifier.evaluate(input_fn=input_fn_eval)["loss"]

# predict outputs the probability distribution of the classes as seen in
# training.
predictions = classifier.predict(new_samples)

 Input of train and evaluate should have following features, otherwise there will be a KeyError:  if weight_column is not None, a feature with key=weight_column whose value is a Tensor.

 Args
  model_dir   Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model.
  n_classes   number of label classes. Default is binary classification. It must be greater than 1. Note: Class labels are integers representing the class index (i.e. values from 0 to n_classes-1). For arbitrary label values (e.g. string labels), convert to class indices first.
  weight_column   A string or a NumericColumn created by tf.feature_column.numeric_column defining feature column representing weights. It will be multiplied by the loss of the example.
  label_vocabulary   Optional list of strings with size [n_classes] defining the label vocabulary. Only supported for n_classes > 2.
  optimizer   String, tf.keras.optimizers.* object, or callable that creates the optimizer to use for training. If not specified, will use Ftrl as the default optimizer.
  config   RunConfig object to configure the runtime settings.
  loss_reduction   One of tf.losses.Reduction except NONE. Describes how to reduce training loss over batch. Defaults to SUM_OVER_BATCH_SIZE.

 Raises
  ValueError   If n_classes < 2.    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

  export_savedmodel

  model_dir

  model_fn   Returns the model_fn which is bound to self.params.
  params
   Methods eval_dir View source
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 View source
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, or
input_fn raises an end-of-input exception (tf.errors.OutOfRangeError or StopIteration).

 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:  A tf.data.Dataset object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a tf.Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs.

  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 View source
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 Tensors. 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, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn. For training and evaluation, the train_op is stored in an extra collection, and loss, metrics, and predictions are included in a SignatureDef for the mode in question. Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.

 Args
  export_dir_base   A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
  input_receiver_fn_map   dict of tf.estimator.ModeKeys to input_receiver_fn mappings, where the input_receiver_fn is a function that takes no arguments and returns the appropriate subclass of InputReceiver.
  assets_extra   A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
  as_text   whether to write the SavedModel proto in text format.
  checkpoint_path   The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.

 Returns   The path to the exported directory as a bytes object.

 Raises
  ValueError   if any input_receiver_fn is None, no export_outputs are provided, or no checkpoint can be found.    export_saved_model View source
export_saved_model(
    export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False,
    checkpoint_path=None, experimental_mode=ModeKeys.PREDICT
)
 Exports inference graph as a SavedModel into the given dir. For a detailed guide, see SavedModel from Estimators. This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session. The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn. Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}. The experimental_mode parameter can be used to export a single train/eval/predict graph as a SavedModel. See experimental_export_all_saved_models for full docs.

 Args
  export_dir_base   A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
  serving_input_receiver_fn   A function that takes no argument and returns a tf.estimator.export.ServingInputReceiver or tf.estimator.export.TensorServingInputReceiver.
  assets_extra   A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
  as_text   whether to write the SavedModel proto in text format.
  checkpoint_path   The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.
  experimental_mode   tf.estimator.ModeKeys value indicating with mode will be exported. Note that this feature is experimental.

 Returns   The path to the exported directory as a bytes object.

 Raises
  ValueError   if no serving_input_receiver_fn is provided, no export_outputs are provided, or no checkpoint can be found.    get_variable_names View source
get_variable_names()
 Returns list of all variable names in this model.

 Returns   List of names.

 Raises
  ValueError   If the Estimator has not produced a checkpoint yet.    get_variable_value View source
get_variable_value(
    name
)
 Returns value of the variable given by name.

 Args
  name   string or a list of string, name of the tensor.

 Returns   Numpy array - value of the tensor.

 Raises
  ValueError   If the Estimator has not produced a checkpoint yet.    latest_checkpoint View source
latest_checkpoint()
 Finds the filename of the latest saved checkpoint file in model_dir.

 Returns   The full path to the latest checkpoint or None if no checkpoint was found.
 predict View source
predict(
    input_fn, predict_keys=None, hooks=None, checkpoint_path=None,
    yield_single_examples=True
)
 Yields predictions for given features. Please note that interleaving two predict outputs does not work. See: issue/20506

 Args
  input_fn   A function that constructs the features. Prediction continues until input_fn raises an end-of-input exception (tf.errors.OutOfRangeError or StopIteration). See Premade Estimators for more information. The function should construct and return one of the following:
tf.data.Dataset object -- Outputs of Dataset object must have same constraints as below. features -- A tf.Tensor or a dictionary of string feature name to Tensor. features are consumed by model_fn. They should satisfy the expectation of model_fn from inputs. A tuple, in which case the first item is extracted as features.

  predict_keys   list of str, name of the keys to predict. It is used if the tf.estimator.EstimatorSpec.predictions is a dict. If predict_keys is used then rest of the predictions will be filtered from the dictionary. If None, returns all.
  hooks   List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the prediction call.
  checkpoint_path   Path of a specific checkpoint to predict. If None, the latest checkpoint in model_dir is used. If there are no checkpoints in model_dir, prediction is run with newly initialized Variables instead of ones restored from checkpoint.
  yield_single_examples   If False, yields the whole batch as returned by the model_fn instead of decomposing the batch into individual elements. This is useful if model_fn returns some tensors whose first dimension is not equal to the batch size.

 Yields   Evaluated values of predictions tensors.

 Raises
  ValueError   If batch length of predictions is not the same and yield_single_examples is True.
  ValueError   If there is a conflict between predict_keys and predictions. For example if predict_keys is not None but tf.estimator.EstimatorSpec.predictions is not a dict.    train View source
train(
    input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
 Trains a model given training data input_fn.

 Args
  input_fn   A function that provides input data for training as minibatches. See Premade Estimators for more information. The function should construct and return one of the following:  A tf.data.Dataset object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a tf.Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs.

  hooks   List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the training loop.
  steps   Number of steps for which to train the model. If None, train forever or train until input_fn generates the tf.errors.OutOfRange error or StopIteration exception. steps works incrementally. If you call two times train(steps=10) then training occurs in total 20 steps. If OutOfRange or StopIteration occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set max_steps instead. If set, max_steps must be None.
  max_steps   Number of total steps for which to train model. If None, train forever or train until input_fn generates the tf.errors.OutOfRange error or StopIteration exception. If set, steps must be None. If OutOfRange or StopIteration occurs in the middle, training stops before max_steps steps. Two calls to train(steps=100) means 200 training iterations. On the other hand, two calls to train(max_steps=100) means that the second call will not do any iteration since first call did all 100 steps.
  saving_listeners   list of CheckpointSaverListener objects. Used for callbacks that run immediately before or after checkpoint savings.

 Returns   self, for chaining.

 Raises
  ValueError   If both steps and max_steps are not None.
  ValueError   If either steps or max_steps <= 0.


tf.estimator.BaselineEstimator     View source on GitHub    An estimator that can establish a simple baseline. Inherits From: Estimator, Estimator
tf.estimator.BaselineEstimator(
    head, model_dir=None, optimizer='Ftrl', config=None
)
 The estimator uses a user-specified head. This estimator ignores feature values and will learn to predict the average value of each label. E.g. for single-label classification problems, this will predict the probability distribution of the classes as seen in the labels. For multi-label classification problems, it will predict the ratio of examples that contain each class. Example:
# Build baseline multi-label classifier.
estimator = tf.estimator.BaselineEstimator(
    head=tf.estimator.MultiLabelHead(n_classes=3))

# 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

# Fit model.
estimator.train(input_fn=input_fn_train)

# Evaluates cross entropy between the test and train labels.
loss = estimator.evaluate(input_fn=input_fn_eval)["loss"]

# For each class, predicts the ratio of training examples that contain the
# class.
predictions = estimator.predict(new_samples)

 Input of train and evaluate should have following features, otherwise there will be a KeyError:  if weight_column is specified in the head constructor (and not None) for the head passed to BaselineEstimator's constructor, a feature with key=weight_column whose value is a Tensor.

 Args
  head   A Head instance constructed with a method such as tf.estimator.MultiLabelHead.
  model_dir   Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model.
  optimizer   String, tf.keras.optimizers.* object, or callable that creates the optimizer to use for training. If not specified, will use Ftrl as the default optimizer.
  config   RunConfig object to configure the runtime settings.

 Attributes
  config

  export_savedmodel

  model_dir

  model_fn   Returns the model_fn which is bound to self.params.
  params
   Methods eval_dir View source
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 View source
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, or
input_fn raises an end-of-input exception (tf.errors.OutOfRangeError or StopIteration).

 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:  A tf.data.Dataset object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a tf.Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs.

  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 View source
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 Tensors. 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, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn. For training and evaluation, the train_op is stored in an extra collection, and loss, metrics, and predictions are included in a SignatureDef for the mode in question. Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.

 Args
  export_dir_base   A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
  input_receiver_fn_map   dict of tf.estimator.ModeKeys to input_receiver_fn mappings, where the input_receiver_fn is a function that takes no arguments and returns the appropriate subclass of InputReceiver.
  assets_extra   A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
  as_text   whether to write the SavedModel proto in text format.
  checkpoint_path   The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.

 Returns   The path to the exported directory as a bytes object.

 Raises
  ValueError   if any input_receiver_fn is None, no export_outputs are provided, or no checkpoint can be found.    export_saved_model View source
export_saved_model(
    export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False,
    checkpoint_path=None, experimental_mode=ModeKeys.PREDICT
)
 Exports inference graph as a SavedModel into the given dir. For a detailed guide, see SavedModel from Estimators. This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session. The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn. Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}. The experimental_mode parameter can be used to export a single train/eval/predict graph as a SavedModel. See experimental_export_all_saved_models for full docs.

 Args
  export_dir_base   A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
  serving_input_receiver_fn   A function that takes no argument and returns a tf.estimator.export.ServingInputReceiver or tf.estimator.export.TensorServingInputReceiver.
  assets_extra   A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
  as_text   whether to write the SavedModel proto in text format.
  checkpoint_path   The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.
  experimental_mode   tf.estimator.ModeKeys value indicating with mode will be exported. Note that this feature is experimental.

 Returns   The path to the exported directory as a bytes object.

 Raises
  ValueError   if no serving_input_receiver_fn is provided, no export_outputs are provided, or no checkpoint can be found.    get_variable_names View source
get_variable_names()
 Returns list of all variable names in this model.

 Returns   List of names.

 Raises
  ValueError   If the Estimator has not produced a checkpoint yet.    get_variable_value View source
get_variable_value(
    name
)
 Returns value of the variable given by name.

 Args
  name   string or a list of string, name of the tensor.

 Returns   Numpy array - value of the tensor.

 Raises
  ValueError   If the Estimator has not produced a checkpoint yet.    latest_checkpoint View source
latest_checkpoint()
 Finds the filename of the latest saved checkpoint file in model_dir.

 Returns   The full path to the latest checkpoint or None if no checkpoint was found.
 predict View source
predict(
    input_fn, predict_keys=None, hooks=None, checkpoint_path=None,
    yield_single_examples=True
)
 Yields predictions for given features. Please note that interleaving two predict outputs does not work. See: issue/20506

 Args
  input_fn   A function that constructs the features. Prediction continues until input_fn raises an end-of-input exception (tf.errors.OutOfRangeError or StopIteration). See Premade Estimators for more information. The function should construct and return one of the following:
tf.data.Dataset object -- Outputs of Dataset object must have same constraints as below. features -- A tf.Tensor or a dictionary of string feature name to Tensor. features are consumed by model_fn. They should satisfy the expectation of model_fn from inputs. A tuple, in which case the first item is extracted as features.

  predict_keys   list of str, name of the keys to predict. It is used if the tf.estimator.EstimatorSpec.predictions is a dict. If predict_keys is used then rest of the predictions will be filtered from the dictionary. If None, returns all.
  hooks   List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the prediction call.
  checkpoint_path   Path of a specific checkpoint to predict. If None, the latest checkpoint in model_dir is used. If there are no checkpoints in model_dir, prediction is run with newly initialized Variables instead of ones restored from checkpoint.
  yield_single_examples   If False, yields the whole batch as returned by the model_fn instead of decomposing the batch into individual elements. This is useful if model_fn returns some tensors whose first dimension is not equal to the batch size.

 Yields   Evaluated values of predictions tensors.

 Raises
  ValueError   If batch length of predictions is not the same and yield_single_examples is True.
  ValueError   If there is a conflict between predict_keys and predictions. For example if predict_keys is not None but tf.estimator.EstimatorSpec.predictions is not a dict.    train View source
train(
    input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
 Trains a model given training data input_fn.

 Args
  input_fn   A function that provides input data for training as minibatches. See Premade Estimators for more information. The function should construct and return one of the following:  A tf.data.Dataset object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a tf.Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs.

  hooks   List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the training loop.
  steps   Number of steps for which to train the model. If None, train forever or train until input_fn generates the tf.errors.OutOfRange error or StopIteration exception. steps works incrementally. If you call two times train(steps=10) then training occurs in total 20 steps. If OutOfRange or StopIteration occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set max_steps instead. If set, max_steps must be None.
  max_steps   Number of total steps for which to train model. If None, train forever or train until input_fn generates the tf.errors.OutOfRange error or StopIteration exception. If set, steps must be None. If OutOfRange or StopIteration occurs in the middle, training stops before max_steps steps. Two calls to train(steps=100) means 200 training iterations. On the other hand, two calls to train(max_steps=100) means that the second call will not do any iteration since first call did all 100 steps.
  saving_listeners   list of CheckpointSaverListener objects. Used for callbacks that run immediately before or after checkpoint savings.

 Returns   self, for chaining.

 Raises
  ValueError   If both steps and max_steps are not None.
  ValueError   If either steps or max_steps <= 0.


tf.estimator.BaselineRegressor     View source on GitHub    A regressor that can establish a simple baseline. Inherits From: Estimator, Estimator
tf.estimator.BaselineRegressor(
    model_dir=None, label_dimension=1, weight_column=None,
    optimizer='Ftrl', config=None,
    loss_reduction=losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE
)
 This regressor ignores feature values and will learn to predict the average value of each label. Example:
# Build BaselineRegressor
regressor = tf.estimator.BaselineRegressor()

# 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

# Fit model.
regressor.train(input_fn=input_fn_train)

# Evaluate squared-loss between the test and train targets.
loss = regressor.evaluate(input_fn=input_fn_eval)["loss"]

# predict outputs the mean value seen during training.
predictions = regressor.predict(new_samples)
 Input of train and evaluate should have following features, otherwise there will be a KeyError:  if weight_column is not None, a feature with key=weight_column whose value is a Tensor.

 Args
  model_dir   Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model.
  label_dimension   Number of regression targets per example. This is the size of the last dimension of the labels and logits Tensor objects (typically, these have shape [batch_size, label_dimension]).
  weight_column   A string or a _NumericColumn created by tf.feature_column.numeric_column defining feature column representing weights. It will be multiplied by the loss of the example.
  optimizer   String, tf.keras.optimizers.* object, or callable that creates the optimizer to use for training. If not specified, will use Ftrl as the default optimizer.
  config   RunConfig object to configure the runtime settings.
  loss_reduction   One of tf.losses.Reduction except NONE. Describes how to reduce training loss over batch. Defaults to SUM_OVER_BATCH_SIZE.    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

  export_savedmodel

  model_dir

  model_fn   Returns the model_fn which is bound to self.params.
  params
   Methods eval_dir View source
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 View source
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, or
input_fn raises an end-of-input exception (tf.errors.OutOfRangeError or StopIteration).

 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:  A tf.data.Dataset object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a tf.Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs.

  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 View source
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 Tensors. 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, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn. For training and evaluation, the train_op is stored in an extra collection, and loss, metrics, and predictions are included in a SignatureDef for the mode in question. Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.

 Args
  export_dir_base   A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
  input_receiver_fn_map   dict of tf.estimator.ModeKeys to input_receiver_fn mappings, where the input_receiver_fn is a function that takes no arguments and returns the appropriate subclass of InputReceiver.
  assets_extra   A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
  as_text   whether to write the SavedModel proto in text format.
  checkpoint_path   The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.

 Returns   The path to the exported directory as a bytes object.

 Raises
  ValueError   if any input_receiver_fn is None, no export_outputs are provided, or no checkpoint can be found.    export_saved_model View source
export_saved_model(
    export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False,
    checkpoint_path=None, experimental_mode=ModeKeys.PREDICT
)
 Exports inference graph as a SavedModel into the given dir. For a detailed guide, see SavedModel from Estimators. This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session. The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn. Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}. The experimental_mode parameter can be used to export a single train/eval/predict graph as a SavedModel. See experimental_export_all_saved_models for full docs.

 Args
  export_dir_base   A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
  serving_input_receiver_fn   A function that takes no argument and returns a tf.estimator.export.ServingInputReceiver or tf.estimator.export.TensorServingInputReceiver.
  assets_extra   A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
  as_text   whether to write the SavedModel proto in text format.
  checkpoint_path   The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.
  experimental_mode   tf.estimator.ModeKeys value indicating with mode will be exported. Note that this feature is experimental.

 Returns   The path to the exported directory as a bytes object.

 Raises
  ValueError   if no serving_input_receiver_fn is provided, no export_outputs are provided, or no checkpoint can be found.    get_variable_names View source
get_variable_names()
 Returns list of all variable names in this model.

 Returns   List of names.

 Raises
  ValueError   If the Estimator has not produced a checkpoint yet.    get_variable_value View source
get_variable_value(
    name
)
 Returns value of the variable given by name.

 Args
  name   string or a list of string, name of the tensor.

 Returns   Numpy array - value of the tensor.

 Raises
  ValueError   If the Estimator has not produced a checkpoint yet.    latest_checkpoint View source
latest_checkpoint()
 Finds the filename of the latest saved checkpoint file in model_dir.

 Returns   The full path to the latest checkpoint or None if no checkpoint was found.
 predict View source
predict(
    input_fn, predict_keys=None, hooks=None, checkpoint_path=None,
    yield_single_examples=True
)
 Yields predictions for given features. Please note that interleaving two predict outputs does not work. See: issue/20506

 Args
  input_fn   A function that constructs the features. Prediction continues until input_fn raises an end-of-input exception (tf.errors.OutOfRangeError or StopIteration). See Premade Estimators for more information. The function should construct and return one of the following:
tf.data.Dataset object -- Outputs of Dataset object must have same constraints as below. features -- A tf.Tensor or a dictionary of string feature name to Tensor. features are consumed by model_fn. They should satisfy the expectation of model_fn from inputs. A tuple, in which case the first item is extracted as features.

  predict_keys   list of str, name of the keys to predict. It is used if the tf.estimator.EstimatorSpec.predictions is a dict. If predict_keys is used then rest of the predictions will be filtered from the dictionary. If None, returns all.
  hooks   List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the prediction call.
  checkpoint_path   Path of a specific checkpoint to predict. If None, the latest checkpoint in model_dir is used. If there are no checkpoints in model_dir, prediction is run with newly initialized Variables instead of ones restored from checkpoint.
  yield_single_examples   If False, yields the whole batch as returned by the model_fn instead of decomposing the batch into individual elements. This is useful if model_fn returns some tensors whose first dimension is not equal to the batch size.

 Yields   Evaluated values of predictions tensors.

 Raises
  ValueError   If batch length of predictions is not the same and yield_single_examples is True.
  ValueError   If there is a conflict between predict_keys and predictions. For example if predict_keys is not None but tf.estimator.EstimatorSpec.predictions is not a dict.    train View source
train(
    input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
 Trains a model given training data input_fn.

 Args
  input_fn   A function that provides input data for training as minibatches. See Premade Estimators for more information. The function should construct and return one of the following:  A tf.data.Dataset object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a tf.Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs.

  hooks   List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the training loop.
  steps   Number of steps for which to train the model. If None, train forever or train until input_fn generates the tf.errors.OutOfRange error or StopIteration exception. steps works incrementally. If you call two times train(steps=10) then training occurs in total 20 steps. If OutOfRange or StopIteration occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set max_steps instead. If set, max_steps must be None.
  max_steps   Number of total steps for which to train model. If None, train forever or train until input_fn generates the tf.errors.OutOfRange error or StopIteration exception. If set, steps must be None. If OutOfRange or StopIteration occurs in the middle, training stops before max_steps steps. Two calls to train(steps=100) means 200 training iterations. On the other hand, two calls to train(max_steps=100) means that the second call will not do any iteration since first call did all 100 steps.
  saving_listeners   list of CheckpointSaverListener objects. Used for callbacks that run immediately before or after checkpoint savings.

 Returns   self, for chaining.

 Raises
  ValueError   If both steps and max_steps are not None.
  ValueError   If either steps or max_steps <= 0.


tf.estimator.BestExporter     View source on GitHub    This class exports the serving graph and checkpoints of the best models. Inherits From: Exporter  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.BestExporter
tf.estimator.BestExporter(
    name='best_exporter', serving_input_receiver_fn=None,
    event_file_pattern='eval/*.tfevents.*', compare_fn=_loss_smaller,
    assets_extra=None, as_text=False, exports_to_keep=5
)
 This class performs a model export everytime the new model is better than any existing model.

 Args
  name   unique name of this Exporter that is going to be used in the export path.
  serving_input_receiver_fn   a function that takes no arguments and returns a ServingInputReceiver.
  event_file_pattern   event file name pattern relative to model_dir. If None, however, the exporter would not be preemption-safe. To be preemption-safe, event_file_pattern must be specified.
  compare_fn   a function that compares two evaluation results and returns true if current evaluation result is better. Follows the signature:  Args:
best_eval_result: This is the evaluation result of the best model.
current_eval_result: This is the evaluation result of current candidate model. Returns: True if current evaluation result is better; otherwise, False.

  assets_extra   An optional dict specifying how to populate the assets.extra directory within the exported SavedModel. Each key should give the destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
  as_text   whether to write the SavedModel proto in text format. Defaults to False.
  exports_to_keep   Number of exports to keep. Older exports will be garbage-collected. Defaults to 5. Set to None to disable garbage collection.

 Raises
  ValueError   if any argument is invalid.

 Attributes
  name   Directory name. A directory name under the export base directory where exports of this type are written. Should not be None nor empty.
   Methods export View source
export(
    estimator, export_path, checkpoint_path, eval_result, is_the_final_export
)
 Exports the given Estimator to a specific format.

 Args
  estimator   the Estimator to export.
  export_path   A string containing a directory where to write the export.
  checkpoint_path   The checkpoint path to export.
  eval_result   The output of Estimator.evaluate on this checkpoint.
  is_the_final_export   This boolean is True when this is an export in the end of training. It is False for the intermediate exports during the training. When passing Exporter to tf.estimator.train_and_evaluate is_the_final_export is always False if TrainSpec.max_steps is None.

 Returns   The string path to the exported directory or None if export is skipped.


tf.estimator.BinaryClassHead     View source on GitHub    Creates a Head for single label binary classification. Inherits From: Head  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.BinaryClassHead
tf.estimator.BinaryClassHead(
    weight_column=None, thresholds=None, label_vocabulary=None,
    loss_reduction=losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE, loss_fn=None,
    name=None
)
 Uses sigmoid_cross_entropy_with_logits loss. The head expects logits with shape [D0, D1, ... DN, 1]. In many applications, the shape is [batch_size, 1]. labels must be a dense Tensor with shape matching logits, namely [D0, D1, ... DN, 1]. If label_vocabulary given, labels must be a string Tensor with values from the vocabulary. If label_vocabulary is not given, labels must be float Tensor with values in the interval [0, 1]. If weight_column is specified, weights must be of shape [D0, D1, ... DN], or [D0, D1, ... DN, 1]. The loss is the weighted sum over the input dimensions. Namely, if the input labels have shape [batch_size, 1], the loss is the weighted sum over batch_size. Also supports custom loss_fn. loss_fn takes (labels, logits) or (labels, logits, features, loss_reduction) as arguments and returns loss with shape [D0, D1, ... DN, 1]. loss_fn must support float labels with shape [D0, D1, ... DN, 1]. Namely, the head applies label_vocabulary to the input labels before passing them to loss_fn. Usage:
head = tf.estimator.BinaryClassHead()
logits = np.array(((45,), (-41,),), dtype=np.float32)
labels = np.array(((1,), (1,),), dtype=np.int32)
features = {'x': np.array(((42,),), dtype=np.float32)}
# expected_loss = sum(cross_entropy(labels, logits)) / batch_size
#               = sum(0, 41) / 2 = 41 / 2 = 20.50
loss = head.loss(labels, logits, features=features)
print('{:.2f}'.format(loss.numpy()))
20.50
eval_metrics = head.metrics()
updated_metrics = head.update_metrics(
  eval_metrics, features, logits, labels)
for k in sorted(updated_metrics):
 print('{} : {:.2f}'.format(k, updated_metrics[k].result().numpy()))
  accuracy : 0.50
  accuracy_baseline : 1.00
  auc : 0.00
  auc_precision_recall : 1.00
  average_loss : 20.50
  label/mean : 1.00
  precision : 1.00
  prediction/mean : 0.50
  recall : 0.50
preds = head.predictions(logits)
print(preds['logits'])
tf.Tensor(
  [[ 45.]
   [-41.]], shape=(2, 1), dtype=float32)
 Usage with a canned estimator: my_head = tf.estimator.BinaryClassHead()
my_estimator = tf.estimator.DNNEstimator(
    head=my_head,
    hidden_units=...,
    feature_columns=...)
 It can also be used with a custom model_fn. Example: def _my_model_fn(features, labels, mode):
  my_head = tf.estimator.BinaryClassHead()
  logits = tf.keras.Model(...)(features)

  return my_head.create_estimator_spec(
      features=features,
      mode=mode,
      labels=labels,
      optimizer=tf.keras.optimizers.Adagrad(lr=0.1),
      logits=logits)

my_estimator = tf.estimator.Estimator(model_fn=_my_model_fn)

 Args
  weight_column   A string or a NumericColumn created by tf.feature_column.numeric_column defining feature column representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example.
  thresholds   Iterable of floats in the range (0, 1). For binary classification metrics such as precision and recall, an eval metric is generated for each threshold value. This threshold is applied to the logistic values to determine the binary classification (i.e., above the threshold is true, below is false.
  label_vocabulary   A list or tuple of strings representing possible label values. If it is not given, that means labels are already encoded within [0, 1]. If given, labels must be string type and have any value in label_vocabulary. Note that errors will be raised if label_vocabulary is not provided but labels are strings.
  loss_reduction   One of tf.losses.Reduction except NONE. Decides how to reduce training loss over batch. Defaults to SUM_OVER_BATCH_SIZE, namely weighted sum of losses divided by batch size * label_dimension.
  loss_fn   Optional loss function.
  name   Name of the head. If provided, summary and metrics keys will be suffixed by "/" + name. Also used as name_scope when creating ops.

 Attributes
  logits_dimension   See base_head.Head for details.
  loss_reduction   See base_head.Head for details.
  name   See base_head.Head for details.    Methods create_estimator_spec View source
create_estimator_spec(
    features, mode, logits, labels=None, optimizer=None, trainable_variables=None,
    train_op_fn=None, update_ops=None, regularization_losses=None
)
 Returns EstimatorSpec that a model_fn can return. It is recommended to pass all args via name.

 Args
  features   Input dict mapping string feature names to Tensor or SparseTensor objects containing the values for that feature in a minibatch. Often to be used to fetch example-weight tensor.
  mode   Estimator's ModeKeys.
  logits   Logits Tensor to be used by the head.
  labels   Labels Tensor, or dict mapping string label names to Tensor objects of the label values.
  optimizer   An tf.keras.optimizers.Optimizer instance to optimize the loss in TRAIN mode. Namely, sets train_op = optimizer.get_updates(loss, trainable_variables), which updates variables to minimize loss.
  trainable_variables   A list or tuple of Variable objects to update to minimize loss. In Tensorflow 1.x, by default these are the list of variables collected in the graph under the key GraphKeys.TRAINABLE_VARIABLES. As Tensorflow 2.x doesn't have collections and GraphKeys, trainable_variables need to be passed explicitly here.
  train_op_fn   Function that takes a scalar loss Tensor and returns an op to optimize the model with the loss in TRAIN mode. Used if optimizer is None. Exactly one of train_op_fn and optimizer must be set in TRAIN mode. By default, it is None in other modes. If you want to optimize loss yourself, you can pass lambda _: tf.no_op() and then use EstimatorSpec.loss to compute and apply gradients.
  update_ops   A list or tuple of update ops to be run at training time. For example, layers such as BatchNormalization create mean and variance update ops that need to be run at training time. In Tensorflow 1.x, these are thrown into an UPDATE_OPS collection. As Tensorflow 2.x doesn't have collections, update_ops need to be passed explicitly here.
  regularization_losses   A list of additional scalar losses to be added to the training loss, such as regularization losses.

 Returns   EstimatorSpec.
 loss View source
loss(
    labels, logits, features=None, mode=None, regularization_losses=None
)
 Returns regularized training loss. See base_head.Head for details. metrics View source
metrics(
    regularization_losses=None
)
 Creates metrics. See base_head.Head for details. predictions View source
predictions(
    logits, keys=None
)
 Return predictions based on keys. See base_head.Head for details.

 Args
  logits   logits Tensor with shape [D0, D1, ... DN, logits_dimension]. For many applications, the shape is [batch_size, logits_dimension].
  keys   a list or tuple of prediction keys. Each key can be either the class variable of prediction_keys.PredictionKeys or its string value, such as: prediction_keys.PredictionKeys.CLASSES or 'classes'. If not specified, it will return the predictions for all valid keys.

 Returns   A dict of predictions.
 update_metrics View source
update_metrics(
    eval_metrics, features, logits, labels, regularization_losses=None
)
 Updates eval metrics. See base_head.Head for details.