smartyfy.mrindigi.com

AI & Machine Learning Master Course — 090. Unsupervised project: explore behavior segments

Smartyfy AI & Machine Learning Master Course

Course ID: smartyfy-ai-ml-master-200

Lesson 090: Unsupervised project: explore behavior segments

Prerequisites: Lesson 089. Learning outcome: Create a cautious segmentation report with stability and usefulness checks.

Frame a modest segmentation project

A behavior segmentation project should end with an interpretable, reproducible description and a plan for checking usefulness. This example summarizes synthetic visit patterns using visits per month and mean visit duration in minutes. It does not infer personality, loyalty, value, or a protected characteristic from those measurements.

The intended question is whether a few stable behavior profiles can help a team design future service experiments. The immediate deliverable is a segmentation report. No intervention is performed, and no claim is made that segment-specific treatment improves outcomes. That distinction keeps discovery from silently becoming an unsupported decision policy.

Generate 240 observations around three deliberately separated behavior centers. Reserve 60 as an audit collection and use 180 for development. Because the data are synthetic independent draws, a random split is appropriate for this teaching exercise. Real repeated visitors would require an entity-aware or temporal design matching the intended future use.

Choose the representation and candidates

Standardize both features using development means and scales, then compare k-means with two, three, and four clusters. Standardization gives the coordinates comparable influence relative to their observed variation. It is a modeling choice, not proof that a one-standard-deviation change in frequency is operationally equivalent to one in duration.

Select the highest development silhouette among these prespecified candidates. This simple criterion is deliberately limited: it favors compact separation in standardized Euclidean geometry. Before operational use, add domain review and sensitivity to reasonable alternative feature definitions. Do not keep modifying the representation until a preferred narrative appears.

Freeze the selected count and main model before examining the audit result. The development silhouettes are 0.6539, 0.7730, and 0.6803, so three clusters are selected. The audit observations receive assignments from the development-fitted scaler and centroids; neither is refitted on audit data.

CPU lab: freeze, summarize, and stress-check

The code executes the full procedure with NumPy and scikit-learn 1.8.0 on CPU. It inverse-transforms centroids into original units for interpretation. It also fits five prespecified bootstrap refits of scaling and clustering, holding the selected count fixed, and compares their assignments on the common audit observations using adjusted Rand index.

The frozen model's audit silhouette is 0.7896. All five bootstrap assignment comparisons have ARI 1.0 in this run. This is strong agreement for these particular resamples and easy synthetic data, not proof of permanent population segments. The audit diagnostics are reported without changing the selected representation or count.

import os
os.environ.setdefault('LOKY_MAX_CPU_COUNT', '1')
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score, adjusted_rand_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from threadpoolctl import threadpool_limits
rng = np.random.default_rng(90)
X = np.vstack([rng.normal([2, 12], [.4, 2], (80, 2)),
               rng.normal([8, 4], [1, .6], (80, 2)),
               rng.normal([5, 22], [.8, 2], (80, 2))])
D, A = train_test_split(X, test_size=60, random_state=90)
scale = StandardScaler().fit(D); d, audit = scale.transform(D), scale.transform(A)
with threadpool_limits(limits=1):
    models = {k: KMeans(n_clusters=k, n_init=10, random_state=90).fit(d) for k in [2, 3, 4]}
    scores = {k: silhouette_score(d, m.labels_) for k, m in models.items()}
    k = max(scores, key=scores.get); m = models[k]
    print('development silhouettes', {k: round(v, 4) for k, v in scores.items()})
    labels = m.predict(audit)
    print('frozen k', k, 'audit silhouette', round(silhouette_score(audit, labels), 4))
    centers = scale.inverse_transform(m.cluster_centers_)
    for j in np.argsort(centers[:, 0]):
        print('center visits duration', np.round(centers[j], 3), 'audit count', int((labels == j).sum()))
    agreement = []
    for seed in range(5):
        idx = np.random.default_rng(seed).choice(len(D), size=len(D), replace=True)
        s = StandardScaler().fit(D[idx])
        b = KMeans(n_clusters=k, n_init=10, random_state=seed).fit(s.transform(D[idx]))
        agreement.append(adjusted_rand_score(labels, b.predict(s.transform(A))))
print('bootstrap assignment ARIs', np.round(agreement, 4))

Profiles in original units

Development-fitted centroids and frozen audit assignments
Neutral profile Visits/month Minutes/visit Audit cases
Lower frequency, medium duration 2.030 11.833 16
Medium frequency, longer duration 5.011 21.910 22
Higher frequency, shorter duration 8.129 4.043 22
Three development centroids at approximately (2.030, 11.833), (5.011, 21.910), and (8.129, 4.043) visits per month and minutes per visit have audit counts 16, 22, and 22.
Original-unit centroids make profiles readable without turning them into permanent identities. Open full-size diagram

Interpret stability at the right level

