Gamma distribution.
Inherits From: Distribution
The Gamma distribution is defined over positive real numbers using parameters concentration (aka "alpha") and rate (aka "beta").
The probability density function (pdf) is,
where:
The cumulative density function (cdf) is,
where GammaInc is the lower incomplete Gamma function.
The parameters can be intuited via their relationship to mean and stddev,
Distribution parameters are automatically broadcast in all functions; see examples for details.
Samples of this distribution are reparameterized (pathwise differentiable). The derivatives are computed using the approach described in (Figurnov et al., 2018).
Compute the gradients of samples w.r.t. the parameters:
Implicit Reparameterization Gradients: Figurnov et al., 2018 (pdf)
Stats return +/- infinity when it makes sense. E.g., the variance of a Cauchy distribution is infinity. However, sometimes the statistic is undefined, e.g., if a distribution's pdf does not achieve a maximum within the support of the distribution, the mode is undefined. If the mean is undefined, then by definition the variance is undefined. E.g. the mean for Student's T for df = 1 is undefined (no clear way to say it is either + or - infinity), so the variance = E[(X - mean)**2] is also undefined.
May be partially defined or unknown.
The batch dimensions are indexes into independent, non-identical parameterizations of this distribution.
May be partially defined or unknown.
Currently this is one of the static instances distributions.FULLY_REPARAMETERIZED or distributions.NOT_REPARAMETERIZED.
View source
Shape of a single sample from a single event index as a 1-D Tensor.
The batch dimensions are indexes into independent, non-identical parameterizations of this distribution.
View source
Cumulative distribution function.
Given random variable X, the cumulative distribution function cdf is:
View source
Creates a deep copy of the distribution.
View source
Covariance.
Covariance is (possibly) defined only for non-scalar-event distributions.
For example, for a length-k, vector-valued distribution, it is calculated as,
where Cov is a (batch of) k x k matrix, 0 <= (i, j) < k, and E denotes expectation.
Alternatively, for non-vector, multivariate distributions (e.g., matrix-valued, Wishart), Covariance shall return a (batch of) matrices under some vectorization of the events, i.e.,
where Cov is a (batch of) k' x k' matrices, 0 <= (i, j) < k' = reduce_prod(event_shape), and Vec is some function mapping indices of this distribution's event dimensions to indices of a length-k' vector.
View source
Computes the (Shannon) cross entropy.
Denote this distribution (self) by P and the other distribution by Q. Assuming P, Q are absolutely continuous with respect to one another and permit densities p(x) dr(x) and q(x) dr(x), (Shanon) cross entropy is defined as:
where F denotes the support of the random variable X ~ P.
View source
Shannon entropy in nats.
View source
Shape of a single sample from a single batch as a 1-D int32 Tensor.
View source
Indicates that batch_shape == [].
View source
Indicates that event_shape == [].
View source
Computes the Kullback--Leibler divergence.
Denote this distribution (self) by p and the other distribution by q. Assuming p, q are absolutely continuous with respect to reference measure r, the KL divergence is defined as:
where F denotes the support of the random variable X ~ p, H[., .] denotes (Shanon) cross entropy, and H[.] denotes (Shanon) entropy.
View source
Log cumulative distribution function.
Given random variable X, the cumulative distribution function cdf is:
Often, a numerical approximation can be used for log_cdf(x) that yields a more accurate answer than simply taking the logarithm of the cdf when x << -1.
View source
Log probability density/mass function.
View source
Log survival function.
Given random variable X, the survival function is defined:
Typically, different numerical approximations can be used for the log survival function, which are more accurate than 1 - cdf(x) when x >> 1.
View source
Mean.
View source
Mode.
Additional documentation from Gamma:
The mode of a gamma distribution is (shape - 1) / rate when shape > 1, and NaN otherwise. If self.allow_nan_stats is False, an exception will be raised rather than returning NaN.
View source
Shapes of parameters given the desired shape of a call to sample().
This is a class method that describes what key/value arguments are required to instantiate the given Distribution so that a particular shape is returned for that instance's call to sample().
Subclasses should override class method _param_shapes.
View source
param_shapes with static (i.e. TensorShape) shapes.
This is a class method that describes what key/value arguments are required to instantiate the given Distribution so that a particular shape is returned for that instance's call to sample(). Assumes that the sample's shape is known statically.
Subclasses should override class method _param_shapes to return constant-valued tensors when constant values are fed.
View source
Probability density/mass function.
View source
Quantile function. Aka "inverse cdf" or "percent point function".
Given random variable X and p in [0, 1], the quantile is:
View source
Generate samples of the specified shape.
Note that a call to sample() without arguments will generate a single sample.
View source
Standard deviation.
Standard deviation is defined as,
where X is the random variable associated with this distribution, E denotes expectation, and stddev.shape = batch_shape + event_shape.
View source
Survival function.
Given random variable X, the survival function is defined:
View source
Variance.
Variance is defined as,
where X is the random variable associated with this distribution, E denotes expectation, and Var.shape = batch_shape + event_shape.


