The Wayback Machine - https://web.archive.org/web/20241118054725/https://www.geeksforgeeks.org/restricted-boltzmann-machine-features-for-digit-classification-in-scikit-learn/
Open In App

Restricted Boltzmann Machine Features for Digit Classification in Scikit Learn

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

Restricted Boltzmann Machine (RBM) is a type of artificial neural network that is used for unsupervised learning and generative modeling.  They follow the rules of energy minimization and are quite similar to probabilistic graphical models. Hopfield networks, which store memories, served as the basis for RBMs’ initial design, which was then modified to include hidden layers for the generative modeling of data. 

 RBMs are frequently used for dimensionality reduction and unsupervised modeling, Although they can be modified for supervised modeling. But prior to supervised training, RBMs frequently go through an unsupervised pretraining period because of their innate properties. It has been discovered that this pretraining procedure, which involves training the RBM without labeled data, is very advantageous for future supervised learning. RBMs thus had a significant influence on the motivation for and acceptance of pretraining in deep learning models.

An RBM’s training procedure is very different from a conventional feed-forward network’s. Backpropagation cannot be used to directly train RBMs; instead, Monte Carlo sampling methods must be used. Contrastive divergence is the RBM training algorithm most frequently used. Through sampling and comparison with the original input, this technique iteratively approximates the gradient of the RBM’s parameters.

 Restricted Boltzmann Machine Model Architecture:

RBMs are two-layer generative neural network models. It is made up of a visible layer and a hidden layer with stochastic binary units. RBMs learn to capture patterns in input data by minimizing an energy function. They employ unsupervised learning and can be used for tasks such as feature learning, dimensionality reduction, and collaborative filtering. RBMs utilize a sampling method, like Gibbs sampling, to activate units probabilistically based on the energy function. Through training, RBMs adjust weights and biases to reconstruct observed data and generate plausible samples, making them effective for probabilistic modeling and generative tasks.

It consists of two main layers named visible layer and hidden layer. Both layers contain a set of binary units. 

  • Visible Layer:
    • Represents input data
    • Can take binary values or continuous values depending on the RBM used
  • Hidden Layer:
    • Represents the hidden variable of RBM
    • Captures a high level of abstraction
    • Can take binary values or continuous values depending on the RBM used
  • Connections:
    • Every visible unit is been connected to the hidden unit and vice-versa
    • Each connection has different weights which indicate the strength of the connection  
  • Biases:
    • Each visible unit has an associated bias term, which influences its activation.
Restricted Boltzmann Machine Architecture-Geeksforgeeks

Restricted Boltzmann Machine Architecture

Example:

In this example, we will demonstrate the use of RBM features for digit classification using the MNIST (Modified National Institute of Standards and Technology) dataset, which consists of handwritten digits ranging from 0 to 9.

Steps for the usage of an RBM in combination with logistic regression for classification tasks are:

  • Step 1: The very first step is to import the necessary libraries
    • BernoulliRBM from sklearn.neural_network
    • Pipeline from sklearn.pipeline
    • load_digits from sklearn.datasets
    • train_test_split from sklearn.model_selection
    • classification_report from sklearn.metrics 
  • Step 2: load the MNIST data set
    • MNIST data set is been used with the help of the load_digits() function.
    • Separate input features and target variables.
    • Apply the min-max scaled to the datasets
  • Step 3: Split the data into training and testing sets
    • train_test_split(): to split the loaded dataset into training and testing sets. 
  • Step 4: Create an RBM model
    • creates an object of the BernoulliRBM class
  • Step 5: Create a classifier
    • creates an object of the LogisticRegression class
  • Step 6: Create a pipeline combining RBM and classifier
    •  creates a Pipeline object from sklearn.pipeline which combines the RBM and classifier together in a sequence
  • Step 7: Train the model
    • trains the pipeline by calling the fit() method on the pipeline object
  • Step 8: Make predictions on the test set
    • Use the trained pipeline to make predictions on the test set (X_test) by calling the predict method.
  • Step 9: Evaluate the model
    • The code calculates and prints the classification report using the classification_report() function.

Python3




# Import necessary libraries
from sklearn.neural_network import BernoulliRBM
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.datasets import load_digits
from sklearn.preprocessing import minmax_scale, OneHotEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
 
# Load the MNIST dataset
digits = load_digits()
 
# Digits image
X = digits.data
# Digits
Y = digits.target
 
# Min-max scaling
X_scaled = minmax_scale(X, feature_range=(0, 1))
 
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X_scaled, Y,
                                                    test_size=0.2, random_state=42)
 
Epoch = 15
# Create an RBM model
rbm = BernoulliRBM(n_components=100, learning_rate=0.02, n_iter=Epoch,
                   random_state=42, verbose=True)
 
# Create a classifier
classifier = LogisticRegression(max_iter=500)
 
