The Outlier and Feature Selection Dilemma: Preparing Data for Clustering
From the publisher’s feed, collected in the ZeroLabs newsroom.
Customer Segmentation SeriesPart 1: Exploratory Data Analysis, handling outliers, and feature selection using Mutual Informationby Mariangela BonghiImage by Author, generated via Seaborn and Paint.A short time ago, I attended a course on Unsupervised Learning. The concepts were fascinating, and I couldn’t wait to put all that new theory into practice. I decided to focus my attention on clustering, using the classic Kaggle Mall Customer Dataset as my playground.The clustering process can be summarized into four steps (often iterative):Feature extraction and selection;Algorithm selection and tuning;Cluster validation;Interpretation of results.When I started, I was looking for a “universal recipe” to apply to any dataset. I quickly discovered that such a recipe doesn’t exist. Instead, clustering is a field where every step requires a choice — some obvious, some less so — guided by data knowledge, business logic, and analytical intuition. While I didn’t find a magic formula, this experience helps me answer some questions: Do I need to consider all the features? Are there outliers, and how significantly will they warp my results? Should I try other algorithms instead of just K-means?This guide is built to answer the very questions I had to solve for myself.The RoadmapSince the journey is extensive, I have divided this project into three specialized parts to ensure we cover every detail of the pipeline:Part 1: EDA, outliers, and feature selection(You are here!) — We’ll start by exploring the data, handling outliers, and analyzing features.Part 2: Identifying optimal parameters for K-Means, GMM, and Linkage methods for different configurations of the dataset.Part 3: Validation, Selection, and Visualization — Evaluating metrics and extracting actionable business insightsLet’s start from the basics: What is Clustering?In short, clustering is the branch of Unsupervised Learning that helps us find hidden patterns in our data, grouping observations into homogeneous clusters with similar characteristics.Consider how powerful this is in marketing: if you truly understand your customers’ behaviors and traits, you can create hyper-targeted campaigns. You’ll know exactly how to communicate with each group, which channel to use, and which products or offers will resonate most with them.Exploratory Data Analysis (EDA)First, let’s import the libraries and take a look at our raw data.# Import Librariesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltimport numpy as npfrom IPython.display import display, HTMLfrom sklearn.preprocessing import StandardScalerfrom sklearn.feature_selection import mutual_info_regression, mutual_info_classiffrom sklearn.cluster import KMeans, AgglomerativeClusteringfrom scipy.cluster.hierarchy import linkage, dendrogramfrom sklearn.model_selection import GridSearchCVfrom sklearn.mixture import GaussianMixturefrom sklearn.neighbors import NearestNeighborsfrom sklearn.metrics import silhouette_score, calinski_harabasz_score, davies_bouldin_score# Load Datadf = pd.read_csv("Mall_Customers.csv")df.head()Figure 1: Initial preview of the Mall Customer datasetThere are four features: “Gender”, “Age”, “Annual Income”, and “Spending Score”.“Customer ID": Serves only as an identifier and will be dropped from the dataset that we’ll use for the clustering.df.describe()Figure 2: Summary statistics“Annual Income” ranges up to 137k, while “Age” only goes up to 70. This suggests that scaling is needed.The jump from the 75th percentile (78k) to the maximum (137k) in “Annual Income” suggests outliers.Before analyzing individual features, we must ensure our dataset is structurally sound.# Check for missing valuesprint("Missing Values\n")print(df.isna().sum())# Check for duplicated rowsprint("\nDuplicated Rows\n")print(df.duplicated().sum())Figure 3: Verification of missing values and duplicated rows.As shown above, a quick check reveals a perfectly “clean” dataset with no missing values or duplicates.To visualize the relationships between features, we use a pair plot.# Remove unnecessary CustomerID columndf_features= df.copy()df_features.drop(["CustomerID"],axis=1,inplace=True)# Plot pairwise relationships in the datasetcustom_palette = {'Male': '#4C72B0', 'Female': '#DD8452'}sns.pairplot(df_features,hue='Gender',palette=custom_palette)plt.show()Figure 4:Pairwise relationships and distributions of Age, Annual Income, and Spending Score, categorized by GenderKey insightsSpending Score vs Annual Income (Row 3, Column 2):This plot is the most informative for clustering purposes. It reveals five distinct clusters forming a clear pattern. This visual evidence strongly suggests that a K-Means algorithm with K=5 would likely be optimal for this dataset when focusing on these two variables.Spending Score vs Age (Row 3, Column 1): High spending scores are notably concentrated among younger customers. Age appears to be a significant factor for isolating high-value segments.The role of Gender (Color: Orange = Female, Blue = Male): Observing the various plots, Gender doesn’t appear to be a variable that makes a clear, stark difference in the overall cluster formation. However, the Age vs. Spending Score plot suggests a slight prevalence of male customers (blue) in the low-spending segments.Detecting and handling outliersNext, it’s time to detect and handle outliers: we’ll use the IQR (Interquartile Range) method. [1,2,3]The IQR method involves the following steps:Calculate the first quartile (Q1) and the third quartile (Q3): these represent the thresholds below which 25% and 75% of the data fall, respectively.Calculate the difference Q3 — Q1: this is what we call the Interquartile Range (IQR) and identifies the central part of the dataset.Establish boundaries beyond this range — typically Q1–1.5 times IQR and Q3 + 1.5 times IQR: data points falling outside these boundaries are defined as outliers.We can visualize them, if any, with the boxplot:# Visualizing data distribution and potential outliers using boxplotsfig, axes = plt.subplots(nrows=1,ncols=3,figsize=(15,5))sns.boxplot(y=df_features['Age'], ax=axes[0],color="#789fb3")sns.boxplot(y=df_features['Annual Income (k$)'], ax=axes[1],color="#789fb3")sns.boxplot(y=df_features['Spending Score (1-100)'], ax=axes[2],color="#789fb3")plt.show()Figure 6: Boxplot for Age, Annual Income, and Spending Score using SeabornAs shown in the box plots, there is only one visible outlier in the ‘Annual Income (k$)’ column. We will now determine the exact number of outliers, as the visual representation may hide multiple overlapping data points. To do this, we will find how many points there are above the Q3 + 1.5 times the IQR.# Evaluation of the first and third quartilesQ1 = np.percentile(df_features['Annual Income (k$)'], 25, method='midpoint')Q3 = np.percentile(df_features['Annual Income (k$)'], 75, method='midpoint')# IQR is calculated as the difference between Q3 and Q1IQR = Q3 - Q1# Upper bound: Q3+1.5∗IQRupper_bound = Q3 + 1.5 * IQR# Outlier Countoutlier = df_features[(df_features['Annual Income (k$)'] >= upper_bound)]print(f"Number of Outliers for the column Annual Income (k$): {len(outlier)}") Number of Outliers for the column Annual Income (k$): 2# Outlier removal: filter the dataframe to keep only records within the upper boundupper_array = np.where(df_features['Annual Income (k$)'] >= upper_bound)[0]df_features_no_outliers=df_features.drop(index=upper_array)# Result verificationprint("Old Shape: ", df_features.shape)print("New Shape: ", df_features_no_outliers.shape)Old Shape: (200, 4)New Shape: (198, 4)Now we have:- df_features: our original dataset without “Customer ID” (200 rows)- df_features_no_outliers: our original dataset without “Customer ID” and without outliers (198 rows)Feature Selection via Mutual InformationBefore proceeding with the clustering phase, it is essential to determine which features provide the most value to our model. In our dataset, there are four features: Spending Score, Annual Income, Age, and Gender. We need to identify which ones contribute to meaningful patterns and which ones act like noise.To answer this, I employed Mutual Information (MI) [4,5,6]. Like correlation, MI measures the relationship between two variables. However, while standard correlation coefficients (such as Pearson’s) are limited to detecting linear dependencies, MI captures any kind of statistical dependency, whether linear or non-linear.How it worksMathematically, given two variables X and Y, MI quantifies how much knowing the value of X reduces our uncertainty about Y.Low MI Value: Indicates that the variables are independent. Knowing the value of X provides no information about Y.High MI Value: Indicates a significant degree of dependency. Knowing X allows us to infer information about Y with greater confidence.In the context of clustering, we prioritize features with high MI scores for two practical reasons:Noise Reduction: A feature with a low MI score is statistically independent of the others. In clustering, such a variable behaves like “noise” — it scatters data points randomly, making it harder for algorithms like K-Means to find cohesive groups.Pattern Recognition: A high MI score means the variable “participates” in the dataset’s internal logic. For example, if Annual Income has a high MI with Spending Score, they work together to define distinct customer segments (e.g., “high earners who spend little”).Practical ApplicationIn our analysis, the function make_mi_scores treats each feature as a target and calculates its relationship with all other variables. By summing these scores, we measure the “centrality” of a feature. A high cumulative MI indicates a variable that shares significant information with the rest of the system, making it essential for defining stable clusters. We distinguish between data types to ensure accuracy:For the Gender feature (categorical/discrete), we utilized mutual_info_classif;For continuous features (Age, Income, Score), we employed mutual_info_regression.This distinction is crucial because the underlying entropy estimation — the mathematical foundation of MI — differs when dealing with discrete labels versus continuous distributions.Comparison: Raw Data vs. No OutliersFinally, by comparing mi_scores with mi_scores_no_outliers, we can observe if the perceived importance of a feature is driven by anomalous data points or if it represents a robust statistical trend. This dual-check ensures that our feature selection is not biased by extreme values in “Annual Income”.# Label encoding for Genderdf_features['Gender'], _ = df_features['Gender'].factorize()df_features_no_outliers['Gender'], _ = df_features_no_outliers['Gender'].factorize()def make_mi_scores(df_input): # Initialize dictionary to store the total MI (centrality) for each feature result = {} for col in df_input: # Define 'col' as target (y) and all other columns as predictors (X) X = df_input.copy() y = X.pop(col) # Create a boolean mask for discrete predictors remaining in X is_discrete = (X.columns == 'Gender') # Use classification MI for categorical target (Gender), # regression MI for continuous targets (Age, Income, Spending Score) if col=='Gender': mi_scores = mutual_info_classif(X, y, discrete_features=is_discrete, random_state=42) else: mi_scores = mutual_info_regression(X, y, discrete_features=is_discrete, random_state=42) result[col]=sum(mi_scores) return resultmi_scores = make_mi_scores(df_features)mi_scores_no_outliers = make_mi_scores(df_features_no_outliers)# Convert dictionaries to DataFrames for easier manipulation and sortingscores_df = pd.DataFrame.from_dict(mi_scores, orient='index', columns=['MI Score'])scores_df_no_outliers = pd.DataFrame.from_dict(mi_scores_no_outliers, orient='index', columns=['MI Score'])# Sort scores in descending order to highlight the most influential featuresscores_df = scores_df.sort_values(by="MI Score", ascending=False)scores_df_no_outliers = scores_df_no_outliers.sort_values(by="MI Score", ascending=False)# Merge the two results into a single tablescore_union = pd.concat([scores_df, scores_df_no_outliers], axis=1)# Rename columnsscore_union.columns = ['With Outliers', 'Without Outliers']# Apply a color gradientscore_union.style.background_gradient(cmap='YlGnBu')Figure 7: MI values for the original and cleaned datasetMI Analysis Results:The marginal difference in MI scores between the two datasets suggests that the underlying structure of the data is stable, and the identified outliers do not significantly distort the global relationship between features.Dominant Features: The Spending Score remains the most informative feature in both scenarios. While its score slightly decreased (from 0.794 to 0.785), it maintains the highest MI, confirming it will be the primary driver for our clusters.Income Stability: Annual Income shows remarkable stability, with its MI score virtually unchanged (from 0.627 to 0.625). This confirms that the relationship between income and the other features is robust and not dependent on anomalous data points.Age Dynamics: Interestingly, Age is the feature that benefited most from the cleaning process, with its MI score increasing from 0.513 to 0.560. However, this increment is still relatively minor and does not fundamentally alter the feature’s importance ranking.The Gender Decision: In both datasets, Gender shows an extremely low MI score (below 0.10). This statistically supports our earlier hypothesis from the pairplot: gender does not share significant information with the other features. Including it in the clustering process might add more noise than value.Dataset Configurations for Model EvaluationBased on the previous Mutual Information and Pairplot analyses, the most promising configuration appears to be the subset including Age, Annual Income, and Spending Score with Gender removed.For educational and comparative purposes, we will not limit our study to a single scenario. Instead, we will evaluate our clustering algorithms across four different dataset configurations:2D Scenario (Annual Income, Spending Score): tested both with and without outliers;3D Scenario (Age, Annual Income, Spending Score): tested both with and without outliers.This multi-scenario approach allows us to empirically observe how the inclusion of specific features or the presence of outliers affects the performance, shape, and stability of the resulting clusters.Feature Scaling: StandardScalerBefore clustering, it is essential to normalize the data to ensure that all features contribute equally to the Euclidean distance calculation. This prevents variables with larger scales from disproportionately dominating the distance metric.We have opted for the StandardScaler method [7,8]; given that only two outliers were identified, their impact is not significant enough to negatively bias the scaling process.The scaling is applied to both versions of the dataset (with and without outliers) as we intend to analyze two distinct hypotheses: one retaining the original data distribution and the other refined by outlier removal, allowing for a comparative evaluation of the clustering results.std_scaler = StandardScaler()# 2D Scenario: Annual Income and Spending Score # Original datasetX_IncomeSpending_all = std_scaler.fit_transform(df_features.loc[:, [ 'Annual Income (k$)', 'Spending Score (1-100)']].values)# Dataset without outliersX_IncomeSpending_no_outliers = std_scaler.fit_transform(df_features_no_outliers.loc[:, [ 'Annual Income (k$)', 'Spending Score (1-100)']].values)# 3D Scenario: Age, Annual Income, and Spending Score # Original datasetX_AgeIncomeSpending_all = std_scaler.fit_transform(df_features.loc[:, ['Age', 'Annual Income (k$)', 'Spending Score (1-100)']].values)# Dataset without outliersX_AgeIncomeSpending_no_outliers = std_scaler.fit_transform(df_features_no_outliers.loc[:, ['Age', 'Annual Income (k$)', 'Spending Score (1-100)']].values)Conclusion & Next StepsWe have successfully laid the groundwork. By combining visual EDA with statistical Mutual Information analysis, we have moved from raw data to a refined set of four dataset configurations.Rather than simply looking for the easiest solution, we are prepared to test multiple “experimental paths” — comparing how algorithms behave across different feature sets and evaluating the true impact of outliers on the final segments.In Part 2, we move from analysis to action. We will identify optimal parameters for K-Means, GMM, and Linkage methods for our four dataset configurations.Read Part 2: Identifying optimal parameters for K-Means, GMM, and Linkage methods →References[1] Penn State University, Identifying Outliers (2023), STAT 200: Elementary Statistics. Online Resource[2] GeeksforGeeks, Detect and Remove the Outliers using Python(2023). Technical Tutorial[3] A. McDonald, Creating Boxplots with the Seaborn Python Library (2022), Towards Data Science. Article Link[4] Wikipedia, Mutual Information (2024). General Reference[5] R. Holbrook, Mutual Information (2021). Kaggle Course[6] Scikit-Learn Documentation (2024), mutual_info_regression & mutual_info_classif[7] S. Sharma, Scaling Numerical Data Explained: A Visual Guide (2020), Towards Data Science. Article Link[8] Scikit-Learn. Comparing different clustering algorithms on toy datasets (2024). Documentation ExampleThe Outlier and Feature Selection Dilemma: Preparing Data for Clustering was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.