Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

API reference

TensorFlow API reference

TensorFlow deep learning

Identifiers
111
With full guides
98
Types
4

Topics covered

  • Tensors
  • Variables & autodiff
  • tf.data
  • Keras layers
  • Training loops
  • Models
  • Saving & loading
  • tf.function

Class

NameWhat it does
tf.Tensortf.Tensor is TensorFlow’s immutable, multidimensional array type. Its elements share one dtype, and the tensor carries a shape for use in eager or graph-based computation.
tf.Variabletf.Variable represents mutable TensorFlow state backed by a tensor. Its initial value establishes the variable's dtype and shape, and assign methods update its value.
Datasettf.data.Dataset represents a collection of elements and a pipeline of transformations. Build one from input data, transform it with operations such as map or batch, and iterate over the resulting elements.
GradientTapeClass
Sequentialtf.keras.Sequential groups an ordered, linear stack of Keras layers into a Model. It is designed for straightforward one-input, one-output layer pipelines.
DenseA fully connected neural-network layer that transforms the last input dimension into units. It can add a bias and apply an optional element-wise activation.
Conv2Dtf.keras.layers.Conv2D is a 2D convolution layer that learns spatial filters and produces a configurable number of output channels. Padding, strides, dilation, groups, bias, initialization, regularization, constraints, and activation control its behavior.
layers.DenseA standard fully connected neural-network layer. It applies a learned affine projection to the final input dimension and then an optional activation, producing the requested number of output units.
layers.Conv2DA Keras layer that applies learned two-dimensional convolution filters to inputs. It can add bias and an activation while configurable padding, strides, dilation, layout, and groups determine the resulting feature maps.
layers.Conv1DA Keras layer that performs one-dimensional convolution over spatial or temporal sequences. It transforms sliding input windows into a configurable number of output channels.
layers.MaxPooling2DMaxPooling2D downsamples 2D spatial data by taking the maximum in sliding windows independently for each channel. Configure its window, stride, padding mode, and tensor data layout.
layers.AveragePooling2DAveragePooling2D downsamples 2D spatial data by taking windowed means independently for each channel. Its pool size, stride, padding, and channel layout determine the resulting feature-map dimensions.
layers.GlobalAveragePooling2DA Keras layer that averages each channel across the height and width of 2D feature maps. It can either remove those spatial axes or preserve them as size-one dimensions.
layers.Flattentf.keras.layers.Flatten turns each sample’s non-batch dimensions into one feature axis. It preserves the batch size and supports channels-last or channels-first dimension ordering.
layers.DropoutApplies dropout regularization by randomly zeroing input units during training and rescaling the units that remain. During inference, it leaves the input unchanged.
layers.BatchNormalizationBatchNormalization normalizes layer inputs toward zero mean and unit standard deviation. It uses current-batch statistics during training and moving statistics during inference.
layers.LayerNormalizationtf.keras.layers.LayerNormalization normalizes activations independently for each example across selected axes, typically the feature axis. It can optionally apply trainable scaling and centering after normalization.
layers.LSTMA Long Short-Term Memory layer for processing sequence data. It can return the final output, the full output sequence, and optionally its recurrent states.
layers.GRUtf.keras.layers.GRU is a gated recurrent layer for sequence data. It can return the final timestep output or the complete output sequence, and can optionally expose its recurrent state.
layers.SimpleRNNtf.keras.layers.SimpleRNN is a fully connected recurrent layer that feeds each output back into the next timestep. It can emit the final output, the full sequence, and optionally the final recurrent state.
layers.BidirectionalClass
layers.EmbeddingClass
layers.AttentionA Keras layer implementing Luong-style attention. It scores query-key pairs, normalizes them with softmax, and returns weighted value combinations.
layers.MultiHeadAttentionClass
layers.ConcatenateClass
layers.Addtf.keras.layers.Add performs elementwise addition over a list of same-shaped tensors and returns one tensor with that shape. It is commonly used to merge branches in a Keras model.
layers.ActivationA Keras layer that applies a chosen activation function to its input. The activation can be specified by supported name or passed as a callable.
layers.ReLUA configurable Keras layer implementing rectified linear activation. Adjust its slope, threshold, and optional upper bound to obtain standard, leaky, thresholded, or capped ReLU behavior.
layers.SoftmaxA Keras layer that converts logits into normalized softmax probabilities. It defaults to the last axis and can optionally ignore masked positions.
layers.Reshapetf.keras.layers.Reshape changes each input sample to a specified target shape while preserving the batch dimension. It requires fixed input dimensions and can infer one target dimension with -1.
layers.TextVectorizationA Keras preprocessing layer that turns batches of strings into token IDs or dense text vectors. It can learn its vocabulary from data with adapt() or use one supplied at construction.
layers.NormalizationA Keras preprocessing layer that standardizes continuous features using stored mean and variance. Statistics can be supplied at construction or learned with adapt().
keras.Modeltf.keras.Model groups layers into a callable object with training and inference features. Create it with the Functional API or by subclassing it.
keras.Sequentialtf.keras.Sequential creates a Model from a linear stack of Keras layers. Layers can be supplied at construction or appended incrementally with add().
optimizers.AdamAdam is a Keras optimizer that adaptively estimates first- and second-order gradient moments to update model variables. Its API includes controls for learning rates, AMSGrad, decay, clipping, moving averages, loss scaling, and gradient accumulation.
optimizers.SGDtf.keras.optimizers.SGD performs gradient descent with an optional momentum accumulator. It supports configurable learning rates, Nesterov momentum, gradient clipping, weight decay, EMA, and gradient accumulation.
optimizers.RMSpropTensorFlow's RMSprop optimizer adapts parameter updates using a discounted moving average of squared gradients. It supports momentum, centered variance normalization, clipping, weight decay, EMA, and gradient accumulation.
optimizers.AdamWAdamW is a Keras optimizer that combines Adam’s adaptive moment estimation with weight decay. It supports configurable learning rates, moment coefficients, clipping, EMA, loss scaling, and gradient accumulation.
optimizers.NadamNadam is a Keras optimizer that combines Adam-style adaptive moment estimates with Nesterov momentum. It also supports clipping, weight decay, EMA, loss scaling, and gradient accumulation.
losses.BinaryCrossentropyBinaryCrossentropy is a Keras loss class for binary classification. It compares binary targets with predicted probabilities or logits and supports label smoothing, axis selection, and configurable reduction.
losses.CategoricalCrossentropyComputes categorical crossentropy between one-hot labels and predictions for multiclass classification. Predictions may be probabilities or logits, with optional label smoothing, feature-axis selection, and configurable reduction.
losses.SparseCategoricalCrossentropyClass
losses.MeanSquaredErrorComputes the average squared difference between labels and predictions. It is a configurable Keras Loss object with selectable reduction behavior.
losses.Hubertf.keras.losses.Huber computes a robust regression loss between true and predicted values. It uses a quadratic penalty for small errors and a linear penalty for errors beyond delta.
metrics.AccuracyCalculates how often predictions equal labels. It accumulates matches and evaluated values across updates, then returns their ratio.
metrics.PrecisionComputes the fraction of predicted positives that are correct. It supports threshold-based binary evaluation, top-k multiclass evaluation, and restricting measurement to one class.
metrics.RecallComputes recall from accumulated true positives and false negatives. It supports threshold-based, top-k, and class-specific evaluation.
metrics.AUCA stateful Keras metric that approximates ROC AUC or precision-recall AUC from predictions accumulated across batches. It supports configurable thresholds, summation, multilabel evaluation, label weighting, and logits.
tf.GradientTapeRecords operations performed in a context so TensorFlow can compute gradients automatically. It watches trainable variables by default and supports manual watching, persistent tapes, and higher-order derivatives.
tf.data.Datasettf.data.Dataset represents a potentially large sequence of elements and provides composable operations for building TensorFlow input pipelines. Data is commonly sourced, transformed, and then consumed by iteration.
callbacks.EarlyStoppingStops Keras training when a monitored metric no longer improves. It can require a minimum improvement, tolerate a configured number of stalled epochs, use a baseline or warm-up period, and restore the best weights.
callbacks.ModelCheckpointClass
callbacks.ReduceLROnPlateauClass
callbacks.TensorBoardLogs Keras training information for visualization in TensorBoard. It can record metrics, the graph, weight histograms, throughput, profiling data, and embeddings.
callbacks.LearningRateSchedulerA Keras callback that changes the optimizer's learning rate from a user-supplied function. The function is evaluated at the start of each epoch using the epoch index and current rate.
layers.LSTMCellAn LSTM cell that performs one timestep of recurrent computation. Wrap it in keras.layers.RNN to apply it across complete input sequences.
layers.GRUCelltf.keras.layers.GRUCell implements one timestep of a gated recurrent unit. Wrap it with tf.keras.layers.RNN when a sequence-level recurrent layer is needed.
layers.Conv2DTransposeClass
layers.DepthwiseConv2DClass
layers.GlobalMaxPooling2DGlobalMaxPooling2D reduces each 2D feature map to its maximum value, retaining one value per channel and batch item. Use data_format to select channel ordering and keepdims to preserve singleton spatial axes.
layers.SpatialDropout2DSpatialDropout2D regularizes convolutional feature maps by dropping complete 2D maps instead of individual elements. It is designed for inputs whose neighboring pixels are strongly correlated.
layers.GaussianNoiseA Keras regularization layer that adds zero-centered Gaussian noise to inputs during training. It can help mitigate overfitting, while inference leaves the input unchanged.
layers.RandomFlipA Keras preprocessing layer that randomly flips channels-last images horizontally, vertically, or both during training. It leaves images unchanged during inference and supports integer or floating-point pixel inputs.
layers.ResizingA Keras preprocessing layer that resizes individual images or batches to a chosen height and width. It supports several interpolation methods and optional aspect-ratio-preserving cropping or padding.
layers.RescalingA Keras preprocessing layer that converts every input value with input * scale + offset. It is commonly used to normalize image pixels, such as mapping [0, 255] to [0, 1] or [-1, 1].

