How to do Affinity based Clustering in Python?
MACHINE LEARNING RECIPES DATA CLEANING PYTHON DATA MUNGING PANDAS CHEATSHEET     ALL TAGS

# How to do Affinity based Clustering in Python?

This recipe helps you do Affinity based Clustering in Python

1

## 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 = wine.data; data = pd.DataFrame(X) cor = data.corr() fig = plt.figure(figsize=(10,10)); sns.heatmap(cor, square = True); plt.show() ```

## 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 clt.fit and printing the number of clusters. ``` model = clt.fit(X_std) 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,data, c=data["Cluster"],s=50) ax.set_title("AffinityPropagation Clustering") ax.set_xlabel("X0"); ax.set_ylabel("X1") plt.colorbar(scatter); plt.show() ```

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

```
```

#### Relevant Projects

##### Data Science Project on Wine Quality Prediction in R
In this R data science project, we will explore wine dataset to assess red wine quality. The objective of this data science project is to explore which chemical properties will influence the quality of red wines.

##### Data Science Project in Python on BigMart Sales Prediction
The goal of this data science project is to build a predictive model and find out the sales of each product at a given Big Mart store.

##### Data Science Project - Instacart Market Basket Analysis
Data Science Project - Build a recommendation engine which will predict the products to be purchased by an Instacart consumer again.

##### Machine Learning or Predictive Models in IoT - Energy Prediction Use Case
In this machine learning and IoT project, we are going to test out the experimental data using various predictive models and train the models and break the energy usage.

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

##### PySpark Tutorial - Learn to use Apache Spark with Python
PySpark Project-Get a handle on using Python with Spark through this hands-on data processing spark python tutorial.

##### Sequence Classification with LSTM RNN in Python with Keras
In this project, we are going to work on Sequence to Sequence Prediction using IMDB Movie Review Dataset​ using Keras in Python.

##### Perform Time series modelling using Facebook Prophet
In this project, we are going to talk about Time Series Forecasting to predict the electricity requirement for a particular house using Prophet.

##### Predict Churn for a Telecom company using Logistic Regression
Machine Learning Project in R- Predict the customer churn of telecom sector and find out the key drivers that lead to churn. Learn how the logistic regression model using R can be used to identify the customer churn in telecom dataset.

##### Choosing the right Time Series Forecasting Methods
There are different time series forecasting methods to forecast stock price, demand etc. In this machine learning project, you will learn to determine which forecasting method to be used when and how to apply with time series forecasting example.