Get the KL-divergence KL(distribution_a || distribution_b). (deprecated)
If there is no KL method registered specifically for type(distribution_a) and type(distribution_b), then the class hierarchies of these types are searched.
If one KL method is registered between any pairs of classes in these two parent hierarchies, it is used.
If more than one such registered method exists, the method whose registered classes have the shortest sum MRO paths to the input types is used.
If more than one such shortest path exists, the first method identified in the search is used (favoring a shorter MRO distance to type(distribution_a)).


The Laplace distribution with location loc and scale parameters.
Inherits From: Distribution
The probability density function (pdf) of this distribution is,
where loc = mu, scale = sigma, and Z is the normalization constant.
Note that the Laplace distribution can be thought of two exponential distributions spliced together "back-to-back."
The Lpalce distribution is a member of the location-scale family, i.e., it can be constructed as,
Stats return +/- infinity when it makes sense. E.g., the variance of a Cauchy distribution is infinity. However, sometimes the statistic is undefined, e.g., if a distribution's pdf does not achieve a maximum within the support of the distribution, the mode is undefined. If the mean is undefined, then by definition the variance is undefined. E.g. the mean for Student's T for df = 1 is undefined (no clear way to say it is either + or - infinity), so the variance = E[(X - mean)**2] is also undefined.
May be partially defined or unknown.
The batch dimensions are indexes into independent, non-identical parameterizations of this distribution.
May be partially defined or unknown.
Currently this is one of the static instances distributions.FULLY_REPARAMETERIZED or distributions.NOT_REPARAMETERIZED.
View source
Shape of a single sample from a single event index as a 1-D Tensor.
The batch dimensions are indexes into independent, non-identical parameterizations of this distribution.
View source
Cumulative distribution function.
Given random variable X, the cumulative distribution function cdf is:
View source
Creates a deep copy of the distribution.
View source
Covariance.
Covariance is (possibly) defined only for non-scalar-event distributions.
For example, for a length-k, vector-valued distribution, it is calculated as,
where Cov is a (batch of) k x k matrix, 0 <= (i, j) < k, and E denotes expectation.
Alternatively, for non-vector, multivariate distributions (e.g., matrix-valued, Wishart), Covariance shall return a (batch of) matrices under some vectorization of the events, i.e.,
where Cov is a (batch of) k' x k' matrices, 0 <= (i, j) < k' = reduce_prod(event_shape), and Vec is some function mapping indices of this distribution's event dimensions to indices of a length-k' vector.
View source
Computes the (Shannon) cross entropy.
Denote this distribution (self) by P and the other distribution by Q. Assuming P, Q are absolutely continuous with respect to one another and permit densities p(x) dr(x) and q(x) dr(x), (Shanon) cross entropy is defined as:
where F denotes the support of the random variable X ~ P.
View source
Shannon entropy in nats.
View source
Shape of a single sample from a single batch as a 1-D int32 Tensor.
View source
Indicates that batch_shape == [].
View source
Indicates that event_shape == [].
View source
Computes the Kullback--Leibler divergence.
Denote this distribution (self) by p and the other distribution by q. Assuming p, q are absolutely continuous with respect to reference measure r, the KL divergence is defined as:
where F denotes the support of the random variable X ~ p, H[., .] denotes (Shanon) cross entropy, and H[.] denotes (Shanon) entropy.
View source
Log cumulative distribution function.
Given random variable X, the cumulative distribution function cdf is:
Often, a numerical approximation can be used for log_cdf(x) that yields a more accurate answer than simply taking the logarithm of the cdf when x << -1.
View source
Log probability density/mass function.
View source
Log survival function.
Given random variable X, the survival function is defined:
Typically, different numerical approximations can be used for the log survival function, which are more accurate than 1 - cdf(x) when x >> 1.
View source
Mean.
View source
Mode.
View source
Shapes of parameters given the desired shape of a call to sample().
This is a class method that describes what key/value arguments are required to instantiate the given Distribution so that a particular shape is returned for that instance's call to sample().
Subclasses should override class method _param_shapes.
View source
param_shapes with static (i.e. TensorShape) shapes.
This is a class method that describes what key/value arguments are required to instantiate the given Distribution so that a particular shape is returned for that instance's call to sample(). Assumes that the sample's shape is known statically.
Subclasses should override class method _param_shapes to return constant-valued tensors when constant values are fed.
View source
Probability density/mass function.
View source
Quantile function. Aka "inverse cdf" or "percent point function".
Given random variable X and p in [0, 1], the quantile is:
View source
Generate samples of the specified shape.
Note that a call to sample() without arguments will generate a single sample.
View source
Standard deviation.
Standard deviation is defined as,
where X is the random variable associated with this distribution, E denotes expectation, and stddev.shape = batch_shape + event_shape.
View source
Survival function.
Given random variable X, the survival function is defined:
View source
Variance.
Variance is defined as,
where X is the random variable associated with this distribution, E denotes expectation, and Var.shape = batch_shape + event_shape.


