from sklearn.cluster import AffinityPropagation from sklearn.datasets import make_blobs # Generate random data X, _ = make_blobs(n_samples=1000, centers=5, random_state=42) # Initialize AffinityPropagation clustering with default parameters model = AffinityPropagation() # Fit the data to the model and predict clusters labels = model.fit_predict(X) # Print the resulting labels print(labels)
from sklearn.cluster import AffinityPropagation from sklearn.datasets import make_moons import matplotlib.pyplot as plt # Generate two moon shaped clusters X, _ = make_moons(n_samples=1000, noise=0.1) # Initialize AffinityPropagation clustering with a preference parameter model = AffinityPropagation(preference=-5) # Fit the data to the model and predict clusters labels = model.fit_predict(X) # Visualize the resulting clusters plt.scatter(X[:, 0], X[:, 1], c=labels) plt.show()In this example, we are generating two moon-shaped clusters using the make_moons function and then using the AffinityPropagation algorithm to cluster the data. The resulting clusters are visualized using a scatter plot. Overall, the AffinityPropagation algorithm is a powerful clustering tool included in the sklearn package library.