<jupyter_start><jupyter_text>Clustering con Python  Importar el dataset<jupyter_code>import pandas as pd
import numpy as np
from scipy.cluster import vq
df = pd.read_csv("../datasets/wine/winequality-red.csv", sep = ";")
df.head()
df.shape
import matplotlib.pyplot as plt
plt.hist(df["quality"])
plt.xlabel("Calidad")
plt.ylabel("Número de muestras de vino")
df.groupby(df["quality"]).mean()<jupyter_output><empty_output><jupyter_text>* "volatile acidity" y "chlorides" influyen negativamente en la calidad del vino".* "sulphates" y "citric acid" influyen positivamente en la calidad del vino.* "density" y "pH" no influyen en la calidad del vino (muy similares).  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>from sklearn.cluster import AgglomerativeClustering
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")
clus.children_
from scipy.cluster.hierarchy import dendrogram, linkage
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()<jupyter_output><empty_output><jupyter_text>K-means<jupyter_code>from sklearn.cluster import KMeans
from sklearn import datasets
model = KMeans(n_clusters = 6)
model.fit(df_norm)
model.labels_
md_k = pd.Series(model.labels_)
df_norm["Cluster jerárquico"] = md_h
df_norm["Cluster K-Means"] = 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("Cluster K-Means").mean()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13271124935199585, 'fraction_numerical': 0.004665629860031105, 'mean_word_length': 7.693693693693693, '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': '592066', 'license': 'MIT', 'n_tokens_mistral': 771, 'n_tokens_neox': 735, 'n_words': 146, 'path': 'My notebooks/T6 - 4 - Clustering completo.ipynb', 'repo_name': 'DGV1995/Machine-Learning-Data-Science', 'size': '1929'}