Adam Optimizer in Tensorflow
Last Updated :
10 Mar, 2025
Adam (Adaptive Moment Estimation) is an optimizer that combines the best features of two well-known optimizers: Momentum and RMSprop. Adam is used in deep learning due to its efficiency and adaptive learning rate capabilities.
To use Adam in TensorFlow, we can pass the string value 'adam' to the optimizer argument of the model.compile() function. Here's a simple example of how to do this:
model.compile(optimizer="adam")
This method passes the Adam optimizer object to the function with default values for parameters like betas and learning rate. Alternatively, we can use the Adam class provided in tf.keras.optimizers. Below is the syntax for using the Adam class directly:
Adam(learning_rate, beta_1, beta_2, epsilon, amsgrad, name)
Here is a description of the parameters in the Adam optimizer:
- learning_rate: The learning rate to use in the algorithm (default value: 0.001).
- beta_1: The exponential decay rate for the 1st moment estimates (default value: 0.9).
- beta_2: The exponential decay rate for the 2nd moment estimates (default value: 0.999).
- epsilon: A small constant for numerical stability (default value: 1e-7).
- amsgrad: A boolean flag to specify whether to apply the AMSGrad variant (default value: False).
- name: Optional name for the operations created when applying gradients (default value: 'Adam').
Using Adam Optimizer in TensorFlow
Let's now look at an example where we will create a simple neural network model using TensorFlow and compile it using the Adam optimizer.
Create the Model
We will create a simple neural network with 2 Dense layers for demonstration.
Python
import tensorflow as tf
def createModel(input_shape):
X_input = tf.keras.layers.Input(input_shape)
X = tf.keras.layers.Dense(10, activation='relu')(X_input)
X_output = tf.keras.layers.Dense(2, activation='softmax')(X)
model = tf.keras.Model(inputs=X_input, outputs=X_output)
return model
Now, we will create an instance of this model and print the summary to inspect the architecture.
Python
# Create the model
model = createModel((10, 10))
# Print the model summary
print(model.summary())
Output:

Check Initial Weights
Before training the model, let's print out the initial weights for the layers.
Python
print('Initial Layer Weights')
for i in range(1, len(model.layers)):
print(f'Weight for Layer {i}:')
print(model.layers[i].get_weights()[0])
print()
Output:

Generate Dummy Data
For this example, we will generate random data to train the model.
Python
tf.random.set_seed(5)
# Generate dummy data
X = tf.random.normal((2, 10, 10))
Y = tf.random.normal((2, 10, 2))
Compile the Model
Now, we compile the model using the Adam optimizer, the categorical cross-entropy loss function, and accuracy as the evaluation metric.
Python
# Compile the model with Adam optimizer
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Print optimizer configuration
print(model.optimizer.get_config())
Output:
{'name': 'adam', 'learning_rate': 0.0010000000474974513, 'weight_decay': None, 'clipnorm': None, 'global_clipnorm': None, 'clipvalue': None, 'use_ema': False, 'ema_momentum': 0.99, 'ema_overwrite_frequency': None, 'loss_scale_factor': None, 'gradient_accumulation_steps': None, 'beta_1': 0.9, 'beta_2': 0.999, 'epsilon': 1e-07, 'amsgrad': False}
The output shows the default configuration of the Adam Optimizer. Now, let's train the model using the dummy data we generated and check the weights of the model after training.
Python
# Train the model with the dummy data
model.fit(X, Y)
print('Final Layer Weights')
for i in range(1, len(model.layers)):
print(f'Weight for Layer {i}:')
print(model.layers[i].get_weights()[0])
print()
Output:

The output shows how well the model is performing on the training data, based on the loss and accuracy, and also allows you to observe how the model's weights have changed as a result of the training process.
By understanding how Adam works and using it effectively in TensorFlow, you can improve the performance and speed of training for various machine learning tasks.
Similar Reads
Optimizers in Tensorflow
Optimizers adjust weights of the model based on the gradient of loss function, aiming to minimize the loss and improve model accuracy. In TensorFlow, optimizers are available through tf.keras.optimizers. You can use these optimizers in your models by specifying them when compiling the model. Here's
3 min read
What is Adam Optimizer?
Adam (short for Adaptive Moment Estimation) optimizer combines the strengths of two other well-known techniquesâMomentum and RMSpropâto deliver a powerful method for adjusting the learning rates of parameters during training. Adam is highly effective, especially when working with large datasets and
4 min read
Tensorflow.js tf.train.Optimizer Class
Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. The tf.train.Optimizer() class is used to extend Serializable class. This tf.train.Optimizer() class contains three inbuilt functions
3 min read
TensorFlow Model Optimization
The field of machine learning has made incredible progress in recent years, with deep learning models providing impressive results in a variety of industries but applying these models to real-world applications is demanding that they work efficiently and quickly that's why speed is important. Becaus
6 min read
Gradient Descent Optimization in Tensorflow
Gradient descent is an optimization algorithm used to find the values of parameters (coefficients) of a function (f) that minimizes a cost function. In other words, gradient descent is an iterative algorithm that helps to find the optimal solution to a given problem.In this blog, we will discuss gra
15+ min read
model.evaluate() in TensorFlow
The model.evaluate() function in TensorFlow is used to evaluate a trained model on a given dataset. It returns the loss value and any additional metrics specified during model compilation. model.evaluate() function allows us to assess how well the trained model generalizes to unseen data.Syntax of m
2 min read
model.fit() in TensorFlow
In TensorFlow,model.fit() function is used to train a machine learning model for a fixed number of epochs (iterations over the entire dataset). During training, the model adjusts its internal parameters (weights and biases) to minimize the loss function using optimization techniques like Gradient De
3 min read
Custom Optimizers in Pytorch
In PyTorch, an optimizer is a specific implementation of the optimization algorithm that is used to update the parameters of a neural network. The optimizer updates the parameters in such a way that the loss of the neural network is minimized. PyTorch provides various built-in optimizers such as SGD
11 min read
Python | Tensorflow nn.sigmoid()
Tensorflow is an open-source machine learning library developed by Google. One of its applications is to develop deep neural networks. The module tensorflow.nn provides support for many basic neural network operations.One of the many activation functions is the sigmoid function which is defined as f
3 min read
TensorArray in TensorFlow
In TensorFlow, a tensor is a multi-dimensional array or data structure representing data. It's the fundamental building block of TensorFlow computations. A tensor can be a scalar (0-D tensor), a vector (1-D tensor), a matrix (2-D tensor), or it can have higher dimensions. In this article, we are goi
6 min read