Function

NameWhat it does
tf.constantCreates a TensorFlow tensor from a tensor-like value, optionally choosing its dtype and shape. Python-side values are embedded as constants during graph construction; eager tensors remain immutable.
tf.matmulMultiplies two tensors as matrices, using their final two dimensions and matching outer batch dimensions. Optional flags can transpose or take adjoints of either input.
tf.reduce_meantf.reduce_mean computes averages across selected tensor dimensions. It reduces all dimensions by default and can preserve reduced axes as length-one dimensions.
keras.InputCreates a symbolic Keras tensor that starts a Functional API graph. Specify sample shape, dtype, batching, sparsity, and optionally a name or existing tensor.
keras.models.load_modelLoads a Keras model saved with model.save() and returns a Keras model instance. It can restore compilation and deserialize custom objects, while safe_mode controls unsafe lambda loading.
tf.zerosCreates a tensor with a specified shape whose elements are all zero. The output dtype defaults to float32 and can be changed with dtype.
tf.onesCreates a tensor of a specified shape whose elements are all one. The element type defaults to tf.float32 and can be selected with dtype.
tf.reshapetf.reshape returns a tensor with a requested shape while preserving all values and their order. The total number of elements must stay unchanged; one shape dimension may be inferred with -1.
tf.concatConcatenates tensors along an existing dimension. Inputs must match in rank and in every dimension except the selected axis.
tf.stackStacks equally shaped tensors along a new axis, producing a tensor whose rank is one greater than each input. The axis determines where the new dimension is inserted.
tf.reduce_sumComputes sums across selected tensor dimensions. By default it reduces all dimensions and returns a one-element tensor; keepdims preserves reduced dimensions as size-one axes.
tf.expand_dimsInserts a length-1 axis into a tensor at a chosen position. It uses zero-based Python indexing, with negative axes counted from the end.
tf.squeezeRemoves dimensions of size 1 from a tensor. By default it removes every singleton dimension, or only the selected singleton dimensions when axis is supplied.
tf.castCasts a tensor to a new numeric dtype. It supports dense, sparse, and indexed-slice inputs while preserving their shape and structure.
tf.transposeTransposes a Tensor by permuting its dimensions. By default, it reverses all dimensions; for complex64 or complex128 inputs, conjugate=True also applies complex conjugation.
tf.gatherSelects slices from a tensor along a chosen axis using integer indices. It supports arbitrary tensor ranks, negative axes, and batch-specific lookups.
tf.whereReturns nonzero-element coordinates, or selects element values from x and y using condition as a mask. The function supports broadcasting across the condition and both branches.
tf.convert_to_tensorConverts supported Python and array-like values into a Tensor. The element type is inferred unless dtype is supplied, while dtype_hint provides a fallback preference.
tf.einsumtf.einsum performs tensor contractions and outer products from a compact Einstein-summation equation. Repeated labels can be summed, while explicit output labels determine the result's axes and order.
tf.argmaxReturns the index of the largest value along a selected tensor axis. It is useful for converting model scores into winning class or item indices.
tf.nn.reluComputes the rectified-linear activation, replacing negative tensor elements with zero and leaving nonnegative elements unchanged. The result has the same dtype as the input.
tf.nn.softmaxComputes softmax activations by converting logits into normalized values along a selected axis. The result has the same shape and type as the input, with each normalized slice summing to one.
tf.splitSplits a tensor along a chosen dimension and returns the pieces as a list. Use an integer for equal-sized outputs or provide explicit sizes for uneven outputs.
tf.tileConstructs a new tensor by repeating an input along each dimension. The repetitions are specified by the corresponding entries in multiples.
tf.padtf.pad adds values before and after each tensor dimension according to [before, after] pairs. It supports CONSTANT, REFLECT, and SYMMETRIC modes and returns a tensor with the input's type.
tf.clip_by_valueClips tensor values to an inclusive minimum and maximum. It preserves the input's shape and type while replacing out-of-range elements with the relevant bound.
tf.one_hotReturns a one-hot tensor by expanding each integer index into a vector of length depth. The selected position uses on_value and all other positions use off_value.
tf.rangeCreates a one-dimensional Tensor containing a numeric sequence from start toward, but excluding, limit. The step is delta, and TensorFlow infers the result dtype unless dtype is specified.
tf.linspaceGenerates a tensor of evenly spaced values between start and stop along a chosen axis. For more than one value, the sequence ends exactly at stop.
tf.keras.utils.to_categoricalConverts integer class labels into a binary class matrix. The class count can be supplied explicitly or inferred from the largest label.

