The Wayback Machine - https://web.archive.org/web/20240930183310/https://www.geeksforgeeks.org/ml-optics-clustering-implementing-using-sklearn/
Open In App

ML | OPTICS Clustering Implementing using Sklearn

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

Prerequisites: OPTICS Clustering This article will demonstrate how to implement OPTICS Clustering technique using Sklearn in Python. The dataset used for the demonstration is the Mall Customer Segmentation Data which can be downloaded from Kaggle.

Step 1: Importing the required libraries 

OPTICS (Ordering Points To Identify the Clustering Structure) is a density-based clustering algorithm that is used to identify the structure of clusters in high-dimensional data. It is similar to DBSCAN, but it also produces a cluster ordering that can be used to identify the density-based clusters at multiple levels of granularity.

The implementation of OPTICS clustering using scikit-learn (sklearn) is straightforward. You can use the OPTICS class from the sklearn.cluster module. Here is an example of how to use it:

Python




from sklearn.cluster import OPTICS
import numpy as np
  
# Generate sample data
np.random.seed(0)
X = np.random.randn(100, 2)
  
# Initialize the OPTICS clustering model
optics = OPTICS(min_samples=5, xi=0.05, min_cluster_size=0.05)
  
# Fit the model to the data
optics.fit(X)
  
# Get the cluster labels
labels = optics.labels_


In this example, the min_samples parameter controls the minimum number of samples required to form a dense region, the xi parameter controls the maximum distance between two samples to be considered as a neighborhood, and the min_cluster_size parameter controls the minimum size of a dense region to be considered as a cluster.

The fit method is used to fit the model to the data, and the labels_ attribute is used to get the cluster labels for each sample in the data.

Note that the implementation of OPTICS clustering in scikit-learn is based on the original paper by Ankerst, Mihael, and Markus (1999). You might consider reading this paper to learn more about the algorithm.

Python3




import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import gridspec
from sklearn.cluster import OPTICS, cluster_optics_dbscan
from sklearn.preprocessing import normalize, StandardScaler


Step 2: Loading the Data 

Python3




# Changing the working location to the location of the data
cd C:\Users\Dev\Desktop\Kaggle\Customer Segmentation
  
X = pd.read_csv('Mall_Customers.csv')
  
# Dropping irrelevant columns
drop_features = ['CustomerID', 'Gender']
X = X.drop(drop_features, axis = 1)
  
# Handling the missing values if any
X.fillna(method ='ffill', inplace = True)
  
X.head()


Step 3: Preprocessing the Data 

Python3




# Scaling the data to bring all the attributes to a comparable level
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
  
# Normalizing the data so that the data
# approximately follows a Gaussian distribution
X_normalized = normalize(X_scaled)
  
# Converting the numpy array into a pandas DataFrame
X_normalized = pd.DataFrame(X_normalized)
  
# Renaming the columns
X_normalized.columns = X.columns
  
X_normalized.head()


Step 4: Building the Clustering Model 

Python3




# Building the OPTICS Clustering model
optics_model = OPTICS(min_samples = 10, xi = 0.05, min_cluster_size = 0.05)
  
# Training the model
optics_model.fit(X_normalized)


Step 5: Storing the results of the training 

Python3




# Producing the labels according to the DBSCAN technique with eps = 0.5
labels1 = cluster_optics_dbscan(reachability = optics_model.reachability_,
                                   core_distances = optics_model.core_distances_,
                                   ordering = optics_model.ordering_, eps = 0.5)
  
# Producing the labels according to the DBSCAN technique with eps = 2.0
labels2 = cluster_optics_dbscan(reachability = optics_model.reachability_,
                                   core_distances = optics_model.core_distances_,
                                   ordering = optics_model.ordering_, eps = 2)
  
# Creating a numpy array with numbers at equal spaces till
# the specified range
space = np.arange(len(X_normalized))
  
# Storing the reachability distance of each point
reachability = optics_model.reachability_[optics_model.ordering_]
  
# Storing the cluster labels of each point
labels = optics_model.labels_[optics_model.ordering_]
  
print(labels)


Step 6: Visualizing the results 

Python3




# Defining the framework of the visualization
plt.figure(figsize =(10, 7))
G = gridspec.GridSpec(2, 3)
ax1 = plt.subplot(G[0, :])
ax2 = plt.subplot(G[1, 0])
ax3 = plt.subplot(G[1, 1])
ax4 = plt.subplot(G[1, 2])
  
