The Wayback Machine - https://web.archive.org/web/20240916051139/https://www.geeksforgeeks.org/softmax-regression-using-tensorflow/
Open In App

Softmax Regression using TensorFlow

Last Updated : 10 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 labels were binary, that is for ith observation,

 y_{i} \in \{ 0, 1 \}

But consider a scenario where we need to classify an observation out of three or more class labels. For example, in digit classification here, the possible labels are:

 y_{i} \in \{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 \}

In such cases, we can use Softmax Regression

Softmax layer

It is harder to train the model using score values since it is hard to differentiate them while implementing the Gradient Descent algorithm for minimizing the cost function. So, we need some function that normalizes the logit scores as well as makes them easily differentiable. In order to convert the score matrix Z to probabilities, we use the Softmax function. For a vector y, softmax function S(y) is defined as:

S\left ( y_i \right )=\frac{e^{y_i}}{\sum_{j=0}^{n-1}e^{y_i}}      

So, the softmax function helps us to achieve two functionalities:

1. Convert all scores to probabilities.
2. Sum of all probabilities is 1.

Recall that in the Binary Logistic regression, we used the sigmoid function for the same task. The softmax function is nothing but a generalization of the sigmoid function. Now, this softmax function computes the probability that the ith training sample belongs to class j given the logits vector Zi as: 

P\left ( y=j| Z_i \right )=\left[S\left ( Z_i \right )\right]_j=\frac{e^{Z_{ij}}}{\sum_{p=0}^{k}e^{Z_{ip}}}      

In vector form, we can simply write:

P\left ( y=j| Z_i \right )=\left[S\left ( Z_i \right )\right]_j      

For simplicity, let Si denote the softmax probability vector for ith observation.

Cost function

Now, we need to define a cost function for which, we have to compare the softmax probabilities and one-hot encoded target vector for similarity. We use the concept of Cross-Entropy for the same. The Cross-entropy is a distance calculation function that takes the calculated probabilities from the softmax function and created a one-hot-encoding matrix to calculate the distance. For the right target classes, the distance values will be lesser, and the distance values will be larger for the wrong target classes. We define cross-entropy, D(Si, Ti) for ith observation with softmax probability vector, Si, and one-hot target vector, Ti as:

D\left ( S_i, T_i \right )=-\sum_{j=1}^{k} T_{ij}\log S_{ij}      

And now, the cost function, J can be defined as the average cross-entropy.

J\left ( W,b \right )=\frac{1}{n}\sum_{i=1}^{n}D\left ( S_i, T_i \right )      

Let us now implement Softmax Regression on the MNIST handwritten digit dataset using the TensorFlow library. For a gentle introduction to TensorFlow, follow this tutorial.

Importing Libraries and Dataset

First of all, we import the dependencies. 

Python3

import tensorflow as tf
import tensorflow.compat.v1 as tf1
 
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

                    

TensorFlow allows you to download and read the MNIST data automatically. Consider the code given below. It will download and assign the MNIST_data to the desired variables like it has been done below. 

Python3

(X_train, Y_train),\
(X_val, Y_val) = tf.keras.datasets.mnist.load_data()
print("Shape of feature matrix:", X_train.shape)
print("Shape of target matrix:", Y_train.shape)

                    

Output:

Shape of feature matrix: (60000, 28, 28)
Shape of target matrix: (60000,)

Now, we try to understand the structure of the dataset. The MNIST data is split into two parts: 60,000 data points of training data, and 10,000 points of validation data. Each image is 28 pixels by 28 pixels. The number of class labels is 10.

Python3

# visualize data by plotting images
fig, ax = plt.subplots(10, 10)
for i in range(10):
    for j in range(10):
        k = np.random.randint(0,X_train.shape[0])
        ax[i][j].imshow(X_train[k].reshape(28, 28),
                        aspect='auto')
plt.show()

                    

Output:

Sample images from the MNIST data

Now let’s define some hyperparameters here only so, that we can control them for the whole notebook from here only. Also, we need to reshape the data, as well as one hot encode the data to get the desired results.

Python3

num_features = 784
num_labels = 10
learning_rate = 0.05
batch_size = 128
num_steps = 5001
 
# input data
train_dataset = X_train.reshape(-1, 784)
train_labels = pd.get_dummies(Y_train).values
valid_dataset = X_val.reshape(-1, 784)
valid_labels = pd.get_dummies(Y_val).values

                    

