How to do Affinity based Clustering in Python?

How to do Affinity based Clustering in Python?

How to do Affinity based Clustering in Python?

This recipe helps you do Affinity based Clustering in Python


Recipe Objective

Have you ever tried to do affinity based Clustering in python? Clustering can give us an idea that how the data set is in groups and affinity based is very usefull sometimes.

So this is the recipe on how we can do Affinity based Clustering in Python.

Step 1 - Import the library

from sklearn import datasets from sklearn.preprocessing import StandardScaler from sklearn.cluster import AffinityPropagation import pandas as pd import seaborn as sns import matplotlib.pyplot as plt

We have imported datasets, StandardScaler, AffinityPropagation, pandas, and seaborn which will be needed for the dataset.

Step 2 - Setting up the Data

We have imported inbuilt wine dataset and stored data in x. We have plotted a heatmap for corelation of features. wine = datasets.load_wine() X =; data = pd.DataFrame(X) cor = data.corr() fig = plt.figure(figsize=(10,10)); sns.heatmap(cor, square = True);

Step 3 - Training model and Predicting Clusters

Here we we are first standarizing the data by standardscaler. scaler = StandardScaler() X_std = scaler.fit_transform(X) Now we are using AffinityPropagation for clustering with features:

  • damping: It is the extent to which the current value is maintained relative to incoming values, by default it is 0.5
  • max_iter: It is the number of iteration we want to do
  • affinity: In this we have to choose between euclidean and precomputed.
clt = AffinityPropagation(damping=0.5, max_iter=500, affinity="euclidean") We are training the data by using and printing the number of clusters. model = n_clusters_ = len(model.cluster_centers_indices_) print("Number of Clusters: ",n_clusters_) Finally we are predicting the clusters. clusters = pd.DataFrame(model.fit_predict(X_std)) data["Cluster"] = clusters

Step 4 - Visualizing the output

fig = plt.figure(figsize=(10,10)); ax = fig.add_subplot(111) scatter = ax.scatter(data[0],data[1], c=data["Cluster"],s=50) ax.set_title("AffinityPropagation Clustering") ax.set_xlabel("X0"); ax.set_ylabel("X1") plt.colorbar(scatter);

We have plot a sactter plot which will show the clusters of data in different colour,

Relevant Projects

Learn to prepare data for your next machine learning project
Text data requires special preparation before you can start using it for any machine learning project.In this ML project, you will learn about applying Machine Learning models to create classifiers and learn how to make sense of textual data.

Forecast Inventory demand using historical sales data in R
In this machine learning project, you will develop a machine learning model to accurately forecast inventory demand based on historical sales data.

Zillow’s Home Value Prediction (Zestimate)
Data Science Project in R -Build a machine learning algorithm to predict the future sale prices of homes.

Build an Image Classifier for Plant Species Identification
In this machine learning project, we will use binary leaf images and extracted features, including shape, margin, and texture to accurately identify plant species using different benchmark classification techniques.

Data Science Project-TalkingData AdTracking Fraud Detection
Machine Learning Project in R-Detect fraudulent click traffic for mobile app ads using R data science programming language.

Ecommerce product reviews - Pairwise ranking and sentiment analysis
This project analyzes a dataset containing ecommerce product reviews. The goal is to use machine learning models to perform sentiment analysis on product reviews and rank them based on relevance. Reviews play a key role in product recommendation systems.

Predict Credit Default | Give Me Some Credit Kaggle
In this data science project, you will predict borrowers chance of defaulting on credit loans by building a credit score prediction model.

Resume parsing with Machine learning - NLP with Python OCR and Spacy
In this machine learning resume parser example we use the popular Spacy NLP python library for OCR and text classification.

Predict Macro Economic Trends using Kaggle Financial Dataset
In this machine learning project, you will uncover the predictive value in an uncertain world by using various artificial intelligence, machine learning, advanced regression and feature transformation techniques.

Machine Learning project for Retail Price Optimization
In this machine learning pricing project, we implement a retail price optimization algorithm using regression trees. This is one of the first steps to building a dynamic pricing model.