# Plotting the Reachability-Distance Plot
colors = ['c.', 'b.', 'r.', 'y.', 'g.']
for Class, colour in zip(range(0, 5), colors):
    Xk = space[labels == Class]
    Rk = reachability[labels == Class]
    ax1.plot(Xk, Rk, colour, alpha = 0.3)
ax1.plot(space[labels == -1], reachability[labels == -1], 'k.', alpha = 0.3)
ax1.plot(space, np.full_like(space, 2., dtype = float), 'k-', alpha = 0.5)
ax1.plot(space, np.full_like(space, 0.5, dtype = float), 'k-.', alpha = 0.5)
ax1.set_ylabel('Reachability Distance')
ax1.set_title('Reachability Plot')
  
# Plotting the OPTICS Clustering
colors = ['c.', 'b.', 'r.', 'y.', 'g.']
for Class, colour in zip(range(0, 5), colors):
    Xk = X_normalized[optics_model.labels_ == Class]
    ax2.plot(Xk.iloc[:, 0], Xk.iloc[:, 1], colour, alpha = 0.3)
      
ax2.plot(X_normalized.iloc[optics_model.labels_ == -1, 0],
        X_normalized.iloc[optics_model.labels_ == -1, 1],
       'k+', alpha = 0.1)
ax2.set_title('OPTICS Clustering')
  
# Plotting the DBSCAN Clustering with eps = 0.5
colors = ['c', 'b', 'r', 'y', 'g', 'greenyellow']
for Class, colour in zip(range(0, 6), colors):
    Xk = X_normalized[labels1 == Class]
    ax3.plot(Xk.iloc[:, 0], Xk.iloc[:, 1], colour, alpha = 0.3, marker ='.')
        
ax3.plot(X_normalized.iloc[labels1 == -1, 0],
        X_normalized.iloc[labels1 == -1, 1],
       'k+', alpha = 0.1)
ax3.set_title('DBSCAN clustering with eps = 0.5')
  
# Plotting the DBSCAN Clustering with eps = 2.0
colors = ['c.', 'y.', 'm.', 'g.']
for Class, colour in zip(range(0, 4), colors):
    Xk = X_normalized.iloc[labels2 == Class]
    ax4.plot(Xk.iloc[:, 0], Xk.iloc[:, 1], colour, alpha = 0.3)
          
ax4.plot(X_normalized.iloc[labels2 == -1, 0],
        X_normalized.iloc[labels2 == -1, 1],
       'k+', alpha = 0.1)
ax4.set_title('DBSCAN Clustering with eps = 2.0')
  
  
plt.tight_layout()
plt.show()




Similar Reads

