The Wayback Machine - https://web.archive.org/web/20240927014430/https://www.geeksforgeeks.org/gradient-descent-optimization-in-tensorflow/
Open In App

Gradient Descent Optimization in Tensorflow

Last Updated : 15 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 gradient descent optimization in TensorFlow, a popular deep-learning framework. TensorFlow provides several optimizers that implement different variations of gradient descent, such as stochastic gradient descent and mini-batch gradient descent.

Before diving into the details of gradient descent in TensorFlow, let’s first understand the basics of gradient descent and how it works.

What is Gradient Descent?

Gradient descent is an iterative optimization algorithm that is used to minimize a function by iteratively moving in the direction of the steepest descent as defined by the negative of the gradient. In other words, the gradient descent algorithm takes small steps in the direction opposite to the gradient of the function at the current point, with the goal of reaching a global minimum.

The gradient of a function tells us the direction in which the function is increasing or decreasing the most. For example, if the gradient of a function is positive at a certain point, it means that the function is increasing at that point, and if the gradient is negative, it means that the function is decreasing at that point.

The gradient descent algorithm starts with an initial guess for the parameters of the function and then iteratively improves these guesses by taking small steps in the direction opposite to the gradient of the function at the current point. This process continues until the algorithm reaches a local or global minimum, where the gradient is zero (i.e., the function is not increasing or decreasing).

How does Gradient Descent work?

The gradient descent algorithm is an iterative algorithm that updates the parameters of a function by taking steps in the opposite direction of the gradient of the function. The gradient of a function tells us the direction in which the function is increasing or decreasing the most. The gradient descent algorithm uses the gradient to update the parameters in the direction that reduces the value of the cost function.

The gradient descent algorithm works in the following way:

  1. Initialize the parameters of the function with some random values.
  2. Calculate the gradient of the cost function with respect to the parameters.
  3. Update the parameters by taking a small step in the opposite direction of the gradient.
  4. Repeat steps 2 and 3 until the algorithm reaches a local or global minimum, where the gradient is zero.
  5. Here is a simple example to illustrate the gradient descent algorithm in action. Let’s say we have a function f(x) = x2, and we want to find the value of x that minimizes the function. We can use the gradient descent algorithm to find this value.

First, we initialize the value of x with some random value, say x = 3. Next, we calculate the gradient of the function with respect to x, which is 2x. In this case, the gradient is 6 (2 * 3). Since the gradient is positive, it means that the function is increasing at x = 3, and we need to take a step in the opposite direction to reduce the value of the function.

We update the value of x by subtracting a small step size (called the learning rate) from the current value of x. For example, if the learning rate is 0.1, we can update the value of x as follows:

x = x - 0.1 * gradient
= 3 - 0.1 * 6
= 2.4

We repeat this process until the algorithm reaches a local or global minimum. To implement gradient descent in TensorFlow, we first need to define the cost function that we want to minimize. In this example, we will use a simple linear regression model to illustrate how gradient descent works.

Linear regression is a popular machine learning algorithm that is used to model the relationship between a dependent variable (y) and one or more independent variables (x). In a linear regression model, we try to find the best-fit line that describes the relationship between the dependent and independent variables. To create a linear regression model in TensorFlow, we first need to define the placeholders for the input and output data. A placeholder is a TensorFlow variable that we can use to feed data into our model.

Here is the code to define the placeholders for the input and output data:

Python

# Import tensorflow 2 as tensorflow 1 import tensorflow.compat.v1 as tf tf.disable_v2_behavior() # Define the placeholders for # the input and output data x = tf.placeholder(tf.float32) y = tf.placeholder(tf.float32) # Define the placeholders for # the input and output data x = tf.placeholder(tf.float32) y = tf.placeholder(tf.float32)

Next, we need to define the variables that represent the parameters of our linear regression model. In this example, we will use a single variable (w) to represent the slope of the best-fit line. We initialize the value of w with a random value, say 0.5.

Here is the code to define the variable for the model parameters:

Python

# Define the model parameters w = tf.Variable(0.5, name="weights")

Once we have defined the placeholders and the model parameters, we can define the linear regression model by using the TensorFlow tf.add() and tf.multiply() functions. The tf.add() function is used to add the bias term to the model, and the tf.multiply() function is used to multiply the input data (x) and the model parameters (w).