Multinomial distribution.
Inherits From: Distribution
This Multinomial distribution is parameterized by probs, a (batch of) length-K prob (probability) vectors (K > 1) such that tf.reduce_sum(probs, -1) = 1, and a total_count number of trials, i.e., the number of trials per draw from the Multinomial. It is defined over a (batch of) length-K vector counts such that tf.reduce_sum(counts, -1) = total_count. The Multinomial is identically the Binomial distribution when K = 2.
The Multinomial is a distribution over K-class counts, i.e., a length-K vector of non-negative integer counts = n = [n_0, ..., n_{K-1}].
The probability mass function (pmf) is,
where:
Distribution parameters are automatically broadcast in all functions; see examples for details.
The number of classes, K, must not exceed:
In other words,
Create a 3-class distribution, with the 3rd class is most likely to be drawn, using logits.
Create a 3-class distribution, with the 3rd class is most likely to be drawn.
The distribution functions can be evaluated on counts.
Create a 2-batch of 3-class distributions.
Stats return +/- infinity when it makes sense. E.g., the variance of a Cauchy distribution is infinity. However, sometimes the statistic is undefined, e.g., if a distribution's pdf does not achieve a maximum within the support of the distribution, the mode is undefined. If the mean is undefined, then by definition the variance is undefined. E.g. the mean for Student's T for df = 1 is undefined (no clear way to say it is either + or - infinity), so the variance = E[(X - mean)**2] is also undefined.
May be partially defined or unknown.
The batch dimensions are indexes into independent, non-identical parameterizations of this distribution.
May be partially defined or unknown.
Currently this is one of the static instances distributions.FULLY_REPARAMETERIZED or distributions.NOT_REPARAMETERIZED.
View source
Shape of a single sample from a single event index as a 1-D Tensor.
The batch dimensions are indexes into independent, non-identical parameterizations of this distribution.
View source
Cumulative distribution function.
Given random variable X, the cumulative distribution function cdf is:
View source
Creates a deep copy of the distribution.
View source
Covariance.
Covariance is (possibly) defined only for non-scalar-event distributions.
For example, for a length-k, vector-valued distribution, it is calculated as,
where Cov is a (batch of) k x k matrix, 0 <= (i, j) < k, and E denotes expectation.
Alternatively, for non-vector, multivariate distributions (e.g., matrix-valued, Wishart), Covariance shall return a (batch of) matrices under some vectorization of the events, i.e.,
where Cov is a (batch of) k' x k' matrices, 0 <= (i, j) < k' = reduce_prod(event_shape), and Vec is some function mapping indices of this distribution's event dimensions to indices of a length-k' vector.
View source
Computes the (Shannon) cross entropy.
Denote this distribution (self) by P and the other distribution by Q. Assuming P, Q are absolutely continuous with respect to one another and permit densities p(x) dr(x) and q(x) dr(x), (Shanon) cross entropy is defined as:
where F denotes the support of the random variable X ~ P.
View source
Shannon entropy in nats.
View source
Shape of a single sample from a single batch as a 1-D int32 Tensor.
View source
Indicates that batch_shape == [].
View source
Indicates that event_shape == [].
View source
Computes the Kullback--Leibler divergence.
Denote this distribution (self) by p and the other distribution by q. Assuming p, q are absolutely continuous with respect to reference measure r, the KL divergence is defined as:
where F denotes the support of the random variable X ~ p, H[., .] denotes (Shanon) cross entropy, and H[.] denotes (Shanon) entropy.
View source
Log cumulative distribution function.
Given random variable X, the cumulative distribution function cdf is:
Often, a numerical approximation can be used for log_cdf(x) that yields a more accurate answer than simply taking the logarithm of the cdf when x << -1.
View source
Log probability density/mass function.
Additional documentation from Multinomial:
For each batch of counts, value = [n_0, ... ,n_{k-1}], P[value] is the probability that after sampling self.total_count draws from this Multinomial distribution, the number of draws falling in class j is n_j. Since this definition is exchangeable; different sequences have the same counts so the probability includes a combinatorial coefficient.
View source
Log survival function.
Given random variable X, the survival function is defined:
Typically, different numerical approximations can be used for the log survival function, which are more accurate than 1 - cdf(x) when x >> 1.
View source
Mean.
View source
Mode.
View source
Shapes of parameters given the desired shape of a call to sample().
This is a class method that describes what key/value arguments are required to instantiate the given Distribution so that a particular shape is returned for that instance's call to sample().
Subclasses should override class method _param_shapes.
View source
param_shapes with static (i.e. TensorShape) shapes.
This is a class method that describes what key/value arguments are required to instantiate the given Distribution so that a particular shape is returned for that instance's call to sample(). Assumes that the sample's shape is known statically.
Subclasses should override class method _param_shapes to return constant-valued tensors when constant values are fed.
View source
Probability density/mass function.
View source
Quantile function. Aka "inverse cdf" or "percent point function".
Given random variable X and p in [0, 1], the quantile is:
View source
Generate samples of the specified shape.
Note that a call to sample() without arguments will generate a single sample.
View source
Standard deviation.
Standard deviation is defined as,
where X is the random variable associated with this distribution, E denotes expectation, and stddev.shape = batch_shape + event_shape.
View source
Survival function.
Given random variable X, the survival function is defined:
View source
Variance.
Variance is defined as,
where X is the random variable associated with this distribution, E denotes expectation, and Var.shape = batch_shape + event_shape.