Computation Graph

Now, we create a computation graph. Defining a computation graph helps us to achieve the functionality of the EagerTensor that is provided by TensorFlow. 

Python3

# initialize a tensorflow graph
graph = tf.Graph()
 
with graph.as_default():
    # Inputs
    tf_train_dataset = tf1.placeholder(tf.float32,
                                       shape=(batch_size, num_features))
    tf_train_labels = tf1.placeholder(tf.float32,
                                      shape=(batch_size, num_labels))
    tf_valid_dataset = tf.constant(valid_dataset)
 
    # Variables.
    weights = tf.Variable(
        tf.random.truncated_normal([num_features, num_labels]))
    biases = tf.Variable(tf.zeros([num_labels]))
 
    # Training computation.
    logits = tf.matmul(tf_train_dataset, weights) + biases
    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
        labels=tf_train_labels, logits=logits))
 
    # Optimizer.
    optimizer = tf1.train.GradientDescentOptimizer(
        learning_rate).minimize(loss)
 
    # Predictions for the training, validation, and test data.
    train_prediction = tf.nn.softmax(logits)
    tf_valid_dataset = tf.cast(tf_valid_dataset, tf.float32)
    valid_prediction = tf.nn.softmax(
        tf.matmul(tf_valid_dataset, weights) + biases)

                    

Running the Computation Graph

Since we have already built the computation graph, now it’s time to run it through a session.

Python3

# utility function to calculate accuracy
def accuracy(predictions, labels):
    correctly_predicted = np.sum(
        np.argmax(predictions, 1) == np.argmax(labels, 1))
    acc = (100.0 * correctly_predicted) / predictions.shape[0]
    return acc

                    

We will use the above utility function to calculate the accuracy of the model as the training goes on.

Python3

with tf1.Session(graph=graph) as session:
    # initialize weights and biases
    tf1.global_variables_initializer().run()
    print("Initialized")
 
    for step in range(num_steps):
        # pick a randomized offset
        offset = np.random.randint(0, train_labels.shape[0] - batch_size - 1)
 
        # Generate a minibatch.
        batch_data = train_dataset[offset:(offset + batch_size), :]
        batch_labels = train_labels[offset:(offset + batch_size), :]
 
        # Prepare the feed dict
        feed_dict = {tf_train_dataset: batch_data,
                     tf_train_labels: batch_labels}
 
        # run one step of computation
        _, l, predictions = session.run([optimizer, loss, train_prediction],
                                        feed_dict=feed_dict)
 
        if (step % 500 == 0):
            print("Minibatch loss at step {0}: {1}".format(step, l))
            print("Minibatch accuracy: {:.1f}%".format(
                accuracy(predictions, batch_labels)))
            print("Validation accuracy: {:.1f}%".format(
                accuracy(valid_prediction.eval(), valid_labels)))

                    

Output:

Initialized
Minibatch loss at step 0: 3185.3974609375
Minibatch accuracy: 7.0%
Validation accuracy: 21.1%
Minibatch loss at step 500: 619.6030883789062
Minibatch accuracy: 86.7%
Validation accuracy: 89.0%
Minibatch loss at step 1000: 247.22283935546875
Minibatch accuracy: 93.8%
Validation accuracy: 85.7%
Minibatch loss at step 1500: 2945.78662109375
Minibatch accuracy: 78.9%
Validation accuracy: 83.6%
Minibatch loss at step 2000: 337.13922119140625
Minibatch accuracy: 94.5%
Validation accuracy: 89.0%
Minibatch loss at step 2500: 409.4652404785156
Minibatch accuracy: 89.8%
Validation accuracy: 90.6%
Minibatch loss at step 3000: 1077.618408203125
Minibatch accuracy: 84.4%
Validation accuracy: 90.3%
Minibatch loss at step 3500: 986.0247802734375
Minibatch accuracy: 80.5%
Validation accuracy: 85.9%
Minibatch loss at step 4000: 467.134521484375
Minibatch accuracy: 89.8%
Validation accuracy: 85.1%
Minibatch loss at step 4500: 1007.259033203125
Minibatch accuracy: 87.5%
Validation accuracy: 87.5%
Minibatch loss at step 5000: 342.13690185546875
Minibatch accuracy: 94.5%
Validation accuracy: 89.6%

