Zero Labs
Industry News / AI

From Customer Segments to Reliable Anomalies: K-Means, PCA, Missing Data, and DBSCAN — Machine…

Source · Towards AI By Michalzarnecki

From the publisher’s feed, collected in the ZeroLabs newsroom.

From Customer Segments to Reliable Anomalies: K-Means, PCA, Missing Data, and DBSCAN — Machine Learning in Analytical Tasks Part 2In the previous part, we transformed raw Online Retail order lines into a table in which one row represents one customer. This is already a completely different dataset from the source table.The source table answered:What was included in each order line?The new table answers:How does each customer behave?Only at this level can we sensibly begin customer segmentation.Before saving the feature table, I still perform several basic checks. I verify that the number of rows matches the number of unique customers, no customer appears twice, the key features contain no missing values, the number of orders is at least one, return_rate stays between zero and one, and revenue is not negative.These are not sophisticated tests. They are valuable because they quickly reveal errors in the aggregation logic. Once the checks pass, the table can be saved as Parquet. The next steps no longer need to process hundreds of thousands of transaction lines. They can load the prepared customer table and focus on modelling.Discovering customer segmentsWe now have a feature table that describes customer behaviour. The analytical question becomes:Are there natural groups of customers who behave in a similar way?The dataset does not contain a ready-made customer_segment column. Nobody has labelled customers as regular, occasional, high-value, wholesale, or at risk of leaving. We therefore cannot immediately build a classifier, because we do not have a target for the model to predict.We can, however, use unsupervised machine learning: methods that try to discover structure without ready-made answers. One of the most popular methods is K-Means.K-Means divides observations into a selected number of groups. Each group is represented by a centroid, which we can imagine as the centre of a cluster. Its coordinates are the mean feature values of the observations assigned to that group.If we analysed only two features — number of orders and total revenue — a centroid could describe the average customer in a segment. In reality, we use more features, so the centroid exists in a multidimensional space.The algorithm works iteratively:It selects initial centroid positions.It assigns every customer to the nearest centroid.It recalculates the centroid of every group.It repeats the assignment and recalculation.The objective is to minimise the sum of squared distances between observations and the centroids of their assigned clusters.The result can depend on the initial centroid positions. For this reason, K-Means is usually run several times with different initialisations, and the best result according to the objective function is retained.K-Means also requires us to specify the number of groups in advance. It works best when the clusters have a relatively regular structure and comparable variation.Selecting featuresWe begin by selecting the customer features used for segmentation:CLUSTER_FEATURES = [ "recency_days", "number_of_orders", "total_revenue", "average_order_value", "number_of_products", "purchase_frequency_30d", "return_rate",]model_frame = customer_features.select( ["customer_id", *CLUSTER_FEATURES])We do not use customer_id as a model feature. The identifier is necessary when we later join the result to a specific customer, but it does not describe shopping behaviour.Customer 20,000 is not more similar to customer 20,001 than to customer 8,000. Those numbers are only technical labels.This illustrates an important rule: not every column in a table should be passed to an algorithm. The analyst must select features that make sense in the context of the problem.Reducing skew before calculating distancesPurchasing data often has strongly skewed distributions. Most customers may place one, two, or several orders, while a small group may make hundreds of purchases. Revenue behaves in a similar way: most customers generate a relatively modest amount, while a few wholesale buyers account for very large values.K-Means relies on distances and is sensitive to very large numbers. A few extreme observations can move the centroids considerably.For positive purchasing features, I therefore apply a log1p transformation: the logarithm of the value plus one.LOG1P_FEATURES = [ "recency_days", "number_of_orders", "total_revenue", "average_order_value", "number_of_products", "purchase_frequency_30d",]transformed_frame = model_frame.with_columns( [ pl.col(column) .clip(lower_bound=0) .log1p() .alias(column) for column in LOG1P_FEATURES ])This transformation does not remove the information that one customer is more active than another. It reduces the difference between typical and extreme values.For example, the difference between revenue of 100 and 200 is usually more meaningful than the same absolute difference between 100,000 and 100,100. I do not transform return_rate this way because it is already a share between zero and one.Putting features on a comparable scaleNext, I apply StandardScaler.Consider the original ranges:return_rate is between zero and onethe number of orders may range from one to several hundredtotal revenue may range from a few units to many thousandsrecency may cover the entire period represented by the datasetIf we calculated distances without scaling, the feature with the largest numeric values could dominate all the others. A revenue difference of ten thousand would overwhelm a return-rate difference of 0.2.That would not mean return rate is unimportant to the business. It would only mean the features use different units.X = transformed_frame.select(CLUSTER_FEATURES).to_numpy()if not np.isfinite(X).all(): raise ValueError( "The feature matrix contains NaN or infinite values." )scaler = StandardScaler()X_scaled = scaler.fit_transform(X)For each feature, StandardScaler subtracts the mean and divides by the standard deviation. The transformed features have a mean close to zero and a variance close to one, so they can participate in a distance calculation on more comparable terms.Scaling does not mean all features are equally important from a business perspective. It only prevents their apparent importance from being determined automatically by the unit in which they were recorded.If some features should matter more in a real project, we can assign weights consciously or compare several segmentation variants.Choosing the number of clustersWe still need to choose k, the number of clusters.K-Means will not decide this by itself. We can create two broad segments, four more detailed ones, or eight small groups. Every version produces a mathematical division, but not every version is useful.With too few clusters, customers with very different behaviour are combined. With too many, we obtain numerous small groups that are difficult to interpret and use.In the notebook, I test several values of k and calculate two indicators for each one:inertiasilhouette scorek_results = []for k in range(2, 9): model = KMeans( n_clusters=k, init="k-means++", n_init=20, random_state=42, ) labels = model.fit_predict(X_scaled) k_results.append( { "k": k, "inertia": float(model.inertia_), "silhouette_score": float( silhouette_score(X_scaled, labels) ), } )k_evaluation = pl.DataFrame(k_results)The elbow methodInertia is the sum of squared distances from customers to the centroids of their assigned clusters. A smaller value means more compact groups.The problem is that inertia always decreases when the number of clusters increases. If every customer had an individual cluster, every distance to its centroid would be zero. That would not be a useful segmentation.The elbow method therefore does not simply select the lowest value. It looks for a point at which adding another cluster stops producing a large improvement. On the chart, this may resemble the bend of an elbow.Silhouette scoreThe silhouette score compares two things:how close an observation is to the other observations in its own cluster;how far it is from the nearest other cluster.The value ranges from minus one to one. A result close to one means the observation fits its own group well and is clearly separated from other groups. A result near zero can indicate a boundary between clusters. A negative value may suggest that the observation would fit another cluster better.The highest silhouette score is a useful hint, but it should not be the only criterion. A solution with a slightly lower score may produce segments that are far more useful to the business.The choice of k should therefore consider:metrics,group sizes,stability,interpretability,the planned applicationFrom cluster numbers to customer profilesAfter choosing k, we run the final model and add a cluster identifier to every customer.kmeans = KMeans( n_clusters=SELECTED_K, init="k-means++", n_init=20, random_state=42,)kmeans_labels = kmeans.fit_predict(X_scaled)customer_segments = customer_features.with_columns( pl.Series("cluster_id", kmeans_labels))This is not the end of the analysis.The algorithm does not know what a regular, high-value, wholesale, or inactive customer is. The cluster number also has no permanent meaning. High-value customers may receive ID zero in one run and ID two in another. cluster_0 is only a technical identifier.To understand the groups, I calculate a profile for each cluster:cluster_profiles = ( customer_segments .group_by("cluster_id") .agg( pl.len().alias("customers"), *[ pl.col(column) .median() .round(3) .alias(f"median_{column}") for column in CLUSTER_FEATURES ], ) .with_columns( ( pl.col("customers") / customer_segments.height ).round(4).alias("customer_share") ) .sort("cluster_id"))For purchasing data, medians are often more useful than means because the dataset may still contain exceptionally large customers.I also create a relative profile showing whether the mean of a feature within a cluster is above, below, or close to the overall mean.One group may have very low recency, many orders, high revenue, and a broad product range. We may interpret it as regular or high-value customers.Another group may have very high recency, few orders, and low revenue. These may be inactive customers or people who made a single purchase a long time ago.A third group may place relatively few orders but have a very high average order value and buy many products in each order. That profile may indicate wholesale customers.These names are examples. We should not assume in advance that the algorithm will discover exactly the five segments we expect. First we inspect the data; only then do we assign meaning.The algorithm calculates distances and returns cluster IDs. The analyst evaluates group size, stability, and meaning, assigns readable names, and proposes actions such as a reactivation campaign, a loyalty programme, or separate support for wholesale buyers.Comparing K-Means with DBSCANDBSCAN takes a different approach. It searches for regions in which observations are sufficiently close to one another, identifies dense cores, and expands clusters around them.We do not specify the number of clusters directly. Instead, we set parameters including:eps, the neighbourhood radius;min_samples, the minimum number of observations needed to create a dense region.DBSCAN may discover several clusters, one cluster, or no clear clusters. It may also label some records as -1. These records are treated as noise because they do not belong to any sufficiently dense region.To select eps, the notebook tests several candidates. For each one, it checks how many clusters were found, what share of customers became noise, and the silhouette score of the records assigned to regular clusters.for eps in [0.4, 0.6, 0.8, 1.0, 1.2, 1.5, 2.0]: labels = DBSCAN( eps=eps, min_samples=DBSCAN_MIN_SAMPLES, ).fit_predict(X_scaled)n_clusters = len(set(labels) - {-1}) noise_share = float(np.mean(labels == -1))A small eps creates a restrictive neighbourhood. It may produce many small groups and a large amount of noise. A large value may merge many observations into a single broad cluster. DBSCAN is therefore sensitive to its parameters, feature scaling, and the number of dimensions.K-Means is usually convenient when:every customer must belong to a segmentthe business needs a defined number of groupsthe segments will be used in reports, campaigns, or a CRM systemthe result needs a relatively simple explanationDBSCAN may be more suitable when:the number of groups is unknownlocal density is importantwe expect irregular shapesrecords that fit no group are themselves an important resultclustering and anomaly detection should be combinedThe practical question is not which algorithm is more advanced. It is which one fits the analytical goal.PCA: seeing a multidimensional customer spaceThe segmentation uses seven features at once. K-Means can work in this multidimensional space, but a person cannot create a chart with seven axes.We could compare features in pairs, but this becomes inconvenient as the number of columns increases. With thirty features, the number of possible pairs already reaches several hundred.PCA — Principal Component Analysis — provides a way to represent high-dimensional data using a smaller number of new dimensions while limiting information loss.PCA does not simply choose two existing columns. It creates new variables called principal components. The first component, PC1, is a combination of all input features. It may be strongly associated with the number of orders, total revenue, and number of products, and we may interpret it cautiously as a general customer activity or value dimension.PC2 is another combination of the features. It describes the greatest amount of variation not already captured by PC1. It may be more closely related to recency, purchase frequency, or return rate.from sklearn.decomposition import PCApca_2d = PCA(n_components=2)X_pca_2d = pca_2d.fit_transform(X_scaled)print("Shape before PCA:", X_scaled.shape)print("Shape after PCA:", X_pca_2d.shape)Before PCA, every customer is described by seven values. Afterwards, each is represented by PC1 and PC2, so the customers can be placed on a standard scatter plot and coloured by their K-Means cluster.If the clusters occupy separate areas, the segmentation corresponds to strong directions of variation in the data. If the groups overlap, that does not automatically mean K-Means failed. We are looking at a two-dimensional projection. Customers close to one another on the PC1–PC2 chart may differ in the third, fourth, or later component.The explained variance ratio tells us how much variation each component represents. If PC1 and PC2 explain 65% together, the chart retains a substantial but incomplete part of the structure. That may be enough for a visualisation. For modelling, we may retain enough components to explain approximately 80–90%.To interpret the components, we inspect their loadings:pca_loadings = pl.DataFrame( { "feature": CLUSTER_FEATURES, "PC1_loading": pca_2d.components_[0], "PC2_loading": pca_2d.components_[1], })Loadings show how strongly each source feature contributes to each component. A component is not always easy to name, however. PCA may combine variables in a mathematically useful way that is difficult to explain in one business phrase.This is one of the costs of dimensionality reduction: a simpler dataset does not always produce a simpler interpretation.Missing data is not the same as zeroBefore detecting anomalies in the NASA Asteroids data, we need to address missing values.Zero is not always a data error. A customer may have made no returns. A product may have generated no sales in a given week. These are valid values.A missing value means we do not know the value. Replacing every missing value with zero would change the meaning of the data.We should also investigate why a value is missing. Missingness may be random, but it may also be connected with the phenomenon being analysed. A sensor may have stopped working, part of a system may have been unavailable, or a store may have been closed on a holiday.In such cases, the fact that a value is missing can be information itself. Alongside the imputed value, we may add a Boolean column indicating that the original value was absent.SimpleImputer and KNNImputerSimpleImputer calculates a replacement for each column independently. For numerical data, we can use the mean or median. The median is often a safer starting point when a feature contains extreme values because it is less affected by a few very large observations.For categorical data, we can use the most frequent value or insert a constant such as unknown.The advantage of this approach is simplicity, speed, and interpretability. The disadvantage is that it ignores relationships between columns. If an asteroid’s missing diameter is related to its absolute magnitude and other parameters, a single median for the entire dataset does not use that information.simple_imputer = SimpleImputer(strategy="median")simple_imputer.fit(X_train_missing)X_train_simple = simple_imputer.transform( X_train_missing)X_test_simple = simple_imputer.transform( X_test_missing)KNNImputer uses a nearest-neighbours idea. When a record is missing a value, it searches for similar observations using the other available features and estimates the missing value from those neighbours.This can be more flexible than inserting the same median into every record. It is not automatically better. If the data does not contain meaningful similarities, the selected neighbours may be accidental. The method can also be sensitive to anomalies, the number of neighbours, and feature scale.Because KNN uses distances, scaling is important. A value measured in millions of kilometres could otherwise dominate a feature recorded between zero and one.knn_scaler = StandardScaler()knn_scaler.fit(X_train_missing)X_train_scaled_with_nan = knn_scaler.transform( X_train_missing)X_test_scaled_with_nan = knn_scaler.transform( X_test_missing)knn_imputer = KNNImputer( n_neighbors=5, weights="distance",)knn_imputer.fit(X_train_scaled_with_nan)X_test_knn_scaled = knn_imputer.transform( X_test_scaled_with_nan)To compare the methods, I hide a small share of values that are known in the original dataset. This is done only in a copy. The correct values remain available, but the imputers behave as if they were missing.Both imputers are fitted only on the training data. The test data is transformed using parameters learned from training. This prevents information from the test set from leaking into the preparation process.Because the features use different units, I compare normalised errors rather than raw absolute errors. A lower error indicates a better result in this particular simulation.One experiment does not prove that a method is always superior. The result depends on how missingness arises, relationships between features, data volume, scaling, the number of neighbours, and unusual observations.A good practical approach is to start with a simple median as a baseline. A more complex method is justified when it genuinely improves the downstream analysis or model.Anomalies are records to investigateAn anomaly is a record that differs from the typical pattern. Depending on the dataset, it may be:an unusually large transactiona customer with an exceptional purchasing profilean asteroid with a rare combination of parametersan incorrect measurementa badly imported rowa new phenomenon that has not appeared beforeAnomaly does not automatically mean error, fraud, or danger. The algorithm only says that a record is unusual according to a particular mathematical definition. Interpretation still requires domain knowledge.K-Means allows us to calculate the distance of every observation from the centroid of its assigned cluster. A customer far from the centre of a segment may combine unusual characteristics, have an extremely high return rate, or sit between several customer profiles.In the asteroid notebook, we mark the highest share of centroid distances as potential anomalies:assigned_centroid_distance = ( asteroid_kmeans .transform(X_anomaly)[ np.arange(len(asteroid_cluster_labels)), asteroid_cluster_labels, ])centroid_threshold = np.quantile( assigned_centroid_distance, 1 - EXPECTED_ANOMALY_SHARE,)centroid_anomaly_labels = np.where( assigned_centroid_distance >= centroid_threshold, -1, 1,)This is an anomaly relative to a segment. A different number of clusters or a different feature set may produce a different result.DBSCAN uses a different definition. It labels observations outside sufficiently dense regions as noise. A record marked as noise may be locally isolated even if it is not especially far from a K-Means centroid.Other useful algorithms include Isolation Forest and Local Outlier Factor. Isolation Forest may detect globally extreme records, while LOF focuses on local density. Different methods therefore do not need to agree.In the notebook, I store a separate flag and anomaly score for each method, then check which asteroids are selected by one, at least two, or all methods.anomaly_flags = pl.DataFrame( { "centroid_anomaly": ( centroid_anomaly_labels == -1 ), "dbscan_noise": dbscan_labels == -1, "centroid_distance": ( assigned_centroid_distance ), "dbscan_cluster_id": dbscan_labels, }).with_columns( pl.sum_horizontal( pl.col( "centroid_anomaly", "dbscan_noise", ).cast(pl.Int8) ).alias("number_of_methods_flagging"))This is not a competition in which one algorithm must be right. Each answers a slightly different question.The final result of anomaly detection should not be:This record is wrong.It should be:This record differs from the typical pattern and should be reviewed.Depending on the domain, that record may be a data error, fraud, a high-value customer, a rare but valid case, the beginning of a new trend, or an observation that is particularly interesting to an expert.That’s all in this part. See you in next one. In the final part, we move from structure without labels to supervised learning. We will classify asteroids, transform complaint text into vectors, and connect the analytical work to intuitive presentation layers with Streamlit and Airflow.Check also full code examples in my github repository.From Customer Segments to Reliable Anomalies: K-Means, PCA, Missing Data, and DBSCAN — Machine… was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.