<jupyter_start><jupyter_text>MeanShift Clustering<jupyter_code># load libraries

import matplotlib.pyplot as plt
from sklearn.cluster import MeanShift
from sklearn.datasets.samples_generator import make_blobs

%matplotlib inline
# define the centers
centers = [[1,1],[4,4]]
# generate random data
# n_samples - sample size
# data should lie around centers
# with a standard devaition of 1

# y is not required here, hence _

X, _ = make_blobs(n_samples=400, centers=centers, cluster_std=1)
X.shape
x0, x1 = X[:,0], X[:,1]
x0.shape, x1.shape
plt.scatter(x0, x1, )<jupyter_output><empty_output><jupyter_text>Clustering using MeanShift<jupyter_code># MeanShift()
ms = MeanShift()
# fit - applying the formula on the variable
ms.fit(X)
labels = ms.labels_
labels
cluster_centers = ms.cluster_centers_
cluster_centers
# number of clusters
n_clusters_ = len(set(labels))
n_clusters_
# define the colors
colors = ['g','r','y','c']
colors
# plotting between x0 and x1

for i in range(len(X)):
    plt.plot(x0[i], x1[i], colors[labels[i]], marker='+', markersize=10)
# plotting between x0 and x1

for i in range(len(X)):
    plt.plot(x0[i], x1[i], colors[labels[i]], marker='+', markersize=10)

plt.scatter(cluster_centers[:,0], cluster_centers[:,1], marker='o',
           linewidths=5, zorder=10)
# we will create one more cluster 
# increase the number of samples
# and increase the std dev to 3
centers = [[1,1],[5,5],[9,9]]

X, _ = make_blobs(n_samples=500, centers=centers, cluster_std=1)

x0, x1 = X[:,0], X[:,1]

plt.scatter(x0, x1, )
ms = MeanShift()
ms.fit(X)
labels = ms.labels_

cluster_centers = ms.cluster_centers_

n_clusters_ = len(set(labels))
print(n_clusters_)

# the algorithm has identified 3 clusters
cluster_centers, labels
# plotting between x0 and x1

for i in range(len(X)):
    plt.plot(x0[i], x1[i], colors[labels[i]], marker='+', markersize=10)

plt.scatter(cluster_centers[:,0], cluster_centers[:,1], marker='o',
           linewidths=5, zorder=10)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14307153576788395, 'fraction_numerical': 0.03151575787893947, 'mean_word_length': 5.666666666666667, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '270366', 'license': 'MIT', 'n_tokens_mistral': 773, 'n_tokens_neox': 750, 'n_words': 191, 'path': 'machinelearning/clustering/ml_python_clustering_meanshift_1.ipynb', 'repo_name': 'futureseadev/hgwxx7', 'size': '1999'}