Here is the code to define the linear regression model:

Python

# Define the linear regression model model = tf.add(tf.multiply(x, w), 0.5)

Once we have defined the linear regression model, we need to define the cost function that we want to minimize. In this example, we will use the mean squared error (MSE) as the cost function. The MSE is a popular metric that is used to evaluate the performance of a linear regression model. It measures the average squared difference between the predicted values and the actual values.

To define the cost function, we first need to calculate the difference between the predicted values and the actual values using the TensorFlow tf.square() function. The tf.square() function squares each element in the input tensor and returns the squared values.

Here is the code to define the cost function using the MSE:

Python

# Define the cost function (MSE) cost = tf.reduce_mean(tf.square(model - y))

Once we have defined the cost function, we can use the TensorFlow tf.train.GradientDescentOptimizer() function to create an optimizer that uses the gradient descent algorithm to minimize the cost function. The tf.train.GradientDescentOptimizer() function takes the learning rate as an input parameter. The learning rate is a hyperparameter that determines the size of the steps that the algorithm takes to reach the minimum of the cost function.

Here is the code to create the gradient descent optimizer:

Python

# Create the gradient descent optimizer optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)

Once we have defined the optimizer, we can use the minimize() method of the optimizer to minimize the cost function. The minimize() method takes the cost function as an input parameter and returns an operation that, when executed, performs one step of gradient descent on the cost function.

Here is the code to minimize the cost function using the gradient descent optimizer:

Python

# Minimize the cost function train = optimizer.minimize(cost)

Once we have defined the gradient descent optimizer and the train operation, we can use the TensorFlow Session class to train our model. The Session class provides a way to execute TensorFlow operations. To train the model, we need to initialize the variables that we have defined earlier (i.e., the model parameters and the optimizer) and then run the train operation in a loop for a specified number of iterations.

Here is the code to train the linear regression model using the gradient descent optimizer:

Python

# Define the toy dataset x_train = [1, 2, 3, 4] y_train = [2, 4, 6, 8] # Create a TensorFlow session with tf.Session() as sess: # Initialize the variables sess.run(tf.global_variables_initializer()) # Training loop for i in range(1000): sess.run(train, feed_dict={x: x_train, y: y_train}) # Evaluate the model w_val = sess.run(w) # Mean Squared Error (MSE) between # the predicted and true output values print(w_val)

In the above code, we have defined a Session object and used the global_variables_initializer() method to initialize the variables. Next, we have run the train operation in a loop for 1000 iterations. In each iteration, we have fed the input and output data to the train operation using the feed_dict parameter. Finally, we evaluated the trained model by running the w variable to get the value of the model parameters. This will train a linear regression model on the toy dataset using gradient descent. The model will learn the weights w that minimizes the mean squared error between the predicted and true output values.

Visualizing the convergence of Gradient Descent using Linear Regression

Linear regression is a method for modeling the linear relationship between a dependent variable (also known as the response or output variable) and one or more independent variables (also known as the predictor or input variables). The goal of linear regression is to find the values of the model parameters (coefficients) that minimize the difference between the predicted values and the true values of the dependent variable.

The linear regression model can be expressed as follows:

[Tex]\hat{y} = w_1 x_1 + w_2 x_2 + \text{. . .} + w_n x_n + b[/Tex]

where:

  • [Tex]\hat{y}   [/Tex] is the predicted value of the dependent variable
  • [Tex]x_1, x_2, \text{…}, x_n [/Tex] are the independent variables [Tex]w_1, w_2, \text{…}, w_n [/Tex] are the coefficients (model parameters) associated with the independent variables.
  • b is the intercept (a constant term).

To train the linear regression model, you need a dataset with input features (independent variables) and labels (dependent variables). You can then use an optimization algorithm, such as gradient descent, to find the values of the model parameters that minimize the loss function.

The loss function measures the difference between the predicted values and the true values of the dependent variable. There are various loss functions that can be used for linear regression, such as mean squared error (MSE) and mean absolute error (MAE). The MSE loss function is defined as follows:

[Tex]\text{MSE} = \frac{1}{N} \sum_{i=1}^N (\hat{y_i} – y_i)^2[/Tex]