The Normal distribution with location loc and scale parameters.
Inherits From: Distribution
The probability density function (pdf) is,
where loc = mu is the mean, scale = sigma is the std. deviation, and, Z is the normalization constant.
The Normal distribution is a member of the location-scale family, i.e., it can be constructed as,
Examples of initialization of one or a batch of distributions.
Arguments are broadcast when possible.
Stats return +/- infinity when it makes sense. E.g., the variance of a Cauchy distribution is infinity. However, sometimes the statistic is undefined, e.g., if a distribution's pdf does not achieve a maximum within the support of the distribution, the mode is undefined. If the mean is undefined, then by definition the variance is undefined. E.g. the mean for Student's T for df = 1 is undefined (no clear way to say it is either + or - infinity), so the variance = E[(X - mean)**2] is also undefined.
May be partially defined or unknown.
The batch dimensions are indexes into independent, non-identical parameterizations of this distribution.
May be partially defined or unknown.
Currently this is one of the static instances distributions.FULLY_REPARAMETERIZED or distributions.NOT_REPARAMETERIZED.
View source
Shape of a single sample from a single event index as a 1-D Tensor.
The batch dimensions are indexes into independent, non-identical parameterizations of this distribution.
View source
Cumulative distribution function.
Given random variable X, the cumulative distribution function cdf is:
View source
Creates a deep copy of the distribution.
View source
Covariance.
Covariance is (possibly) defined only for non-scalar-event distributions.
For example, for a length-k, vector-valued distribution, it is calculated as,
where Cov is a (batch of) k x k matrix, 0 <= (i, j) < k, and E denotes expectation.
Alternatively, for non-vector, multivariate distributions (e.g., matrix-valued, Wishart), Covariance shall return a (batch of) matrices under some vectorization of the events, i.e.,
where Cov is a (batch of) k' x k' matrices, 0 <= (i, j) < k' = reduce_prod(event_shape), and Vec is some function mapping indices of this distribution's event dimensions to indices of a length-k' vector.
View source
Computes the (Shannon) cross entropy.
Denote this distribution (self) by P and the other distribution by Q. Assuming P, Q are absolutely continuous with respect to one another and permit densities p(x) dr(x) and q(x) dr(x), (Shanon) cross entropy is defined as:
where F denotes the support of the random variable X ~ P.
View source
Shannon entropy in nats.
View source
Shape of a single sample from a single batch as a 1-D int32 Tensor.
View source
Indicates that batch_shape == [].
View source
Indicates that event_shape == [].
View source
Computes the Kullback--Leibler divergence.
Denote this distribution (self) by p and the other distribution by q. Assuming p, q are absolutely continuous with respect to reference measure r, the KL divergence is defined as:
where F denotes the support of the random variable X ~ p, H[., .] denotes (Shanon) cross entropy, and H[.] denotes (Shanon) entropy.
View source
Log cumulative distribution function.
Given random variable X, the cumulative distribution function cdf is:
Often, a numerical approximation can be used for log_cdf(x) that yields a more accurate answer than simply taking the logarithm of the cdf when x << -1.
View source
Log probability density/mass function.
View source
Log survival function.
Given random variable X, the survival function is defined:
Typically, different numerical approximations can be used for the log survival function, which are more accurate than 1 - cdf(x) when x >> 1.
View source
Mean.
View source
Mode.
View source
Shapes of parameters given the desired shape of a call to sample().
This is a class method that describes what key/value arguments are required to instantiate the given Distribution so that a particular shape is returned for that instance's call to sample().
Subclasses should override class method _param_shapes.
View source
param_shapes with static (i.e. TensorShape) shapes.
This is a class method that describes what key/value arguments are required to instantiate the given Distribution so that a particular shape is returned for that instance's call to sample(). Assumes that the sample's shape is known statically.
Subclasses should override class method _param_shapes to return constant-valued tensors when constant values are fed.
View source
Probability density/mass function.
View source
Quantile function. Aka "inverse cdf" or "percent point function".
Given random variable X and p in [0, 1], the quantile is:
View source
Generate samples of the specified shape.
Note that a call to sample() without arguments will generate a single sample.
View source
Standard deviation.
Standard deviation is defined as,
where X is the random variable associated with this distribution, E denotes expectation, and stddev.shape = batch_shape + event_shape.
View source
Survival function.
Given random variable X, the survival function is defined:
View source
Variance.
Variance is defined as,
where X is the random variable associated with this distribution, E denotes expectation, and Var.shape = batch_shape + event_shape.