# Create a pipeline combining RBM and classifier
pipeline = Pipeline(steps=[('rbm', rbm), ('classifier', classifier)])
 
# Train the model
pipeline.fit(X_train, y_train)
 
# Make predictions on the test set
y_pred = pipeline.predict(X_test)
 
# Evaluate the model
print('\nClassification Report :\n',classification_report(y_test, y_pred))


Output:

[BernoulliRBM] Iteration 1, pseudo-likelihood = -26.07, time = 0.03s
[BernoulliRBM] Iteration 2, pseudo-likelihood = -25.78, time = 0.03s
[BernoulliRBM] Iteration 3, pseudo-likelihood = -25.69, time = 0.03s
[BernoulliRBM] Iteration 4, pseudo-likelihood = -25.56, time = 0.06s
[BernoulliRBM] Iteration 5, pseudo-likelihood = -25.77, time = 0.03s
[BernoulliRBM] Iteration 6, pseudo-likelihood = -25.55, time = 0.03s
[BernoulliRBM] Iteration 7, pseudo-likelihood = -25.62, time = 0.04s
[BernoulliRBM] Iteration 8, pseudo-likelihood = -25.38, time = 0.04s
[BernoulliRBM] Iteration 9, pseudo-likelihood = -24.95, time = 0.03s
[BernoulliRBM] Iteration 10, pseudo-likelihood = -24.67, time = 0.03s
[BernoulliRBM] Iteration 11, pseudo-likelihood = -23.88, time = 0.03s
[BernoulliRBM] Iteration 12, pseudo-likelihood = -23.51, time = 0.04s
[BernoulliRBM] Iteration 13, pseudo-likelihood = -22.78, time = 0.04s
[BernoulliRBM] Iteration 14, pseudo-likelihood = -22.45, time = 0.04s
[BernoulliRBM] Iteration 15, pseudo-likelihood = -21.96, time = 0.04s

Classification Report :
               precision    recall  f1-score   support

           0       0.91      0.94      0.93        33
           1       0.66      0.75      0.70        28
           2       0.72      0.85      0.78        33
           3       0.76      0.82      0.79        34
           4       0.94      1.00      0.97        46
           5       0.83      0.64      0.72        47
           6       0.97      0.94      0.96        35
           7       0.81      0.85      0.83        34
           8       0.78      0.47      0.58        30
           9       0.60      0.68      0.64        40

    accuracy                           0.80       360
   macro avg       0.80      0.79      0.79       360
weighted avg       0.80      0.80      0.79       360

Explanation: 

The output of the code will display the classification report. In this report, there are 4 cols with the name precision, recall, and F1-score for each digit class, indicating the accuracy and reliability of the model’s predictions and the support value represents the number of samples for each class in the test set.

The model can achieve competitive performance in digit classification tasks by learning meaningful representations of the digit images using RBM features.

Applications of Restricted Boltzmann Machine

Restricted Boltzmann Machines (RBMs) have found numerous applications in various fields, some of which are:

  • Collaborative filtering: RBMs are widely used in collaborative filtering for recommender systems. They learn to predict user preferences based on their past behavior and recommend items that are likely to be of interest to the user.
  • Image and video processing: RBMs can be used for image and video processing tasks such as object recognition, image denoising, and image reconstruction. They can also be used for tasks such as video segmentation and tracking.
  • Natural language processing: RBMs can be used for natural language processing tasks such as language modeling, text classification, and sentiment analysis. They can also be used for tasks such as speech recognition and speech synthesis.
  • Bioinformatics: RBMs have found applications in bioinformatics for tasks such as protein structure prediction, gene expression analysis, and drug discovery.
  • Financial modeling: RBMs can be used for financial modeling tasks such as predicting stock prices, risk analysis, and portfolio optimization.
  • Anomaly detection: RBMs can be used for anomaly detection tasks such as fraud detection in financial transactions, network intrusion detection, and medical diagnosis.


Similar Reads