Implementing Agglomerative Clustering using Sklearn
Prerequisites: Agglomerative Clustering Agglomerative Clustering is one of the most common hierarchical clustering techniques. Dataset - Credit Card Dataset. Assumption: The clustering technique assumes that each data point is similar enough to the other data points that the data at the starting can be assumed to be clustered in 1 cluster. Step 1:
3 min read
Ordering Points To Identify Cluster Structure (OPTICS) using Sklearn
Sklearn's OPTICS, an acronym for Ordering Points To Identify the Clustering Structure, stands as a powerful tool in the realm of machine learning and data analysis. It is a part of the Scikit-learn library, a popular machine-learning library in Python. OPTICS is particularly adept at uncovering hidden patterns and structures within datasets, making
10 min read
ML | OPTICS Clustering Explanation
Prerequisites: DBSCAN Clustering OPTICS Clustering stands for Ordering Points To Identify Cluster Structure. It draws inspiration from the DBSCAN clustering algorithm. It adds two more terms to the concepts of DBSCAN clustering. OPTICS (Ordering Points To Identify the Clustering Structure) is a density-based clustering algorithm, similar to DBSCAN
7 min read
Mean Shift Clustering using Sklearn
Clustering is a fundamental method in unsupervised device learning, and one powerful set of rules for this venture is Mean Shift clustering. Mean Shift is a technique for grouping comparable data factors into clusters primarily based on their inherent characteristics, with our previous understanding of the number of clusters. This article explores
9 min read
Python Sklearn – sklearn.datasets.load_breast_cancer() Function
In this article, we are going to see how to convert sklearn dataset to a pandas dataframe in Python. Sklearn is a python library that is used widely for data science and machine learning operations. Sklearn library provides a vast list of tools and functions to train machine learning models. The library is available via pip install. pip install sci
2 min read
Implementing DBSCAN algorithm using Sklearn
Prerequisites: DBSCAN Algorithm Density Based Spatial Clustering of Applications with Noise(DBCSAN) is a clustering algorithm which was proposed in 1996. In 2014, the algorithm was awarded the 'Test of Time' award at the leading Data Mining conference, KDD. Dataset - Credit Card Step 1: Importing the required libraries import numpy as np import pan
3 min read
ML | Implementing L1 and L2 regularization using Sklearn
Prerequisites: L2 and L1 regularizationThis article aims to implement the L2 and L1 regularization for Linear regression using the Ridge and Lasso modules of the Sklearn library of Python. Dataset - House prices dataset.Step 1: Importing the required libraries C/C++ Code import pandas as pd import numpy as np import matplotlib.pyplot as plt from sk
3 min read
DBSCAN Clustering in ML | Density based clustering
Clustering analysis or simply Clustering is basically an Unsupervised learning method that divides the data points into a number of specific batches or groups, such that the data points in the same groups have similar properties and data points in different groups have different properties in some sense. It comprises many different methods based on
7 min read
Difference between CURE Clustering and DBSCAN Clustering
Clustering is a technique used in Unsupervised learning in which data samples are grouped into clusters on the basis of similarity in the inherent properties of the data sample. Clustering can also be defined as a technique of clubbing data items that are similar in some way. The data items belonging to the same clusters are similar to each other i
2 min read
Difference Between Agglomerative clustering and Divisive clustering
Hierarchical clustering is a popular unsupervised machine learning technique used to group similar data points into clusters based on their similarity or dissimilarity. It is called "hierarchical" because it creates a tree-like hierarchy of clusters, where each node represents a cluster that can be further divided into smaller sub-clusters. There a
5 min read
Python | Decision Tree Regression using sklearn
Decision Tree is a decision-making tool that uses a flowchart-like tree structure or is a model of decisions and all of their possible results, including outcomes, input costs, and utility.Decision-tree algorithm falls under the category of supervised learning algorithms. It works for both continuous as well as categorical output variables. The bra
4 min read
Python | Create Test DataSets using Sklearn
Python's Sklearn library provides a great sample dataset generator which will help you to create your own custom dataset. It's fast and very easy to use. Following are the types of samples it provides.For all the above methods you need to import sklearn.datasets.samples_generator. C/C++ Code # importing libraries from sklearn.datasets import make_b
3 min read
ML | Implementation of KNN classifier using Sklearn
Prerequisite: K-Nearest Neighbours Algorithm K-Nearest Neighbors is one of the most basic yet essential classification algorithms in Machine Learning. It belongs to the supervised learning domain and finds intense application in pattern recognition, data mining and intrusion detection. It is widely disposable in real-life scenarios since it is non-
2 min read
ML | Dummy classifiers using sklearn
A dummy classifier is a type of classifier which does not generate any insight about the data and classifies the given data using only simple rules. The classifier's behavior is completely independent of the training data as the trends in the training data are completely ignored and instead uses one of the strategies to predict the class label. It
3 min read
ML | Ridge Regressor using sklearn
A Ridge regressor is basically a regularized version of a Linear Regressor. i.e to the original cost function of linear regressor we add a regularized term that forces the learning algorithm to fit the data and helps to keep the weights lower as possible. The regularized term has the parameter 'alpha' which controls the regularization of the model
3 min read
ML | Voting Classifier using Sklearn
A Voting Classifier is a machine learning model that trains on an ensemble of numerous models and predicts an output (class) based on their highest probability of chosen class as the output. It simply aggregates the findings of each classifier passed into Voting Classifier and predicts the output class based on the highest majority of voting. The i
3 min read
Data Pre-Processing with Sklearn using Standard and Minmax scaler
Data Scaling is a data preprocessing step for numerical features. Many machine learning algorithms like Gradient descent methods, KNN algorithm, linear and logistic regression, etc. require data scaling to produce good results. Various scalers are defined for this purpose. This article concentrates on Standard Scaler and Min-Max scaler. The task he
3 min read
How To Do Train Test Split Using Sklearn In Python
In this article, let's learn how to do a train test split using Sklearn in Python. Train Test Split Using Sklearn The train_test_split() method is used to split our data into train and test sets. First, we need to divide our data into features (X) and labels (y). The dataframe gets divided into X_train,X_test , y_train and y_test. X_train and y_tra
5 min read
Classification Using Sklearn Multi-layer Perceptron
A key machine learning method that belongs to the class of artificial neural networks is classification using Multi-Layer Perceptrons (MLP). It is a flexible and effective method for tackling a variety of classification problems, including text classification and picture recognition. Traditional linear classifiers might not be up to the challenge,
7 min read
Classification Metrics using Sklearn
Machine learning classification is a powerful tool that helps us make predictions and decisions based on data. Whether it's determining whether an email is spam or not, diagnosing diseases from medical images, or predicting customer churn, classification algorithms are at the heart of many real-world applications. However, the mere creation of a cl
14 min read
Canonical Correlation Analysis (CCA) using Sklearn
Canonical Correlation Analysis (CCA) is a statistical method used in data analysis to identify and quantify the relationships between two sets of variables. When working with multivariate data—that is, when there are several variables in each of the two sets and we want to know how they connect—it is very helpful. This post will explain CCA, go ove
10 min read
Gaussian Naive Bayes using Sklearn
In the world of machine learning, Gaussian Naive Bayes is a simple yet powerful algorithm used for classification tasks. It belongs to the Naive Bayes algorithm family, which uses Bayes' Theorem as its foundation. The goal of this post is to explain the Gaussian Naive Bayes classifier and offer a detailed implementation tutorial for Python users ut
8 min read
Partial Least Squares Regression (PLSRegression) using Sklearn
Partial least square regression is a Machine learning Algorithm used for modelling the relationship between independent and dependent variables. This is mainly used when there are many interrelated independent variables. It is more commonly used in regression and latent variable modelling. It finds the directions (latent variables) in the independe
8 min read
Linear and Quadratic Discriminant Analysis using Sklearn
Linear Discriminant Analysis (LDA) and Quadratic Discriminant Analysis (QDA) are two well-known classification methods that are used in machine learning to find patterns and put things into groups. They are especially helpful when you have labeled data and want to classify new observations notes into pre-defined categories. In this we will implemen
5 min read
Bag of word and Frequency count in text using sklearn
Text data is ubiquitous in today's digital world, from emails and social media posts to research articles and customer reviews. To analyze and derive insights from this textual information, it's essential to convert text into a numerical form that machine learning algorithms can process. One of the fundamental methods for this conversion is the "Ba
3 min read
Python | Linear Regression using sklearn
Prerequisite: Linear Regression Linear Regression is a machine learning algorithm based on supervised learning. It performs a regression task. Regression models a target prediction value based on independent variables. It is mostly used for finding out the relationship between variables and forecasting. Different regression models differ based on –
3 min read
Target encoding using nested CV in sklearn pipeline
In machine learning, feature engineering plays a pivotal role in enhancing model performance. One such technique is target encoding, which is particularly useful for categorical variables. However, improper implementation can lead to data leakage and overfitting. This article delves into the intricacies of target encoding using nested cross-validat
7 min read
How to Perform Ordinal Encoding Using Sklearn
Have you ever played a game where you rank things, like your favorite pizza toppings or the scariest monsters? In the field of computers, it is essentially what ordinal encoding accomplishes! It converts ordered data, such as "small," "medium", and "large," into numerical values that a computer can comprehend. Understanding Ordinal EncodingWhat is
6 min read
Changing Colors for Decision Tree Plot Using Sklearn plot_tree
Decision trees are a popular machine learning model used for classification and regression tasks. Visualizing decision trees can provide insights into the decision-making process of the model, making it easier to interpret and explain the results. Scikit-learn, a widely used machine learning library in Python, offers a convenient method called plot
4 min read
SHAP with a Linear SVC model from Sklearn Using Pipeline
SHAP (SHapley Additive exPlanations) is a powerful tool for interpreting machine learning models by assigning feature importance based on Shapley values. In this article, we will explore how to integrate SHAP with a linear SVC model from Scikit-learn using a Pipeline. We'll provide an overview of SHAP, discuss how to build an SVC model, and illustr
5 min read
Article Tags :
Practice Tags :