Decorator to register a KL divergence implementation function.
@distributions.RegisterKL(distributions.Normal, distributions.Normal) def _kl_normal_mvn(norm_a, norm_b): # Return KL(norm_a || norm_b)
View source
Perform the KL registration.


Instances of this class represent how sampling is reparameterized.
Two static instances exist in the distributions library, signifying one of two possible properties for samples from a distribution:
FULLY_REPARAMETERIZED: Samples from the distribution are fully reparameterized, and straight-through gradients are supported.
NOT_REPARAMETERIZED: Samples from the distribution are not fully reparameterized, and straight-through gradients are either partially unsupported or are not supported at all. In this case, for purposes of e.g. RL or variational inference, it is generally safest to wrap the sample results in a stop_gradients call and use policy gradients / surrogate loss instead.
View source
Determine if this ReparameterizationType is equal to another.
Since ReparameterizationType instances are constant static global instances, equality checks if two instances' id() values are equal.


Student's t-distribution.
Inherits From: Distribution
This distribution has parameters: degree of freedom df, location loc, and scale.
The probability density function (pdf) is,
where:
The StudentT distribution is a member of the location-scale family, i.e., it can be constructed as,
Notice that scale has semantics more similar to standard deviation than variance. However it is not actually the std. deviation; the Student's t-distribution std. dev. is scale sqrt(df / (df - 2)) when df > 2.
Samples of this distribution are reparameterized (pathwise differentiable). The derivatives are computed using the approach described in (Figurnov et al., 2018).
Examples of initialization of one or a batch of distributions.
Arguments are broadcast when possible.
Compute the gradients of samples w.r.t. the parameters:
Implicit Reparameterization Gradients: Figurnov et al., 2018 (pdf)
Stats return +/- infinity when it makes sense. E.g., the variance of a Cauchy distribution is infinity. However, sometimes the statistic is undefined, e.g., if a distribution's pdf does not achieve a maximum within the support of the distribution, the mode is undefined. If the mean is undefined, then by definition the variance is undefined. E.g. the mean for Student's T for df = 1 is undefined (no clear way to say it is either + or - infinity), so the variance = E[(X - mean)**2] is also undefined.
May be partially defined or unknown.
The batch dimensions are indexes into independent, non-identical parameterizations of this distribution.
May be partially defined or unknown.
Currently this is one of the static instances distributions.FULLY_REPARAMETERIZED or distributions.NOT_REPARAMETERIZED.
View source
Shape of a single sample from a single event index as a 1-D Tensor.
The batch dimensions are indexes into independent, non-identical parameterizations of this distribution.
View source
Cumulative distribution function.
Given random variable X, the cumulative distribution function cdf is:
View source
Creates a deep copy of the distribution.
View source
Covariance.
Covariance is (possibly) defined only for non-scalar-event distributions.
For example, for a length-k, vector-valued distribution, it is calculated as,
where Cov is a (batch of) k x k matrix, 0 <= (i, j) < k, and E denotes expectation.
Alternatively, for non-vector, multivariate distributions (e.g., matrix-valued, Wishart), Covariance shall return a (batch of) matrices under some vectorization of the events, i.e.,
where Cov is a (batch of) k' x k' matrices, 0 <= (i, j) < k' = reduce_prod(event_shape), and Vec is some function mapping indices of this distribution's event dimensions to indices of a length-k' vector.
View source
Computes the (Shannon) cross entropy.
Denote this distribution (self) by P and the other distribution by Q. Assuming P, Q are absolutely continuous with respect to one another and permit densities p(x) dr(x) and q(x) dr(x), (Shanon) cross entropy is defined as:
where F denotes the support of the random variable X ~ P.
View source
Shannon entropy in nats.
View source
Shape of a single sample from a single batch as a 1-D int32 Tensor.
View source
Indicates that batch_shape == [].
View source
Indicates that event_shape == [].
View source
Computes the Kullback--Leibler divergence.
Denote this distribution (self) by p and the other distribution by q. Assuming p, q are absolutely continuous with respect to reference measure r, the KL divergence is defined as:
where F denotes the support of the random variable X ~ p, H[., .] denotes (Shanon) cross entropy, and H[.] denotes (Shanon) entropy.
View source
Log cumulative distribution function.
Given random variable X, the cumulative distribution function cdf is:
Often, a numerical approximation can be used for log_cdf(x) that yields a more accurate answer than simply taking the logarithm of the cdf when x << -1.
View source
Log probability density/mass function.
View source
Log survival function.
Given random variable X, the survival function is defined:
Typically, different numerical approximations can be used for the log survival function, which are more accurate than 1 - cdf(x) when x >> 1.
View source
Mean.
Additional documentation from StudentT:
The mean of Student's T equals loc if df > 1, otherwise it is NaN. If self.allow_nan_stats=True, then an exception will be raised rather than returning NaN.
View source
Mode.
View source
Shapes of parameters given the desired shape of a call to sample().
This is a class method that describes what key/value arguments are required to instantiate the given Distribution so that a particular shape is returned for that instance's call to sample().
Subclasses should override class method _param_shapes.
View source
param_shapes with static (i.e. TensorShape) shapes.
This is a class method that describes what key/value arguments are required to instantiate the given Distribution so that a particular shape is returned for that instance's call to sample(). Assumes that the sample's shape is known statically.
Subclasses should override class method _param_shapes to return constant-valued tensors when constant values are fed.
View source
Probability density/mass function.
View source
Quantile function. Aka "inverse cdf" or "percent point function".
Given random variable X and p in [0, 1], the quantile is:
View source
Generate samples of the specified shape.
Note that a call to sample() without arguments will generate a single sample.
View source
Standard deviation.
Standard deviation is defined as,
where X is the random variable associated with this distribution, E denotes expectation, and stddev.shape = batch_shape + event_shape.
View source
Survival function.
Given random variable X, the survival function is defined:
View source
Variance.
Variance is defined as,
where X is the random variable associated with this distribution, E denotes expectation, and Var.shape = batch_shape + event_shape.
Additional documentation from StudentT:
The variance for Student's T equals