where:

  • [Tex]\hat{y_i}   [/Tex] is the predicted value for the [Tex]i [/Tex]th sample
  • [Tex]y_i [/Tex] is the true value for the [Tex]i [/Tex]th sample
  • N   is the total number of samples
  • The MSE loss function measures the average squared difference between the predicted values and the true values. A lower MSE value indicates that the model is performing better.
Python

import tensorflow as tf import matplotlib.pyplot as plt # Set up the data and model X = tf.constant([[1.], [2.], [3.], [4.]]) y = tf.constant([[2.], [4.], [6.], [8.]]) w = tf.Variable(0.) b = tf.Variable(0.) # Define the model and loss function def model(x): return w * x + b def loss(predicted_y, true_y): return tf.reduce_mean(tf.square(predicted_y - true_y)) # Set the learning rate learning_rate = 0.001 # Training loop losses = [] for i in range(250): with tf.GradientTape() as tape: predicted_y = model(X) current_loss = loss(predicted_y, y) gradients = tape.gradient(current_loss, [w, b]) w.assign_sub(learning_rate * gradients[0]) b.assign_sub(learning_rate * gradients[1]) losses.append(current_loss.numpy()) # Plot the loss plt.plot(losses) plt.xlabel("Iteration") plt.ylabel("Loss") plt.show()

Output:

Loss vs Iteration

The loss function calculates the mean squared error (MSE) loss between the predicted values and the true labels. The model function defines the linear regression model, which is a linear function of the form [Tex]w * x + b [/Tex].

The training loop performs 250 iterations of gradient descent. At each iteration, the with tf.GradientTape() as tape: block activates the gradient tape, which records the operations for computing the gradients of the loss with respect to the model parameters.

Inside the block, the predicted values are calculated using the model function and the current values of the model parameters. The loss is then calculated using the loss function and the predicted values and true labels.

After the loss has been calculated, the gradients of the loss with respect to the model parameters are computed using the gradient method of the gradient tape. The model parameters are then updated by subtracting the learning rate multiplied by the gradients from the current values of the parameters. This process is repeated until the training loop is completed.

Finally, the model parameters will contain the optimized values that minimize the loss function, and the model will be trained to predict the dependent variable given the independent variables.

A list called losses store the loss at each iteration. After the training loop is completed, the losses list contains the loss values at each iteration.

The plt.plot function plots the losses list as a function of the iteration number, which is simply the index of the loss in the list. The plt.xlabel and plt.ylabel functions add labels to the x-axis and y-axis of the plot, respectively. Finally, the plt.show function displays the plot.

The resulting plot shows how the loss changes over the course of the training process. As the model is trained, the loss should decrease, indicating that the model is learning and the model parameters are being optimized to minimize the loss. Eventually, the loss should converge to a minimum value, indicating that the model has reached a good solution. The rate at which the loss decreases and the final value of the loss will depend on various factors, such as the learning rate, the initial values of the model parameters, and the complexity of the model.

Visualizing the Gradient Descent

Gradient descent is an optimization algorithm that is used to find the values of the model parameters that minimize the loss function. The algorithm works by starting with initial values for the parameters and then iteratively updating the values to minimize the loss.

The equation for the gradient descent algorithm for linear regression can be written as follows:

[Tex]w_i = w_i – \alpha \frac{\partial}{\partial w_i} \text{MSE}(w_1, w_2, \text{…}, w_n)[/Tex]

[Tex]b = b – \alpha \frac{\partial}{\partial b} \text{MSE}(w_1, w_2, \text{…}, w_n)[/Tex]

where:

  • w_i  is the ith model parameter.
  • [Tex]\alpha [/Tex] is the learning rate (a hyperparameter that determines the step size of the update).
  • [Tex]\frac{\partial}{\partial w_i} \text{MSE}(w_1, w_2, \text{…}, w_n) [/Tex] is the partial derivative of the MSE loss function with respect to the ith model parameter.

This equation updates the value of each parameter in the direction that reduces the loss. The learning rate determines the size of the update, with a smaller learning rate resulting in smaller steps and a larger learning rate resulting in larger steps.

The process of performing gradient descent can be visualized as taking small steps downhill on a loss surface, with the goal of reaching the global minimum of the loss function. The global minimum is the point on the loss surface where the loss is the lowest.

