<jupyter_start><jupyter_text>Clustering con Python<jupyter_code>import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import AgglomerativeClustering
from scipy.cluster.hierarchy import dendrogram, linkage
from sklearn.cluster import KMeans
df = pd.read_csv("../datasets/wine/winequality-red.csv", sep = ";")
df.head()
df.shape
plt.hist(df["quality"])
df.groupby("quality").mean()<jupyter_output><empty_output><jupyter_text>Normalización de los datos<jupyter_code>df_norm = (df-df.min())/(df.max()-df.min())
df_norm.head()<jupyter_output><empty_output><jupyter_text>Clustering jerárquico con Scikit-learn<jupyter_code>clus= AgglomerativeClustering(n_clusters=6, linkage="ward").fit(df_norm)
md_h = pd.Series(clus.labels_)
plt.hist(md_h)
plt.title("Histograma de los clusters")
plt.xlabel("Cluster")
plt.ylabel("Número de vinos del cluster")
Z = linkage(df_norm, "ward")
plt.figure(figsize=(25,10))
plt.title("Dendrograma de los vinos")
plt.xlabel("ID del vino")
plt.ylabel("Distancia")
dendrogram(Z, leaf_rotation=90., leaf_font_size=4.)
plt.show()
plt.figure(figsize=(25,10))
plt.title("Dendrograma de los vinos")
plt.xlabel("ID del vino")
plt.ylabel("Distancia")
dendrogram(Z, leaf_rotation=90., leaf_font_size=4., truncate_mode="lastp", p=12, show_leaf_counts=True, show_contracted=True,)
plt.axhline(y=4.5, c='k')
plt.show()<jupyter_output><empty_output><jupyter_text>K-Means<jupyter_code>model = KMeans(n_clusters=6)
model.fit(df_norm)
model.labels_
md_k = pd.Series(model.labels_)
df_norm["clust_h"] = md_h
df_norm["clust_k"] = md_k
df_norm.head()
plt.hist(md_k)
model.cluster_centers_
model.inertia_<jupyter_output><empty_output><jupyter_text>Interpretación Final<jupyter_code>df_norm.groupby("clust_k").mean()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15410764872521246, 'fraction_numerical': 0.0113314447592068, 'mean_word_length': 9.267441860465116, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 21, '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': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '492466', 'license': 'MIT', 'n_tokens_mistral': 751, 'n_tokens_neox': 711, 'n_words': 102, 'path': 'MaPeCode_Notebooks/18. Clustering completo.ipynb', 'repo_name': 'mapecode/python-ml-course', 'size': '1765'}