Uniform distribution with low and high parameters.
Inherits From: Distribution
The probability density function (pdf) is,
where
The parameters low and high must be shaped in a way that supports broadcasting (e.g., high - low is a valid operation).
Stats return +/- infinity when it makes sense. E.g., the variance of a Cauchy distribution is infinity. However, sometimes the statistic is undefined, e.g., if a distribution's pdf does not achieve a maximum within the support of the distribution, the mode is undefined. If the mean is undefined, then by definition the variance is undefined. E.g. the mean for Student's T for df = 1 is undefined (no clear way to say it is either + or - infinity), so the variance = E[(X - mean)**2] is also undefined.
May be partially defined or unknown.
The batch dimensions are indexes into independent, non-identical parameterizations of this distribution.
May be partially defined or unknown.
Currently this is one of the static instances distributions.FULLY_REPARAMETERIZED or distributions.NOT_REPARAMETERIZED.
View source
Shape of a single sample from a single event index as a 1-D Tensor.
The batch dimensions are indexes into independent, non-identical parameterizations of this distribution.
View source
Cumulative distribution function.
Given random variable X, the cumulative distribution function cdf is:
View source
Creates a deep copy of the distribution.
View source
Covariance.
Covariance is (possibly) defined only for non-scalar-event distributions.
For example, for a length-k, vector-valued distribution, it is calculated as,
where Cov is a (batch of) k x k matrix, 0 <= (i, j) < k, and E denotes expectation.
Alternatively, for non-vector, multivariate distributions (e.g., matrix-valued, Wishart), Covariance shall return a (batch of) matrices under some vectorization of the events, i.e.,
where Cov is a (batch of) k' x k' matrices, 0 <= (i, j) < k' = reduce_prod(event_shape), and Vec is some function mapping indices of this distribution's event dimensions to indices of a length-k' vector.
View source
Computes the (Shannon) cross entropy.
Denote this distribution (self) by P and the other distribution by Q. Assuming P, Q are absolutely continuous with respect to one another and permit densities p(x) dr(x) and q(x) dr(x), (Shanon) cross entropy is defined as:
where F denotes the support of the random variable X ~ P.
View source
Shannon entropy in nats.
View source
Shape of a single sample from a single batch as a 1-D int32 Tensor.
View source
Indicates that batch_shape == [].
View source
Indicates that event_shape == [].
View source
Computes the Kullback--Leibler divergence.
Denote this distribution (self) by p and the other distribution by q. Assuming p, q are absolutely continuous with respect to reference measure r, the KL divergence is defined as:
where F denotes the support of the random variable X ~ p, H[., .] denotes (Shanon) cross entropy, and H[.] denotes (Shanon) entropy.
View source
Log cumulative distribution function.
Given random variable X, the cumulative distribution function cdf is:
Often, a numerical approximation can be used for log_cdf(x) that yields a more accurate answer than simply taking the logarithm of the cdf when x << -1.
View source
Log probability density/mass function.
View source
Log survival function.
Given random variable X, the survival function is defined:
Typically, different numerical approximations can be used for the log survival function, which are more accurate than 1 - cdf(x) when x >> 1.
View source
Mean.
View source
Mode.
View source
Shapes of parameters given the desired shape of a call to sample().
This is a class method that describes what key/value arguments are required to instantiate the given Distribution so that a particular shape is returned for that instance's call to sample().
Subclasses should override class method _param_shapes.
View source
param_shapes with static (i.e. TensorShape) shapes.
This is a class method that describes what key/value arguments are required to instantiate the given Distribution so that a particular shape is returned for that instance's call to sample(). Assumes that the sample's shape is known statically.
Subclasses should override class method _param_shapes to return constant-valued tensors when constant values are fed.
View source
Probability density/mass function.
View source
Quantile function. Aka "inverse cdf" or "percent point function".
Given random variable X and p in [0, 1], the quantile is:
View source
high - low.
View source
Generate samples of the specified shape.
Note that a call to sample() without arguments will generate a single sample.
View source
Standard deviation.
Standard deviation is defined as,
where X is the random variable associated with this distribution, E denotes expectation, and stddev.shape = batch_shape + event_shape.
View source
Survival function.
Given random variable X, the survival function is defined:
View source
Variance.
Variance is defined as,
where X is the random variable associated with this distribution, E denotes expectation, and Var.shape = batch_shape + event_shape.