Decorator

NameWhat it does
tf.functionCompiles a Python function into a callable TensorFlow graph. The returned polymorphic callable can dispatch among specialized concrete graphs for different argument types or shapes.

Module

NameWhat it does
tf.kerastf.keras is TensorFlow's high-level API for building and using deep-learning models. It combines reusable layers and models with workflows for data processing, training, evaluation, tuning, and deployment.
tf.nnModule
tf.optimizersModule
model.compileConfigures a Keras model for training by specifying its optimizer, loss, and metrics. Optional settings control weighting, execution mode, batches per function call, XLA compilation, and mixed-precision loss scaling.
model.fitTrains a compiled Keras model for a chosen number of epochs using arrays, tensors, or dataset-like inputs. It supports batching, validation, weighting, callbacks, shuffling, and resuming training.
model.evaluateEvaluates a compiled Keras model in test mode on supplied data. It returns the configured loss and metric results, either as a list or as a name-keyed dictionary.
model.predictGenerates predictions for input samples using batch processing. For small inputs that fit in one batch, directly calling the model is faster.
model.saveModule
model.summarytf.summary provides TensorFlow’s public API for writing training and evaluation summaries. It includes writers and functions for recording values such as scalars, images, histograms, and text.
Dataset.from_tensor_slicesCreates a Dataset by slicing supplied tensors along their first dimension. Each resulting element preserves the input structure and contains one corresponding slice.
Dataset.batchDataset.batch groups consecutive dataset elements into batches, adding an outer dimension to each component. It can retain or discard a smaller final batch, while variable-shaped tensors require padded_batch.
Dataset.shuffleRandomly shuffles dataset elements using a finite sampling buffer. A buffer at least as large as the dataset is needed for perfect shuffling, while smaller buffers use less memory but provide less thorough mixing.
Dataset.mapApplies a function to every element of a TensorFlow dataset and returns a new dataset of transformed elements. It can also change element structure and optionally process elements in parallel.
Dataset.prefetchDataset.prefetch buffers upcoming dataset elements so they can be prepared while current elements are processed. It can improve pipeline latency and throughput, with additional memory use; tf.data.AUTOTUNE can tune the buffer size.
Dataset.repeattf.data.Dataset.repeat repeats a dataset’s elements for a specified number of traversals. With no count or -1, it produces an indefinitely repeating dataset.

Search across every package and filter by type in your dashboard.

Start learning