The bootstrap draws development rows with replacement and refits scaling and clustering. Comparing predictions on the same audit observations avoids the problem of different resamples containing different row sets. ARI also ignores arbitrary cluster-number permutations. The diagnostic measures agreement in audit partitions conditional on the selected k; it does not repeat cluster-count selection.

Five replicates are a small demonstration, not a comprehensive uncertainty analysis. They do not explore different feature windows, changing behavior, collection failures, or different clustering families. Perfect agreement can also occur when a method consistently captures an irrelevant artifact. Stability is evidence about reproducibility, not a certificate of usefulness.

The audit set is now observed. If you use its diagnostics to redesign features or select a different k, it becomes development feedback and a new confirmation boundary is needed. An honest report can still describe the adaptive process, but should not call the reused audit untouched.

Turn profiles into hypotheses

Use the profile table to ask practical questions. Would shorter visits benefit from a faster check-in process? Would long visits benefit from different seating or opening hours? The profiles suggest experiments; they do not prove the answers. Compare a segment-informed intervention with an appropriate baseline using a separate design.

Inspect distributions, not just means. Two groups can have different centroids while overlapping substantially. A person near a boundary may change assignment after a small measurement change. Show representative and boundary examples, include group sizes, and avoid language that turns a temporary behavior summary into a permanent identity.

Check whether features are available and measured consistently at assignment time. A monthly summary based on a complete future month cannot classify a visitor at the start of that month without leakage. Define the look-back window, eligibility rules, minimum observation count, and treatment of new visitors with little history.

Write the final report and maintenance plan

The report should state the question, synthetic or real data provenance, feature units, fitting population, split logic, candidate set, selection rule, audit diagnostics, profile summaries, and unresolved limitations. Include a reproducible assignment function that preserves the fitted scaler and centroid order.

For a real service, monitor assignment proportions, missingness, and distance to centroids over time. A drift signal is a reason to investigate, not automatic permission to relabel everyone. Define versioning and a review process for changing profiles, particularly when downstream teams attach actions to segment names.

The project succeeds when another reader understands both what was found and what remains unknown. Here, three stable geometric profiles summarize deliberately structured synthetic visits. Operational value, temporal persistence, and equitable treatment remain questions for additional evidence.

Four practice questions with worked answers

Practice 1

What proportion of audit observations belongs to the lower-frequency profile?

Answer: There are 16 of 60 audit cases, so the proportion is 16/60 = 0.2667, approximately 26.7 percent. This is an audit-sample proportion, not a guaranteed future population share.

Practice 2

Why inverse-transform centroids before naming profiles?

Answer: The model fits standardized coordinates, whose units are less intuitive. Returning centroids to visits per month and minutes per visit supports readable descriptions and helps detect implausible interpretations.

Practice 3

Why refit scaling inside each bootstrap replicate?

Answer: This stability check includes the learned preprocessing while holding k fixed. Reusing one scaler would hold part of that procedure fixed and omit its contribution to assignment variability.

Practice 4

What would invalidate the untouched status of the audit?

Answer: Changing the feature set, cluster count, or other decisions because the audit result looked disappointing would use it for selection. A subsequent revised-model confirmation needs a new boundary or an explicit disclosure of adaptive reuse.

Five multiple-choice questions

Question 1

What is the direct deliverable of this project?

  • A. A cautious reproducible segmentation report
  • B. Permanent identities for all visitors
  • C. Proof that targeted interventions improve service

Correct: A. The experiment establishes a descriptive procedure and diagnostics, not intervention effects.

Question 2

Why are the profile names neutral?

  • A. They remove the need to validate feature definitions
  • B. They guarantee that profiles persist after a distribution shift
  • C. They describe measured behavior without inventing motives

Correct: C. Interpretation should stay within the observed features.

Question 3

What does bootstrap ARI 1.0 establish here?

  • A. The causal usefulness of the profiles
  • B. Identical audit partitions for the tested resamples
  • C. Guaranteed stability under future distribution shift

Correct: B. It is a limited reproducibility observation.

Question 4

Where is the main scaler fitted?

  • A. Separately on each audit row
  • B. Only on the development observations
  • C. On all development and audit observations

Correct: B. The audit receives the frozen development transformation.

Question 5

Which feature window is valid at a prediction date?

  • A. A defined history available by that date
  • B. The complete following month’s behavior
  • C. Any future window if its labels are hidden

Correct: A. Feature availability, not merely target availability, determines leakage.

Common pitfalls

Do not rename geometric clusters as psychological categories. Avoid treating five stable bootstrap runs as proof of long-term usefulness. Preserve the audit boundary, define time-correct histories, and inspect distributions and boundary cases alongside centroid summaries.

Summary

A useful segmentation project combines explicit purpose, interpretable features, frozen selection, and stability checks. The resulting profiles generate testable operational hypotheses while leaving causal value and future persistence open for further evaluation.

Primary sources and further reading