Public API for tf.dtypes namespace.
class DType: Represents the type of the elements in a Tensor.
as_dtype(...): Converts the given type_value to a DType.
as_string(...): Converts each entry in the given tensor to strings.
cast(...): Casts a tensor to a new type.
complex(...): Converts two real numbers to a complex number.
saturate_cast(...): Performs a safe saturating cast of value to dtype.


Use control flow v2.
control flow v2 (cfv2) is an improved version of control flow in TensorFlow with support for higher order derivatives. Enabling cfv2 will change the graph/function representation of control flow, e.g., tf.while_loop and tf.cond will generate functional While and If ops instead of low-level Switch, Merge etc. ops. Note: Importing and running graphs exported with old control flow will still be supported.
Calling tf.enable_control_flow_v2() lets you opt-in to this TensorFlow 2.0 feature.


Enables eager execution for the lifetime of this program.
Eager execution provides an imperative interface to TensorFlow. With eager execution enabled, TensorFlow functions execute operations immediately (as opposed to adding to a graph to be executed later in a tf.compat.v1.Session) and return concrete values (as opposed to symbolic references to a node in a computational graph).
Eager execution cannot be enabled after TensorFlow APIs have been used to create or execute graphs. It is typically recommended to invoke this function at program startup and not in a library (as most libraries should be usable both with and without eager execution).


Creates resource variables by default.
Resource variables are improved versions of TensorFlow variables with a well-defined memory model. Accessing a resource variable reads its value, and all ops which access a specific read value of the variable are guaranteed to see the same value for that tensor. Writes which happen after a read (by having a control or data dependency on the read) are guaranteed not to affect the value of the read tensor, and similarly writes which happen before a read are guaranteed to affect the value. No guarantees are made about unordered read/write pairs.
Calling tf.enable_resource_variables() lets you opt-in to this TensorFlow 2.0 feature.


Compare Tensors with element-wise comparison and thus be unhashable.
Comparing tensors with element-wise allows comparisons such as tf.Variable(1.0) == 1.0. Element-wise equality implies that tensors are unhashable. Thus tensors can no longer be directly used in sets or as a key in a dictionary.