Restricted Boltzmann Machine
Introduction : Restricted Boltzmann Machine (RBM) is a type of artificial neural network that is used for unsupervised learning. It is a type of generative model that is capable of learning a probability distribution over a set of input data. RBM was introduced in the mid-2000s by Hinton and Salakhutdinov as a way to address the problem of unsuperv
7 min read
Restricted Boltzmann Machine (RBM) with Practical Implementation
In the world of machine learning, one algorithm that has gained significant attention is the Restricted Boltzmann Machine (RBM). RBMs are powerful generative models that have been widely used for various applications, such as dimensionality reduction, feature learning, and collaborative filtering. In this article, we will explore the concepts and s
8 min read
Restricted Boltzmann Machine : How it works
A Restricted Boltzmann Machine (RBM), Introduced by Geoffrey Hinton and Terry Sejnowski in 1985, Since, It become foundational in unsupervised machine learning, particularly in the context of deep learning architectures. They are widely used for dimensionality reduction, classification, regression, collaborative filtering, feature learning, and top
5 min read
Contrastive Divergence in Restricted Boltzmann Machines
Contrastive Divergence (CD) is a fundamental technique in the realm of machine learning, particularly in the field of unsupervised learning and specifically in training Restricted Boltzmann Machines (RBMs). It serves as a crucial component in the learning process by approximating the gradient needed to update the weights in these models. Initially
10 min read
Classification of text documents using sparse features in Python Scikit Learn
Classification is a type of machine learning algorithm in which the model is trained, so as to categorize or label the given input based on the provided features for example classifying the input image as an image of a dog or a cat (binary classification) or to classify the provided picture of a living organism into one of the species from within t
5 min read
Probability Calibration for 3-class Classification in Scikit Learn
Probability calibration is a technique to map the predicted probabilities of a model to their true probabilities. The probabilities predicted by some classification algorithms like Logistic Regression, SVM, or Random Forest may not be well calibrated, meaning they may not accurately reflect the true probabilities of the target classes. This can lea
4 min read
Normal and Shrinkage Linear Discriminant Analysis for Classification in Scikit Learn
In this article, we will try to understand the difference between Normal and Shrinkage Linear Discriminant Analysis for Classification. We will try to implement the same using sci-kit learn library in Python. But first, let's try to understand what is LDA. What is Linear discriminant analysis (LDA)? Linear discriminant analysis (LDA) is a supervise
4 min read
Iso-Probability Lines for Gaussian Processes Classification (GPC) in Scikit Learn
Gaussian Processes (GPs) are a powerful tool for probabilistic modeling and have been widely used in various fields such as machine learning, computer vision, and signal processing. Gaussian Processes Classification is a classification technique based on Gaussian Processes to model the probability of an input belonging to a certain class. In GPC, w
11 min read
Gaussian Process Classification (GPC) on the XOR Dataset in Scikit Learn
Gaussian process classification (GPC) is a probabilistic approach to classification that models the conditional distribution of the class labels given the feature values. In GPC, the data is assumed to be generated by a Gaussian process, which is a stochastic process that is characterized by its mean and covariance functions. The mean function in G
4 min read
MNIST Classification Using Multinomial Logistic + L1 in Scikit Learn
In this article, we shall implement MNIST classification using Multinomial Logistic Regression using the L1 penalty in the Scikit Learn Python library. Multinomial Logistic Regression and L1 Penalty MNIST is a widely used dataset for classification purposes. You may think of this dataset as the Hello World dataset of Machine Learning. Logistic Regr
4 min read
Probabilistic Predictions with Gaussian Process Classification (GPC) in Scikit Learn
Gaussian Process Classification (GPC) is a probabilistic model for classification tasks. It is based on the idea of using a Gaussian process to model the relationship between the input features and the target labels of a classification problem. GPC makes use of Bayesian inference to make predictions, which means that it can output not only the most
7 min read
Multiclass classification using scikit-learn
Multiclass classification is a popular problem in supervised machine learning. Problem - Given a dataset of m training examples, each of which contains information in the form of various features and a label. Each label corresponds to a class, to which the training example belongs. In multiclass classification, we have a finite set of classes. Each
5 min read
Comprehensive Guide to Classification Models in Scikit-Learn
Scikit-Learn, a powerful and user-friendly machine learning library in Python, has become a staple for data scientists and machine learning practitioners. It offers a wide array of tools for data mining and data analysis, making it accessible and reusable in various contexts. This article delves into the classification models available in Scikit-Le
12 min read
Text Classification using scikit-learn in NLP
The purpose of text classification, a key task in natural language processing (NLP), is to categorise text content into preset groups. Topic categorization, sentiment analysis, and spam detection can all benefit from this. In this article, we will use scikit-learn, a Python machine learning toolkit, to create a simple text categorization pipeline.
5 min read
ML | Cancer cell classification using Scikit-learn
Machine Learning is a sub-field of Artificial Intelligence that gives systems the ability to learn themselves without being explicitly programmed to do so. Machine Learning can be used in solving many real world problems. Let's classify cancer cells based on their features, and identifying them if they are 'malignant' or 'benign'. We will be using
10 min read
Revealing K-Modes Cluster Features with Scikit-Learn
Clustering is a powerful technique in unsupervised machine learning that helps in identifying patterns and structures in data. While K-Means is widely known for clustering numerical data, K-Modes is a variant specifically designed for categorical data. In this article, we will delve into the K-Modes algorithm, its implementation using Scikit-Learn,
3 min read
How to Identify the Most Informative Features for scikit-learn Classifiers
Feature selection is an important step in the machine learning pipeline. By identifying the most informative features, you can enhance model performance, reduce overfitting, and improve computational efficiency. In this article, we will demonstrate how to use scikit-learn to determine feature importance using several methods. In machine learning, s
7 min read
Save and Load Machine Learning Models in Python with scikit-learn
In this article, let's learn how to save and load your machine learning model in Python with scikit-learn in this tutorial. Once we create a machine learning model, our job doesn't end there. We can save the model to use in the future. We can either use the pickle or the joblib library for this purpose. The dump method is used to create the model a
4 min read
Identifying Overfitting in Machine Learning Models Using Scikit-Learn
Overfitting is a critical issue in machine learning that can significantly impact the performance of models when applied to new, unseen data. Identifying overfitting in machine learning models is crucial to ensuring their performance generalizes well to unseen data. In this article, we'll explore how to identify overfitting in machine learning mode
7 min read
Types of Boltzmann Machines
Deep Learning models are broadly classified into supervised and unsupervised models. Supervised DL models: Artificial Neural Networks (ANNs)Recurrent Neural Networks (RNNs)Convolutional Neural Networks (CNNs) Unsupervised DL models: Self Organizing Maps (SOMs)Boltzmann MachinesAutoencoders Let us learn what exactly Boltzmann machines are, how they
7 min read
Deep Boltzmann Machines (DBMs) in Deep Learning
In this article, we will discuss the Deep Boltzmann Machines concepts and their applications in the real-world scenario. What are Deep Boltzmann Machines (DBMs)?Deep Boltzmann Machines (DBMs) are a kind of artificial neural network that belongs to the family of generative models. They are designed to discover intricate structures within large datas
10 min read
Map Data to a Normal Distribution in Scikit Learn
A Normal Distribution, also known as a Gaussian distribution, is a continuous probability distribution that is symmetrical around its mean. It is defined by its norm, which is the center of the distribution, and its standard deviation, which is a measure of the spread of the distribution. The normal distribution is often used to model continuous an
5 min read
ML | Implement Face recognition using k-NN with scikit-learn
k-Nearest Neighbors: k-NN is one of the most basic classification algorithms in machine learning. It belongs to the supervised learning category of machine learning. k-NN is often used in search applications where you are looking for “similar” items. The way we measure similarity is by creating a vector representation of the items, and then compare
5 min read
Implementing PCA in Python with scikit-learn
In this article, we will learn about PCA (Principal Component Analysis) in Python with scikit-learn. Let's start our learning step by step. WHY PCA? When there are many input attributes, it is difficult to visualize the data. There is a very famous term ‘Curse of dimensionality in the machine learning domain.Basically, it refers to the fact that a
4 min read
Pipelines - Python and scikit-learn
The workflow of any machine learning project includes all the steps required to build it. A proper ML project consists of basically four main parts are given as follows: Gathering data: The process of gathering data depends on the project it can be real-time data or the data collected from various sources such as a file, database, survey and other
4 min read
How To Create/Customize Your Own Scorer Function In Scikit-Learn?
A well-known Python machine learning toolkit called Scikit-learn provides a variety of machine learning tools and methods to assist programmers in creating sophisticated machine learning models. A strong framework for assessing the effectiveness of these models using a variety of metrics and scoring functions is also offered by Scikit-learn. To ass
4 min read
Clustering Performance Evaluation in Scikit Learn
In this article, we shall look at different approaches to evaluate Clustering Algorithms using Scikit Learn Python Machine Learning Library. Clustering is an Unsupervised Machine Learning algorithm that deals with grouping the dataset to its similar kind data point. Clustering is widely used for Segmentation, Pattern Finding, Search engine, and so
3 min read
Ledoit-Wolf vs OAS Estimation in Scikit Learn
Generally, Shrinkage is used to regularize the usual covariance maximum likelihood estimation. Ledoit and Wolf proposed a formula which is known as the Ledoit-Wolf covariance estimation formula; This close formula can compute the asymptotically optimal shrinkage parameter with minimizing a Mean Square Error(MSE) criterion feature. After that, one r
4 min read
SVM with Univariate Feature Selection in Scikit Learn
Support Vector Machines (SVM) is a powerful machine learning algorithm used for classification and regression analysis. It is based on the idea of finding the optimal boundary between two classes that maximizes the margin between them. However, the challenge with SVM is that it requires a large amount of computational power and is sensitive to the
10 min read
How to Install Scikit-Learn on Linux?
In this article, we are going to see how to install Scikit-Learn on Linux. Scikit-Learn is a python open source library for predictive data analysis. It is built on NumPy, SciPy, and matplotlib. It is written in Python, Cython, C, and C++ language. It is available for Linux, Unix, Windows, and Mac. Method 1: Installing Scikit-Learn from source Step
2 min read
three90RightbarBannerImg