Here is an example of how to plot the loss surface and the trajectory of the gradient descent algorithm:

Python

import numpy as np import matplotlib.pyplot as plt # Generate synthetic data np.random.seed(42) X = 2 * np.random.rand(100, 1) - 1 y = 4 + 3 * X + np.random.randn(100, 1) # Initialize model parameters w = np.random.randn(2, 1) b = np.random.randn(1)[0] # Set the learning rate alpha = 0.1 # Set the number of iterations num_iterations = 20 # Create a mesh to plot the loss surface w1, w2 = np.meshgrid(np.linspace(-5, 5, 100), np.linspace(-5, 5, 100)) # Compute the loss for each point on the grid loss = np.zeros_like(w1) for i in range(w1.shape[0]): for j in range(w1.shape[1]): loss[i, j] = np.mean((y - w1[i, j] \ * X - w2[i, j] * X**2)**2) # Perform gradient descent for i in range(num_iterations): # Compute the gradient of the loss # with respect to the model parameters grad_w1 = -2 * np.mean(X * (y - w[0] \ * X - w[1] * X**2)) grad_w2 = -2 * np.mean(X**2 * (y - w[0] \ * X - w[1] * X**2)) # Update the model parameters w[0] -= alpha * grad_w1 w[1] -= alpha * grad_w2 # Plot the loss surface fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(projection='3d') ax.plot_surface(w1, w2, loss, cmap='coolwarm') ax.set_xlabel('w1') ax.set_ylabel('w2') ax.set_zlabel('Loss') # Plot the trajectory of the gradient descent algorithm ax.plot(w[0], w[1], np.mean((y - w[0]\ * X - w[1] * X**2)**2), 'o', c='red', markersize=10) plt.show()

Output:

Gradient Descent finding global minima

Gradient Descent finding global minima

This code generates synthetic data for a quadratic regression problem, initializes the model parameters, and performs gradient descent to find the values of the model parameters that minimize the mean squared error loss. The code also plots the loss surface and the trajectory of the gradient descent algorithm on the loss surface.

The resulting plot shows how the gradient descent algorithm takes small steps downhill on the loss surface and eventually reaches the global minimum of the loss function. The global minimum is the point on the loss surface where the loss is the lowest.

It is important to choose an appropriate learning rate for the gradient descent algorithm. If the learning rate is too small, the algorithm will take a long time to converge to the global minimum. On the other hand, if the learning rate is too large, the algorithm may overshoot the global minimum and may not converge to a good solution.

Another important consideration is the initialization of the model parameters. If the initialization is too far from the global minimum, the gradient descent algorithm may take a long time to converge. It is often helpful to initialize the model parameters to small random values.

It is also important to choose an appropriate stopping criterion for the gradient descent algorithm. One common stopping criterion is to stop the algorithm when the loss function stops improving or when the improvement is below a certain threshold. Another option is to stop the algorithm after a fixed number of iterations.

Overall, gradient descent is a powerful optimization algorithm that can be used to find the values of the model parameters that minimize the loss function for a wide range of machine learning problems.

Conclusion

In this blog, we have discussed gradient descent optimization in TensorFlow and how to implement it to train a linear regression model. We have seen that TensorFlow provides several optimizers that implement different variations of gradient descent, such as stochastic gradient descent and mini-batch gradient descent.

Gradient descent is a powerful optimization algorithm that is widely used in machine learning and deep learning to find the optimal solution to a given problem. It is an iterative algorithm that updates the parameters of a function by taking steps in the opposite direction of the gradient of the function. TensorFlow makes it easy to implement gradient descent by providing built-in optimizers and functions for computing gradients.



Previous Article
Next Article

Similar Reads