Enables TensorFlow 2.x behaviors.
This function can be called at the beginning of the program (before Tensors, Graphs or other structures have been created, and before devices have been initialized. It switches all global behaviors that are different between TensorFlow 1.x and 2.x to behave as intended for 2.x.
This function is called in the main TensorFlow __init__.py file, user should not need to call it, except during complex migrations.


In TensorFlow 2.0, iterating over a TensorShape instance returns values.
This enables the new behavior.
Concretely, tensor_shape[i] returned a Dimension instance in V1, but it V2 it returns either an integer, or None.


Exception types for TensorFlow errors.
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 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.
class raise_exception_on_not_ok_status: Context manager to check for C API status.
error_code_from_exception_type(...)
exception_type_from_error_code(...)


Context manager to check for C API status.
View source
View source


Estimator: High level tools for working with models.
experimental module: Public API for tf.estimator.experimental namespace.
export module: All public utility methods for exporting Estimator to SavedModel.
inputs module: Utility methods to create simple input_fns.
tpu module: Public API for tf.estimator.tpu namespace.
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.
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.


A classifier that can establish a simple baseline.
Inherits From: Estimator
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.
Input of train and evaluate should have following features, otherwise there will be a KeyError:
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.
View source
Shows the directory name where evaluation metrics are dumped.
View source
Evaluates the model given evaluation data input_fn.
For each step, calls input_fn, which returns one batch of data. Evaluates until:
View source
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'}.
View source
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.
View source
Exports inference graph as a SavedModel into the given dir. (deprecated)
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'}.
View source
Returns list of all variable names in this model.
View source
Returns value of the variable given by name.
View source
Finds the filename of the latest saved checkpoint file in model_dir.
View source
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: issue/20506
View source
Trains a model given training data input_fn.


An estimator that can establish a simple baseline.
Inherits From: Estimator
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.
Input of train and evaluate should have following features, otherwise there will be a KeyError:
View source
Shows the directory name where evaluation metrics are dumped.
View source
Evaluates the model given evaluation data input_fn.
For each step, calls input_fn, which returns one batch of data. Evaluates until:
View source
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'}.
View source
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.
View source
Exports inference graph as a SavedModel into the given dir. (deprecated)
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'}.
View source
Returns list of all variable names in this model.
View source
Returns value of the variable given by name.
View source
Finds the filename of the latest saved checkpoint file in model_dir.
View source
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: issue/20506
View source
Trains a model given training data input_fn.


A regressor that can establish a simple baseline.
Inherits From: Estimator
This regressor ignores feature values and will learn to predict the average value of each label.
Input of train and evaluate should have following features, otherwise there will be a KeyError:
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.
View source
Shows the directory name where evaluation metrics are dumped.
View source
Evaluates the model given evaluation data input_fn.
For each step, calls input_fn, which returns one batch of data. Evaluates until:
View source
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'}.
View source
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.
View source
Exports inference graph as a SavedModel into the given dir. (deprecated)
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'}.
View source
Returns list of all variable names in this model.
View source
Returns value of the variable given by name.
View source
Finds the filename of the latest saved checkpoint file in model_dir.
View source
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: issue/20506
View source
Trains a model given training data input_fn.


Generates parsing spec for tf.parse_example to be used with classifiers.
If users keep data in tf.Example format, they need to call tf.parse_example with a proper feature spec. There are two main things that this utility helps:
Example output of parsing spec:
Example usage with a classifier:


A classifier for TensorFlow DNN models.
Inherits From: Estimator
Input of train and evaluate should have following features, otherwise there will be a KeyError:
Loss is calculated by using softmax cross entropy.
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.
View source
Shows the directory name where evaluation metrics are dumped.
View source
Evaluates the model given evaluation data input_fn.
For each step, calls input_fn, which returns one batch of data. Evaluates until:
View source
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'}.
View source
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.
View source
Exports inference graph as a SavedModel into the given dir. (deprecated)
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'}.
View source
Returns list of all variable names in this model.
View source
Returns value of the variable given by name.
View source
Finds the filename of the latest saved checkpoint file in model_dir.
View source
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: issue/20506
View source
Trains a model given training data input_fn.


An estimator for TensorFlow DNN models with user-specified head.
Inherits From: Estimator
Input of train and evaluate should have following features, otherwise there will be a KeyError:
Loss and predicted output are determined by the specified head.
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.
View source
Shows the directory name where evaluation metrics are dumped.
View source
Evaluates the model given evaluation data input_fn.
For each step, calls input_fn, which returns one batch of data. Evaluates until:
View source
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'}.
View source
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.
View source
Exports inference graph as a SavedModel into the given dir. (deprecated)
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'}.
View source
Returns list of all variable names in this model.
View source
Returns value of the variable given by name.
View source
Finds the filename of the latest saved checkpoint file in model_dir.
View source
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: issue/20506
View source
Trains a model given training data input_fn.


An estimator for TensorFlow Linear and DNN joined classification models.
Inherits From: Estimator
Input of train and evaluate should have following features, otherwise there will be a KeyError:
Loss is calculated by using softmax cross entropy.
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.
View source
Shows the directory name where evaluation metrics are dumped.
View source
Evaluates the model given evaluation data input_fn.
For each step, calls input_fn, which returns one batch of data. Evaluates until:
View source
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'}.
View source
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.
View source
Exports inference graph as a SavedModel into the given dir. (deprecated)
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'}.
View source
Returns list of all variable names in this model.
View source
Returns value of the variable given by name.
View source
Finds the filename of the latest saved checkpoint file in model_dir.
View source
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: issue/20506
View source
Trains a model given training data input_fn.


An estimator for TensorFlow Linear and DNN joined models with custom head.
Inherits From: Estimator
Input of train and evaluate should have following features, otherwise there will be a KeyError:
Loss is calculated by using mean squared error.
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.
View source
Shows the directory name where evaluation metrics are dumped.
View source
Evaluates the model given evaluation data input_fn.
For each step, calls input_fn, which returns one batch of data. Evaluates until:
View source
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'}.
View source
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.
View source
Exports inference graph as a SavedModel into the given dir. (deprecated)
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'}.
View source
Returns list of all variable names in this model.
View source
Returns value of the variable given by name.
View source
Finds the filename of the latest saved checkpoint file in model_dir.
View source
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: issue/20506
View source
Trains a model given training data input_fn.


An estimator for TensorFlow Linear and DNN joined models for regression.
Inherits From: Estimator
Input of train and evaluate should have following features, otherwise there will be a KeyError:
Loss is calculated by using mean squared error.
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.
View source
Shows the directory name where evaluation metrics are dumped.
View source
Evaluates the model given evaluation data input_fn.
For each step, calls input_fn, which returns one batch of data. Evaluates until:
View source
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'}.
View source
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.
View source
Exports inference graph as a SavedModel into the given dir. (deprecated)
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'}.
View source
Returns list of all variable names in this model.
View source
Returns value of the variable given by name.
View source
Finds the filename of the latest saved checkpoint file in model_dir.
View source
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: issue/20506
View source
Trains a model given training data input_fn.