Some important points to note:

  • In every iteration, a minibatch is selected by choosing a random offset value using np.random.randint method.
  • To feed the placeholders tf_train_dataset and tf_train_label, we create a feed_dict like this:
feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}

Although many of the functionalities we have implemented from scratch here are provided automatically if one uses TensorFlow. But they have been implemented from scratch to get a better intuition of the mathematical formulas which are used in the Softmax Regression Classifier.



Similar Reads

How to Implement Softmax and Cross-Entropy in Python and PyTorch
Multiclass classification is an application of deep learning/machine learning where the model is given input and renders a categorical output corresponding to one of the labels that form the output. For example, providing a set of images of animals and classifying it among cats, dogs, horses, etc. For this purpose, where the model outputs multiple
7 min read
Solving Linear Regression without using Sklearn and TensorFlow
In this article, we will see how can we implement a Linear Regression class on our own without using any of the sklearn or the Tensorflow API pre-implemented functions which are highly optimized for such tasks. But then why we are implementing these functions on our own? The answer to this is very simple that is because they help to clarify our con
3 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
Multiple Linear Regression using R
Prerequisite: Simple Linear-Regression using RLinear Regression: It is the basic and commonly used type for predictive analysis. It is a statistical approach for modeling the relationship between a dependent variable and a given set of independent variables.These are of two types: Simple linear RegressionMultiple Linear Regression Let's Discuss Mul
3 min read
Linear Regression using PyTorch
Linear Regression is a very commonly used statistical method that allows us to determine and study the relationship between two continuous variables. The various properties of linear regression and its Python implementation have been covered in this article previously. Now, we shall find out how to implement this in PyTorch, a very popular deep lea
4 min read
Pyspark | Linear regression using Apache MLlib
Problem Statement: Build a predictive Model for the shipping company, to find an estimate of how many Crew members a ship requires. The dataset contains 159 instances with 9 features. The Description of dataset is as below: Let’s make the Linear Regression Model, predicting Crew members Attached dataset: cruise_ship_info import pyspark from pyspark
3 min read
How To Make Scatter Plot with Regression Line using Seaborn in Python?
In this article, we will learn how to male scatter plots with regression lines using Seaborn in Python. Let's discuss some concepts : Seaborn : Seaborn is a tremendous visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on t
2 min read
Scatter Plot with Regression Line using Altair in Python
Prerequisite: Altair In this article, we are going to discuss how to plot to scatter plots with a regression line using the Altair library. Scatter Plot and Regression Line The values of two different numeric variables is represented by dots or circle in Scatter Plot. Scatter Plot is also known as aka scatter chart or scatter graph. The position of
4 min read
Orthogonal distance regression using SciPy
Regression basically involves determining the relationship between a dependent variable and one or more independent variables. It generally involves finding the best fit line that minimizes the sum of squared errors for each point. Based on the implementation procedures, regression algorithms are classified as linear regression, ridge regression, l
4 min read
Linear Regression in Python using Statsmodels
In this article, we will discuss how to use statsmodels using Linear Regression in Python. Linear regression analysis is a statistical technique for predicting the value of one variable(dependent variable) based on the value of another(independent variable). The dependent variable is the variable that we want to predict or forecast. In simple linea
4 min read
House Price Prediction using Linear Regression | Django
In this article, we'll explore how to use a Python machine-learning algorithm called linear regression to estimate house prices. We'll do this by taking input data from users who want to predict the price of their home. To make things more accessible and interactive, we'll transform this house price prediction code into a web-based system using the
4 min read
Mathematical explanation for Linear Regression working
Suppose we are given a dataset: Given is a Work vs Experience dataset of a company and the task is to predict the salary of a employee based on his / her work experience. This article aims to explain how in reality Linear regression mathematically works when we use a pre-defined function to perform prediction task. Let us explore how the stuff work
1 min read
ML | Locally weighted Linear Regression
Linear Regression is a supervised learning algorithm used for computing linear relationships between input (X) and output (Y). The steps involved in ordinary linear regression are: Training phase: Compute [Tex]\theta [/Tex]to minimize the cost. [Tex]J(\theta) = $\sum_{i=1}^{m} (\theta^Tx^{(i)} - y^{(i)})^2 [/Tex] Predict output: for given query poi
3 min read
How To Add Regression Line Per Group with Seaborn in Python?
In this article, we will learn how to add a regression line per group with Seaborn in Python. Seaborn has multiple functions to form scatter plots between two quantitative variables. For example, we can use lmplot() function to make the required plot. What is Regression Line? A regression line is just one line that most closely fits the info (in te
1 min read
How to Get Regression Model Summary from Scikit-Learn
In this article, we are going to see how to get a regression model summary from sci-kit learn. It can be done in these ways: Scikit-learn PackagesStats model packageExample 1: Using scikit-learn. You may want to extract a summary of a regression model created in Python with Scikit-learn. Scikit-learn does not have many built-in functions for analyz
3 min read
How to Perform Quadratic Regression in Python?
The quadratic equation is a method of modeling a relationship between sets of independent variables is quadratic regression or we can say the technique of obtaining the equation of a parabola that best fits a collection of data is known as quadratic regression. We use the R square metric to measure the relative predictive power of a Quadratic Regre
2 min read
Plot Multinomial and One-vs-Rest Logistic Regression in Scikit Learn
Logistic Regression is a popular classification algorithm that is used to predict the probability of a binary or multi-class target variable. In scikit-learn, there are two types of logistic regression algorithms: Multinomial logistic regression and One-vs-Rest logistic regression. Multinomial logistic regression is used when the target variable ha
4 min read
Classification vs Regression in Machine Learning
Classification and Regression are two major prediction problems that are usually dealt with in Data Mining and Machine Learning. We are going to deal with both Classification and Regression and we will also see differences between them in this article. Classification AlgorithmsClassification is the process of finding or discovering a model or funct
5 min read
Multivariate Regression
Prerequisite Article-Machine Learning The goal in any data analysis is to extract from raw information the accurate estimation. One of the most important and common question concerning if there is statistical relationship between a response variable (Y) and explanatory variables (Xi). An option to answer this question is to employ regression analys
4 min read
Effect of Transforming the Targets in Regression Model
Regression modelling plays a crucial role in predicting numerical outcomes and understanding the relationships between variables. One key aspect of building robust regression models is the careful consideration of the target variable, as its distribution and characteristics can significantly impact model performance. In this article, we will discus
8 min read
Python | Creating tensors using different functions in Tensorflow
Tensorflow is an open-source machine learning framework that is used for complex numerical computation. It was developed by the Google Brain team in Google. Tensorflow can train and run deep neural networks that can be used to develop several AI applications. What is a Tensor? A tensor can be described as a n-dimensional numerical array. A tensor c
5 min read
One Hot Encoding using Tensorflow
In this post, we will be seeing how to initialize a vector in TensorFlow with all zeros or ones. The function you will be calling is tf.ones(). To initialize with zeros you could use tf.zeros() instead. These functions take in a shape and return an array full of zeros and ones accordingly. Code: import tensorflow as tf ones_matrix = tf.ones([2, 3])
2 min read
Python - Model Deployment Using TensorFlow Serving
The most important part of the machine learning pipeline is the model deployment. Model Deployment means Deployment is the method by which you integrate a machine learning model into an existing production environment to allow it to use for practical purposes in real-time. There are many ways to deploy a model. One way is to integrate a model with
10 min read
How to Create Custom Model For Android Using TensorFlow?
Tensorflow is an open-source library for machine learning. In android, we have limited computing power as well as resources. So we are using TensorFlow light which is specifically designed to operate on devices with limited power. In this post, we going to see a classification example called the iris dataset. The dataset contains 3 classes of 50 in
5 min read
Implementing Neural Networks Using TensorFlow
Deep learning has been on the rise in this decade and its applications are so wide-ranging and amazing that it's almost hard to believe that it's been only a few years in its advancements. And at the core of deep learning lies a basic "unit" that governs its architecture, yes, It's neural networks. A neural network architecture comprises a number o
8 min read
Image Segmentation Using TensorFlow
Image segmentation refers to the task of annotating a single class to different groups of pixels. While the input is an image, the output is a mask that draws the region of the shape in that image. Image segmentation has wide applications in domains such as medical image analysis, self-driving cars, satellite image analysis, etc. There are differen
7 min read
How can Tensorflow be used to standardize the data using Python?
In this article, we are going to see how to use standardize the data using Tensorflow in Python. What is Data Standardize? The process of converting the organizational structure of various datasets into a single, standard data format is known as data standardization. It is concerned with the modification of datasets following their collection from
3 min read