Applications of Gradient Descent in TensorFlow
To reduce a model's cost function, machine learning practitioners frequently employ the gradient descent optimization procedure. It entails incrementally changing the model's parameters in the direction of the cost function's steepest decline. A free machine learning package called TensorFlow has built-in support for gradient descent optimization.
7 min read
Stochastic Gradient Descent Classifier
One essential tool in the data science and machine learning toolkit for a variety of classification tasks is the stochastic gradient descent (SGD) classifier. Through an exploration of its functionality and critical role in data-driven decision-making, we set out to explore the complexities of the SGD Classifier in this article. A flexible classifi
14 min read
Stochastic Gradient Descent Regressor
A key method in data science and machine learning is the stochastic gradient descent (SGD) regression. It is essential to many regression activities and aids in the creation of predictive models for a variety of uses. We will study the idea of the SGD Regressor, its operation, and its importance in the context of data-driven decision-making in this
10 min read
Python - tensorflow.GradientTape.gradient()
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. gradient() is used to computes the gradient using operations recorded in context of this tape. Syntax: gradient(target, sources, output_gradients, unconnected_gradients) Parameters: target: It is Tensor or list of Tensor
2 min read
Applying Gradient Clipping in TensorFlow
In deep learning, gradient clipping is an essential technique to prevent gradients from becoming too large during backpropagation, which can lead to unstable training and exploding gradients. This article provides a detailed overview of how to apply gradient clipping in TensorFlow, starting from the basics and advancing to practical implementation
5 min read
PyQt5 QSpinBox - Getting descent of the font
In this article we will see how we can get the descent of the spin box's font i.e text. The descent is the distance from the base line to the lowest point characters extend to. In practice, some font designers break this rule, e.g. to accommodate an unusual character in an exotic language, so it is possible (though rare) that this value will be too
2 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. Because we all know that the true test of a model lies n
6 min read
Main Loopholes in TensorFlow - Tensorflow Security
TensorFlow is an open-source machine-learning framework widely used for building, training, and deploying machine-learning models. Despite its popularity and versatility, TensorFlow is not immune to security vulnerabilities and loopholes. Some of the common security loopholes in TensorFlow are related to data privacy, session hijacking, and lack of
6 min read
Why TensorFlow is So Popular - Tensorflow Features
In this article, we will see Why TensorFlow Is So Popular, and then explore Tensorflow Features. TensorFlow is an open-source software library. It was originally developed by researchers and engineers working on the Google Brain Team within Google’s Machine Intelligence research organization for the purposes of conducting machine learning and deep
3 min read
Tensorflow 1.xvs. Tensorflow 2.x: What's the Difference?
TensorFlow is an end-to-end open-source machine learning platform that contains comprehensive tools, libraries and community resources. It is meant for developers, data scientists and researchers to build and deploy applications powered by machine learning. TensorFlow was essentially built to scale, developed by Google Brain team, TensorFlow accele
6 min read
How to migrate from TensorFlow 1.x to TensorFlow 2.x
The introduction of TensorFlow 2. x marks a significant advance in the strong open-source machine learning toolkit TensorFlow. TensorFlow 2.0 introduces significant API changes, making manual code upgrades tedious and error prone. TensorFlow 2. x places an emphasis on user-friendliness and optimizes the development process, whereas TensorFlow 1. x
7 min read
Python | Plotting an Excel chart with Gradient fills using XlsxWriter module
Prerequisite: Create and Write on an excel sheetXlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations, and plotting graphs. Let’s see how to plot a chart with Gradient fills, using real-time data.Charts are composed of at least one series of one or more data point
5 min read
Python | Morphological Operations in Image Processing (Gradient) | Set-3
In the previous articles, the Opening operation and the Closing operations were specified. In this article, another morphological operation is elaborated that is Gradient. It is used for generating the outline of the image. There are two types of gradients, internal and external gradient. The internal gradient enhances the internal boundaries of ob
2 min read
PyQt5 - Gradient color Bar of Progress Bar
In this article we will see how we can create the gradient color to bar of progress bar. Gradient Color : In computer graphics, a color gradient specifies a range of position-dependent colors, usually used to fill a region. For example, many window managers allow the screen background to be specified as a gradient. The colors produced by a gradient
2 min read
PyQt5 - Gradient Color Progress Bar
In this article we will see how we can set gradient color to the progress bar. Below is how normal color progress bar looks like vs the gradient color progress bar looks like. In order to do this we have to change the CSS style sheet, below is the code for style sheet. QProgressBar::chunk { border : 1px solid black; background: QLinearGradient( x1:
2 min read
Make a gradient color mapping on a specified column in Pandas
Let us see how to gradient color mapping on specific columns of a Pandas DataFrame. We can do this using the Styler.background_gradient() function of the Styler class. Syntax : Styler.background_gradient(cmap='PuBu', low=0, high=0, axis=0, subset=None) Parameters : cmap : str or colormap (matplotlib colormap) low, high : float (compress the range b
2 min read
PyQtGraph – Setting Predefined Gradient to Image View
In this article, we will see how we can set a predefined gradient to the image view object in PyQTGraph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc
4 min read
How to Estimate the Gradient of a Function in One or More Dimensions in PyTorch?
In this article, we are going to see how to estimate the gradient of a function in one or more dimensions in PyTorch. torch.gradient() function torch.gradient() method estimates the gradient of a function in one or more dimensions using the second-order accurate central differences method, and the function can be defined on a real or complex domain
2 min read
How to optimize networking using optimization algorithms in PyBrain
In this article, we are going to see how to optimize networking using optimization algorithms in PyBrain using Python. In the field of machine learning, Optimization algorithms are specifically used to reduce certain functions known as loss function/error function. By loss function, the optimization algorithm may result in reducing the difference b
3 min read
Maximize Optimization using Scipy
In this post, we'll talk about the Python Scipy module and the idea of linear programming problems, including how to maximize the objective function and obtain the best solution. Linear Programming Linear Programming consists of an objective function (Z) and some constraints. According to the situation, the mode will be either maximum or minimum. I
5 min read
Optimization in SciPy
SciPy is a Python library that is available for free and open source and is used for technical and scientific computing. It is a set of useful functions and mathematical methods created using Python's NumPy module. Features of SciPy:Creating complex programs and specialized applications is a benefit of building SciPy on Python.SciPy contains variet
8 min read
Python Database Optimization with Psycopg2 and Multiprocessing
This article will provide a succinct overview of the fundamental utilization of the Psycopg2 module and the Multiprocessing module in Python. It will cover how Psycopg2 operates independently and in conjunction with multiprocessing. Psycopg2 and Its Role in Database OperationsAccording to PyPi's documentation for Psycopg2, it is designed to be used
6 min read
Optimization Tips for Python Code
In this article, some interesting optimization tips for Faster Python Code are discussed. These techniques help to produce result faster in a python code. Use builtin functions and libraries: Builtin functions like map() are implemented in C code. So the interpreter doesn't have to execute the loop, this gives a considerable speedup. The map() func
6 min read
Softmax Regression using TensorFlow
This article discusses the basics of Softmax Regression and its implementation in Python using the TensorFlow library. Softmax regression Softmax regression (or multinomial logistic regression) is a generalization of logistic regression to the case where we want to handle multiple classes in the target column. In binary logistic regression, the lab
6 min read
Introduction to Tensor with Tensorflow
TensorFlow is an open-source software library for dataflow programming across a range of tasks. It is a symbolic math library, and also used for machine learning applications such as neural networks. Google open-sourced TensorFlow in November 2015. Since then, TensorFlow has become the most starred machine learning repository on Github. (https://gi
8 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 [Tex]f(x) = 1 / (1 + e^{-x}) [/Tex].Sigmoid functio
3 min read
Python | Tensorflow nn.relu() and nn.leaky_relu()
Tensorflow is an open-source machine learning library developed by Google. One of its applications is to developed deep neural networks. The module tensorflow.nn provides support for many basic neural network operations. An activation function is a function which is applied to the output of a neural network layer, which is then passed as the input
3 min read
Python | Tensorflow nn.tanh()
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 hyperbolic tangent function (also known as tanh) which is defined as [Tex]tanh(x) = (e^
3 min read
What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?
Padding is a technique used in convolutional neural networks (CNNs) to preserve the spatial dimensions of the input data and prevent the loss of information at the edges of the image. It involves adding additional rows and columns of pixels around the edges of the input data. There are several different ways to apply padding in Python, depending on
14 min read
Difference Between tf.Session() And tf.InteractiveSession() Functions in Python Tensorflow
In this article, we are going to see the differences between tf.Session() and tf.InteractiveSession(). tf.Session() In TensorFlow, the computations are done using graphs. But when a graph is created, the values and computations are not defined. So a session is used to run the graph. The sessions place the graphs on targeted devices and execute them
3 min read