<jupyter_start><jupyter_text>Clustering Implementation<jupyter_code>from sklearn.cluster import KMeans

kmeans = KMeans(n_clusters=5)
kmeans.fit(df)
y_kmeans = kmeans.predict(df)
centroids = kmeans.cluster_centers_
plt.scatter(df.Age, df.Income, c=y_kmeans, s=50, cmap='viridis')
# Try a few different values of K; we'll decide later what's the best.
K = range(1,6)
fits = [KMeans(n_clusters=k, init='k-means++', max_iter=5000, n_init=30, verbose=False, random_state=42).fit(df) for k in K]
centroids = [fit.cluster_centers_ for fit in fits]
inertias = [fit.inertia_ for fit in fits]
clusters_df = pd.DataFrame( { "num_clusters":K, "cluster_errors": inertias } )
plt.figure(figsize=(12,6))
plt.plot( clusters_df.num_clusters, clusters_df.cluster_errors, marker = "o" )
plt.show()
k = 4 
km = fits[k]

cluster_terms = []
order_centroids = km.cluster_centers_.argsort()[:, ::-1]
for i in range(k):
    print("Cluster {:>2} ({:>4} customer):".format(i, len([x for x in km.labels_ if x == i])), end='')
    cterms = []
    cluster_terms.append(' '.join(cterms))
    print("")<jupyter_output>Cluster  0 ( 115 customer):
Cluster  1 (  85 customer):
Cluster  2 ( 157 customer):
Cluster  3 (  87 customer):<jupyter_text>DBSCAN<jupyter_code>from sklearn.cluster import DBSCAN

db = DBSCAN(eps=3, min_samples=2).fit(df)
labels = db.labels_
labels
# Black removed and is used for noise instead.
unique_labels = set(labels)
colors = [plt.cm.Spectral(each)
          for each in np.linspace(0, 1, len(unique_labels))]
for k, col in zip(unique_labels, colors):
    if k == -1:
        # Black used for noise.
        col = [0, 0, 0, 1]

    class_member_mask = (labels == k)

    xy = df[class_member_mask & core_samples_mask]
    plt.plot(xy.Age, xy.Income, 'o', markerfacecolor=tuple(col),
             markeredgecolor='k', markersize=14)

    xy = df[class_member_mask & ~core_samples_mask]
    plt.plot(xy.Age, xy.Income, 'o', markerfacecolor=tuple(col),
             markeredgecolor='k', markersize=6)

plt.title('Estimated number of clusters: %d' % db.labels_)
plt.show()
core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
#Gaussian
from sklearn.mixture import GaussianMixture

gmm = GaussianMixture(n_components=5, covariance_type='full').fit(df)

labels = gmm.predict(df)

gmm<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14434330299089726, 'fraction_numerical': 0.02037277850021673, 'mean_word_length': 4.784461152882206, 'pattern_counts': {'":': 2, '<': 8, '<?xml version=': 0, '>': 10, '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': '373949', 'license': 'MIT', 'n_tokens_mistral': 925, 'n_tokens_neox': 867, 'n_words': 198, 'path': 'Jewelery/Jewelry.ipynb', 'repo_name': 'hhaggan/Machine-Learning-Hands-On', 'size': '2307'}