### Install DenseClus Source: https://github.com/awslabs/amazon-denseclus/blob/main/README.md Use pip to install the package from PyPI. ```bash python3 -m pip install amazon-denseclus ``` -------------------------------- ### Install Dependencies Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/01_DenseClusExampleNB.ipynb Install required visualization libraries using pip. ```python %pip install matplotlib seaborn -q ``` -------------------------------- ### Quick Start Clustering Source: https://github.com/awslabs/amazon-denseclus/blob/main/README.md Initialize the model with a pandas DataFrame and perform clustering. ```python from denseclus import DenseClus from denseclus.utils import make_dataframe df = make_dataframe() clf = DenseClus(df) clf.fit(df) scores = clf.evaluate() print(scores[0:10]) ``` -------------------------------- ### Install required packages Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/02_TuningWithHDBSCAN.ipynb Install necessary libraries for data visualization and notebook management. ```python %pip install matplotlib seaborn -q %pip install --upgrade ipywidgets -q %pip install --upgrade jupyter -q ``` -------------------------------- ### Install dependencies Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/03_ValidationForUMAP.ipynb Install or upgrade Jupyter and ipywidgets in the current environment. ```python %pip install --upgrade jupyter -q %pip install --upgrade ipywidgets -q ``` -------------------------------- ### Initialize environment and load data Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/03_ValidationForUMAP.ipynb Import necessary libraries, configure plotting styles, and load the churn dataset from a remote URL. ```python # To supress deprecation warnings import logging from warnings import filterwarnings import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from umap import validation from denseclus import DenseClus %matplotlib inline sns.set_style("darkgrid", {"axes.facecolor": ".9"}) sns.set(rc={"figure.figsize": (10, 8)}) SEED = 42 np.random.seed(SEED) # set the random seed as best we can data_url = ( "https://raw.githubusercontent.com/awslabs/aws-customer-churn-pipeline/main/data/churn.txt" ) df = pd.read_csv(data_url).sample(n=2000, random_state=SEED) df.drop(["Phone", "Area Code"], axis=1, inplace=True) ``` -------------------------------- ### Import libraries and load dataset Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/02_TuningWithHDBSCAN.ipynb Initialize the environment, import dependencies, and load the churn dataset for clustering analysis. ```python import logging # to further silence deprecation warnings import warnings import hdbscan import joblib import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from hdbscan.validity import validity_index from sklearn import metrics, preprocessing from sklearn.metrics import make_scorer from sklearn.model_selection import RandomizedSearchCV # This runs in about a minute or two from denseclus import DenseClus warnings.filterwarnings("ignore") %matplotlib inline sns.set_style("darkgrid", {"axes.facecolor": ".9"}) sns.set(rc={"figure.figsize": (10, 8)}) SEED = 42 np.random.seed(SEED) # set the random seed to reproduce resulst as best we can # see: https://umap-learn.readthedocs.io/en/latest/reproducibility.html data_url = ( "https://raw.githubusercontent.com/awslabs/aws-customer-churn-pipeline/main/data/churn.txt" ) df = pd.read_csv(data_url) df.drop(["Phone", "Area Code"], axis=1, inplace=True) df.head(5) ``` -------------------------------- ### Initialize DenseClus Environment Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/04_JumpstartDenseClus.ipynb Import required libraries and configure plotting settings for the DenseClus workflow. ```python import io import boto3 import hdbscan import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import umap.umap_ as umap from denseclus import DenseClus from denseclus.categorical import extract_categorical from denseclus.numerical import extract_numerical SEED = 42 # random seed to set reproducibility as best we can sns.set_style("darkgrid") sns.set_context("notebook") %matplotlib inline ``` -------------------------------- ### Load and Sample Data Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/01_DenseClusExampleNB.ipynb Set a random seed and load the churn dataset from a remote URL. ```python SEED = 42 np.random.seed(SEED) # set the random seed as best we can data_url = ( "https://raw.githubusercontent.com/awslabs/aws-customer-churn-pipeline/main/data/churn.txt" ) df = pd.read_csv(data_url).sample(n=2000, random_state=SEED) ``` -------------------------------- ### Enable GPU Acceleration Source: https://github.com/awslabs/amazon-denseclus/blob/main/README.md Set use_gpu to True to leverage RAPIDS for computation. ```python clf = DenseClus( umap_combine_method="ensemble", use_gpu=True ) ``` -------------------------------- ### Initialize and Fit DenseClus Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/02_TuningWithHDBSCAN.ipynb Initializes the DenseClus model and fits it to the input dataframe. ```python logging.captureWarnings(True) clf = DenseClus(random_state=SEED, umap_combine_method="intersection") clf.fit(df) ``` -------------------------------- ### Import Libraries Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/01_DenseClusExampleNB.ipynb Import necessary data science libraries and the DenseClus package. ```python import warnings import joblib import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from sklearn import metrics, preprocessing from denseclus import DenseClus %matplotlib inline warnings.filterwarnings("ignore") ``` -------------------------------- ### Initialize and Fit DenseClus Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/04_JumpstartDenseClus.ipynb Configures the DenseClus model with the intersection_union_mapper method and fits it to the dataset. ```python ium_clf = DenseClus(random_state=SEED, umap_combine_method="intersection_union_mapper") ium_clf.fit(df) labels = ium_clf.evaluate() ``` -------------------------------- ### Configure Combination Method Source: https://github.com/awslabs/amazon-denseclus/blob/main/README.md Select intersection_union_mapper for more stable results at the cost of performance. ```python clf = DenseClus( umap_combine_method="intersection_union_mapper", ) ``` -------------------------------- ### Configure Visualization Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/01_DenseClusExampleNB.ipynb Set the aesthetic style and figure size for seaborn plots. ```python sns.set_style("darkgrid", {"axes.facecolor": ".9"}) sns.set(rc={"figure.figsize": (10, 8)}) ``` -------------------------------- ### Execute DenseClus with Multiple Combination Methods Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/04_JumpstartDenseClus.ipynb Iterates through supported UMAP combination methods to fit the DenseClus model and visualize results. ```python methods = ["intersection", "union", "contrast", "intersection_union_mapper", "ensemble"] hdbscan_params = { "min_cluster_size": 200, "min_samples": 30, "gen_min_span_tree": True, "metric": "manhattan", "cluster_selection_method": "eom", } for method in methods: print(f"Running combination method: {method}") clf = DenseClus(random_state=SEED, umap_combine_method=method) clf.fit(df) clusters = clf.evaluate() n_clusters = len(np.unique(clusters)) print(f"Number of clusters: {n_clusters}") if hasattr(clf, "mapper_"): embeddings = clf.mapper_.embedding_ else: embeddings = clf.numerical_umap_.embedding_ plot_clusters(method, embeddings, clusters) print("-" * 30) ``` -------------------------------- ### Download and Load Census Income Data Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/04_JumpstartDenseClus.ipynb Retrieve the dataset from S3 and load it into a Pandas DataFrame with assigned column names. ```python s3 = boto3.client("s3") region = boto3.session.Session().region_name ## read the data s3.download_file( f"sagemaker-example-files-prod-{region}", "datasets/tabular/uci_adult/adult.data", "adult.data" ) df = pd.read_csv("adult.data", header=None) ## set column names df.columns = [ "age", "workclass", "fnlwgt", "education", "education-num", "marital-status", "occupation", "relationship", "race", "sex", "capital-gain", "capital-loss", "hours-per-week", "native-country", "IncomeGroup", ] df.head() ``` -------------------------------- ### Visualize Clusters with Jointplot Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/02_TuningWithHDBSCAN.ipynb Creates a KDE jointplot to visualize the density of the identified clusters. ```python _ = sns.jointplot( x=embedding[clustered, 0], y=embedding[clustered, 1], hue=labels[clustered], kind="kde" ) ``` -------------------------------- ### Cite UMAP Algorithm Source: https://github.com/awslabs/amazon-denseclus/blob/main/README.md BibTeX citation for the UMAP algorithm. ```bibtex @article{mcinnes2018umap-software, title={UMAP: Uniform Manifold Approximation and Projection}, author={McInnes, Leland and Healy, John and Saul, Nathaniel and Grossberger, Lukas}, journal={The Journal of Open Source Software}, volume={3}, number={29}, pages={861}, year={2018} } ``` -------------------------------- ### Define UMAP and HDBSCAN Parameters Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/04_JumpstartDenseClus.ipynb Configuration dictionaries for UMAP dimensionality reduction and HDBSCAN clustering algorithms. ```python default_umap_params = { "categorical": { "metric": "hamming", "n_neighbors": 30, "n_components": 5, "min_dist": 0.0, }, "numerical": { "metric": "l2", "n_neighbors": 30, "n_components": 5, "min_dist": 0.0, }, } hdbscan_params = { "min_cluster_size": 100, "min_samples": 15, "gen_min_span_tree": True, "metric": "euclidean", } ``` -------------------------------- ### Advanced Parameter Tuning Source: https://github.com/awslabs/amazon-denseclus/blob/main/README.md Pass custom dictionaries to control UMAP and HDBSCAN hyperparameters. ```python from denseclus import DenseClus from denseclus.utils import make_dataframe umap_params = { "categorical": {"n_neighbors": 15, "min_dist": 0.1}, "numerical": {"n_neighbors": 20, "min_dist": 0.1}, } hdbscan_params = {"min_cluster_size": 10} df = make_dataframe() clf = DenseClus(umap_combine_method="union" , umap_params=umap_params , hdbscan_params=hdbscan_params , random_state=None) # this will run in parallel clf.fit(df) ``` -------------------------------- ### Preprocess Data Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/01_DenseClusExampleNB.ipynb Remove unnecessary columns and inspect the data types of the remaining features. ```python df.drop(["Phone", "Area Code"], axis=1, inplace=True) df.dtypes ``` -------------------------------- ### Fit UMAP for Clustering Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/02_TuningWithHDBSCAN.ipynb Prepares numerical data for clustering by fitting a UMAP embedding. ```python # Fit a UMAP to the data to cluster on numerics_df = df.select_dtypes(include=[int, float]) fitted_umap = umap.UMAP(n_components=5, n_neighbors=30, min_dist=0.0).fit(numerics_df) ``` -------------------------------- ### Plot Condensed Tree Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/02_TuningWithHDBSCAN.ipynb Visualizes the condensed tree of the HDBSCAN clustering process. ```python _ = clf.hdbscan_.condensed_tree_.plot( select_clusters=True, selection_palette=sns.color_palette("deep", np.unique(clustered).shape[0]), ) ``` -------------------------------- ### Fit DenseClus model Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/03_ValidationForUMAP.ipynb Configure and fit the DenseClus model using specified HDBSCAN parameters and UMAP combination methods. ```python logging.captureWarnings(True) hdbscan_params = {"cluster_selection_method": "leaf"} clf = DenseClus( random_state=SEED, hdbscan_params=hdbscan_params, umap_combine_method="intersection_union_mapper", ) clf.fit(df) logging.captureWarnings(False) ``` -------------------------------- ### Cite HDBSCAN Algorithm Source: https://github.com/awslabs/amazon-denseclus/blob/main/README.md BibTeX citation for the HDBSCAN algorithm. ```bibtex @article{mcinnes2017hdbscan, title={hdbscan: Hierarchical density based clustering}, author={McInnes, Leland and Healy, John and Astels, Steve}, journal={The Journal of Open Source Software}, volume={2}, number={11}, pages={205}, year={2017} } ``` -------------------------------- ### Profile Categorical Clusters Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/01_DenseClusExampleNB.ipynb Identify categorical columns for profiling and generate bar plots for each to visualize distribution across segments. ```python categorical = df.select_dtypes(include=["object"]).drop(labels=["State"], axis=1) ``` ```python for c in categorical.columns: df.groupby(["segment"] + [c]).size().plot( kind="bar", color=sns.color_palette("deep", np.unique(labels).shape[0]) ) plt.title(c) plt.show() ``` -------------------------------- ### Calculate Coverage and DBCV Score Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/02_TuningWithHDBSCAN.ipynb Computes the percentage of data points assigned to clusters and the final DBCV score. ```python coverage = np.sum(clustered) / embedding.shape[0] print(f"Coverage {coverage}") print(f"DBCV score {clf.hdbscan_.relative_validity_}") ``` -------------------------------- ### Visualize Embedding Density Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/04_JumpstartDenseClus.ipynb Uses kernel density estimation to verify the distribution of the generated embeddings. ```python for i in range(len(ium_clf.mapper_.embedding_[0])): sns.kdeplot(ium_clf.mapper_.embedding_[:, i], fill=True) ``` -------------------------------- ### Analyze Cluster Distribution Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/02_TuningWithHDBSCAN.ipynb Extracts labels and counts the number of points per cluster. ```python embedding = clf.mapper_.embedding_ labels = clf.score() clustered = labels >= 0 cnts = pd.DataFrame(labels)[0].value_counts() cnts = cnts.reset_index() cnts.columns = ["cluster", "count"] print(cnts.sort_values(["cluster"])) ``` -------------------------------- ### Profile Categorical Clusters Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/04_JumpstartDenseClus.ipynb Generates descriptive statistics for categorical features grouped by cluster segment. ```python categorical = df.select_dtypes(include=["object"]) categorical["segment"] = clustered_results.segment categorical.groupby("segment").describe(include=["object"]).T ``` -------------------------------- ### Plot Condensed Hierarchical Tree Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/01_DenseClusExampleNB.ipynb Visualize the hierarchical structure of the HDBSCAN clustering, specifically using the leaf selection method to identify sub-clusters. ```python _ = clf.hdbscan_.condensed_tree_.plot( select_clusters=True, selection_palette=sns.color_palette("deep", np.unique(labels).shape[0]), ) ``` -------------------------------- ### Hyperparameter Tuning with RandomizedSearchCV Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/02_TuningWithHDBSCAN.ipynb Performs a randomized search over HDBSCAN hyperparameters to maximize the DBCV score. ```python # we will make our own scorer for DBCV def dbcv_score(X, labels): return validity_index(X, labels) dbcv_scorer = make_scorer(dbcv_score, greater_is_better=True) logging.captureWarnings(True) # specify parameters and distributions to sample from param_distributions = { "min_samples": [10, 30, 50, 60, 100], "min_cluster_size": [100, 200, 300, 400, 500, 600], "cluster_selection_method": ["eom", "leaf"], "metric": ["euclidean", "manhattan"], } n_iter_search = 50 random_search = RandomizedSearchCV( hdb, param_distributions=param_distributions, n_iter=n_iter_search, scoring=dbcv_scorer, random_state=SEED, ) random_search.fit(fitted_umap.embedding_) print(f"Best Parameters {random_search.best_params_}") print(f"DBCV score :{random_search.best_estimator_.relative_validity_}") ``` -------------------------------- ### Extract and Count Cluster Labels Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/01_DenseClusExampleNB.ipynb Retrieve cluster assignments from the model and calculate the proportion of data points in each cluster. Labels of -1 represent noise. ```python labels = clf.score() print(labels, "\n") print(pd.DataFrame(labels).value_counts(normalize=True)) ``` -------------------------------- ### Cluster Numerical Features Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/04_JumpstartDenseClus.ipynb Perform dimensionality reduction and clustering on numerical data, followed by visualization and statistical aggregation. ```python numerical_df = extract_numerical(df) numerical_umap = umap.UMAP( random_state=SEED, n_jobs=1, verbose=False, low_memory=True, **default_umap_params["numerical"], ).fit(numerical_df) numerical_hdb = hdbscan.HDBSCAN(**hdbscan_params).fit(numerical_umap.embedding_) joint_plot = sns.jointplot( x=numerical_umap.embedding_[:, 0], y=numerical_umap.embedding_[:, -1], hue=numerical_hdb.labels_, kind="kde", marginal_ticks=True, ) ``` ```python numerical_df = df.select_dtypes(include=[int, float]) numerical_df["segment"] = numerical_hdb.labels_ numerical_df.groupby(["segment"]).agg(["mean", "median"]) ``` -------------------------------- ### Predict with Ensemble Method Source: https://github.com/awslabs/amazon-denseclus/blob/main/README.md Use the predict method when umap_combine_method is set to ensemble to return labels and probabilities. ```python from denseclus import DenseClus from denseclus.utils import make_dataframe RANDOM_STATE = 10 df = make_dataframe(random_state=RANDOM_STATE) train = df.sample(frac=0.8, random_state=RANDOM_STATE) test = df.drop(train.index) clf = DenseClus(random_state=RANDOM_STATE, umap_combine_method='ensemble') clf.fit(train) predictions = clf.predict(test) print(predictions) # labels, probabilities ``` -------------------------------- ### Profile Numerical Clusters Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/01_DenseClusExampleNB.ipynb Calculate the median values of numerical features grouped by the assigned cluster segment to identify distinct patterns. ```python df["segment"] = clf.score() numerics = df.select_dtypes(include=[int, float]).drop(labels=["segment"], axis=1).columns.tolist() df[numerics + ["segment"]].groupby(["segment"]).median() ``` -------------------------------- ### Inspect Cluster Counts Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/04_JumpstartDenseClus.ipynb Aggregates and displays the number of data points assigned to each cluster, including noise labeled as -1. ```python cnts = pd.DataFrame(labels)[0].value_counts() cnts = cnts.reset_index() cnts.columns = ["cluster", "count"] print(cnts.sort_values(["cluster"])) ``` -------------------------------- ### Visualize embedding distribution Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/01_DenseClusExampleNB.ipynb Attempts to plot the density of embedding components using seaborn. ```python for i in range(clf.n_components): sns.kdeplot(clf.mapper_.embedding_[:, i], shade=True) ``` -------------------------------- ### Access UMAP embeddings Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/03_ValidationForUMAP.ipynb Retrieve the numerical UMAP embedding from the fitted DenseClus model. ```python clf.numerical_umap_.embedding_ ``` -------------------------------- ### Cluster Categorical Features Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/04_JumpstartDenseClus.ipynb Perform dimensionality reduction and clustering on categorical data, followed by visualization and descriptive analysis. ```python categorical_df = extract_categorical(df) categorical_umap = umap.UMAP( random_state=SEED, n_jobs=1, verbose=False, low_memory=True, **default_umap_params["categorical"], ).fit(categorical_df) categorical_hdb = hdbscan.HDBSCAN(**hdbscan_params).fit(categorical_umap.embedding_) n_clusters = len(np.unique(categorical_hdb.labels_)) print(f"Number of clusters: {n_clusters}") ``` ```python joint_plot = sns.jointplot( x=categorical_umap.embedding_[:, 0], y=categorical_umap.embedding_[:, -1], hue=categorical_hdb.labels_, kind="kde", marginal_ticks=True, ) joint_plot.ax_joint.legend_.remove() joint_plot.set_axis_labels("umap_embeddings: 0", "umap_embeddings: -1") ``` ```python categorical_df = df.select_dtypes(include=[object]) categorical_df["segment"] = categorical_hdb.labels_ categorical_df.groupby("segment").describe(include="object").tail(10) ``` -------------------------------- ### Profile Numerical Clusters Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/04_JumpstartDenseClus.ipynb Calculates the mean values of numerical features grouped by their assigned cluster segment. ```python numerics = clustered_results.select_dtypes(include=[int, float]) numerics.groupby("segment").mean() ``` -------------------------------- ### Calculate and Plot Trustworthiness Scores Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/03_ValidationForUMAP.ipynb Computes trustworthiness vectors for numerical and categorical UMAP embeddings and plots the results to evaluate neighbor preservation. ```python K = 50 # supress numba deprecation warnings from UMAP filterwarnings("ignore") numerical_trustworthiness = validation.trustworthiness_vector( source=clf.numerical_umap_._raw_data, embedding=clf.numerical_umap_.embedding_, max_k=K ) categorical_trustworthiness = validation.trustworthiness_vector( source=clf.categorical_umap_._raw_data, embedding=clf.categorical_umap_.embedding_, max_k=K ) filterwarnings("default") _ = plt.plot(numerical_trustworthiness) _ = plt.plot(categorical_trustworthiness) _ = plt.ylabel("Trustworthiness score") _ = plt.xlabel("Value of K") _ = plt.title(f"Trustworthiness at {K}") # _=plt.ylim(0,1) _ = plt.legend(["numerical T", "categorical T"], loc="upper right") ``` -------------------------------- ### Define Cluster Visualization Function Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/04_JumpstartDenseClus.ipynb Utility function to generate KDE joint plots for visualizing cluster density in UMAP embedding space. ```python def plot_clusters(method, embeddings, clusters): """display KDE plots for given embeddings/clusters""" joint_plot = sns.jointplot( x=embeddings[:, 0], y=embeddings[:, -1], hue=clusters, kind="kde", marginal_ticks=True ) joint_plot.set_axis_labels("umap_embeddings: 0", "umap_embeddings: -1") joint_plot.figure.suptitle(f"Method: {method}") if n_clusters > 50: joint_plot.ax_joint.legend_.remove() ``` -------------------------------- ### Visualize embedding joint plot Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/01_DenseClusExampleNB.ipynb Creates a joint plot to visualize the distribution of the first and last embedding dimensions. ```python _ = sns.jointplot(x=clf.mapper_.embedding_[:, 0], y=clf.mapper_.embedding_[:, -1], kind="kde") ``` -------------------------------- ### Assign Segments to Data Source: https://github.com/awslabs/amazon-denseclus/blob/main/notebooks/04_JumpstartDenseClus.ipynb Adds cluster labels to the original dataframe and filters out noise points for further analysis. ```python df["segment"] = labels clustered_results = df[df.segment > -1] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.