Recipe: How to do Affinity based Clustering in Python?
MACHINE LEARNING RECIPES

How to do Affinity based Clustering in Python?

This recipe helps you do Affinity based Clustering in Python
In [2]:
## How to do Affinity based Clustering in Python
def Snippet_158():
    print()
    print(format('How to do Affinity based Clustering in Python','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    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

    # Load data
    iris = datasets.load_iris()
    X = iris.data; data = pd.DataFrame(X)
    cor = data.corr()

    fig = plt.figure(figsize=(10,10));
    sns.heatmap(cor, square = True); plt.show()

    # Standarize features
    scaler = StandardScaler()
    X_std = scaler.fit_transform(X)

    # Conduct AffinityPropagation Clustering
    clt = AffinityPropagation(damping=0.5, max_iter=500, affinity='euclidean')

    # Train model
    model = clt.fit(X_std)
    n_clusters_ = len(model.cluster_centers_indices_)
    print('Number of Clusters: ',n_clusters_)

    # Predict clusters
    clusters = pd.DataFrame(model.fit_predict(X_std))
    data['Cluster'] = clusters

    # Visualise cluster membership
    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); plt.show()

Snippet_158()
******************How to do Affinity based Clustering in Python*******************
Number of Clusters:  9


Stuck at work?
Can't find the recipe you are looking for. Let us know and we will find an expert to create the recipe for you. Click here
Companies using this Recipe