跳到主要内容
英国伦敦 · 创立于 1994 年
中文

Unit 3: Unsupervised Learning and Feature Engineering

How machine learning finds structure in unlabelled data through clustering, dimensionality reduction and anomaly detection, and how careful data preparation and feature engineering make every kind of model work better.

Unit 3 of 5 · about 54 minutes

3.1 Clustering: finding groups in data

In unsupervised learning, there are no labels telling the model the right answer. Instead, the aim is to discover structure hidden in the data: natural groups, simpler underlying patterns or unusual cases. Unsupervised methods are particularly useful for exploration, when you do not yet know what categories exist, and when labelling data would be too expensive.

What clustering does

Clustering groups examples so that those within a group, called a cluster, are more similar to each other than to those in other groups. Typical uses include:

  • Customer segmentation: grouping customers by purchasing behaviour to tailor services and communications.
  • Document organisation: grouping support tickets, reviews or articles by topic.
  • Operations: grouping stores, sites or machines with similar patterns to share good practice or plan maintenance.
  • Exploration: getting a first view of a new dataset before deciding what to predict.

Similarity and distance

Clustering depends on a definition of similarity, usually expressed as a distance between examples. If each customer is described by annual spend and number of visits, two customers with similar values for both are "close". This makes scaling essential: if spend is measured in thousands and visits in single figures, spend will dominate the distance calculation unless the features are put on comparable scales. Choosing which features to include is equally important, because clusters can only reflect the information provided.

k-means clustering

The most widely used clustering method is k-means. It works as follows:

  1. Choose the number of clusters, k.
  2. Place k starting points, called centroids, usually at random.
  3. Assign each example to its nearest centroid.
  4. Move each centroid to the average position of the examples assigned to it.
  5. Repeat steps 3 and 4 until the assignments stop changing.

k-means is fast and simple, but it has limitations. You must choose k in advance; it works best when clusters are roughly round and of similar size; it is sensitive to outliers; and different starting points can give different results, so it is usually run several times.

Choosing the number of clusters

There is rarely a single correct number of clusters. Practitioners use several aids: the elbow method, which plots how tightly grouped the clusters are for different values of k and looks for the point where adding more clusters brings little improvement; the silhouette score, which measures how well each example fits its own cluster compared with the next nearest; and, most importantly, judgement about whether the clusters are useful and understandable for the intended purpose.

Other clustering approaches

  • Hierarchical clustering builds a tree of clusters by repeatedly merging the closest groups, letting you choose the level of detail afterwards.
  • Density-based clustering, such as the DBSCAN method, finds clusters of any shape as dense regions of data and labels isolated points as noise, which is useful when outliers are expected.
  • Gaussian mixture models assign each example a probability of belonging to each cluster, allowing for overlap.

Remember: Clustering will always produce clusters, even in random data. Whether they are meaningful is a question for domain experts and further analysis, not for the algorithm.

Interpreting clusters

Once clusters are found, the next step is to describe them. Compare the average values of each feature by cluster, look at typical examples and give each cluster a descriptive name, such as "frequent low-spend visitors" or "occasional high-value buyers". Then test whether the segmentation is useful: do the clusters respond differently to offers, have different needs or call for different processes? Clusters should also be reasonably stable; if they change completely when the analysis is repeated on a slightly different sample, they may not reflect real structure.

Common mistakes

  • Forgetting to scale features, so one feature dominates the result.
  • Including features that are irrelevant to the purpose, which blurs useful groupings.
  • Treating cluster names as facts about individuals rather than broad descriptions of groups.
  • Never revisiting segments as customer behaviour changes over time.

In practice

Before running a clustering analysis, agree what decisions the clusters will inform. A segmentation intended for marketing messages needs different features from one intended to plan staffing. Start with a small number of well-chosen features, try several values of k, and work with colleagues who know the customers or operations to judge which result is most meaningful and actionable.

3.2 Dimensionality reduction and anomaly detection

Real datasets often have dozens, hundreds or even thousands of features. Customer records may include many behavioural measures; sensors on a machine may record numerous readings every second; text, once converted to numbers, can have thousands of dimensions. Two further unsupervised techniques help in these situations: dimensionality reduction, which simplifies data while keeping its important structure, and anomaly detection, which finds cases that do not fit the usual patterns.

Why many features cause problems

As the number of features grows, data becomes spread thinly across a vast space, so examples that seem similar become harder to identify and models need far more data to learn reliably. This difficulty is often called the curse of dimensionality. Many features are also redundant: height in centimetres and height in inches carry the same information, and many business measures move closely together. Reducing dimensions can speed up models, reduce overfitting and make data easier to visualise.

Principal component analysis

The best-known technique is principal component analysis (PCA). It creates new features, called principal components, that are combinations of the original features. The first component captures the direction in which the data varies most; the second captures the most remaining variation while being unrelated to the first; and so on. Often a handful of components capture most of the variation in dozens of original features.

An everyday analogy is photographing a three-dimensional object. A well-chosen angle captures most of its shape in two dimensions, while a poor angle hides important features. PCA, in effect, finds the most informative angles. The trade-off is interpretability: a component combining twenty original features is harder to explain than any one of them.

Visualisation techniques

Methods such as t-SNE and UMAP are popular for visualising high-dimensional data in two dimensions, for example to see whether documents or images form natural groups. They are excellent for exploration but should be interpreted cautiously: distances and cluster sizes on these plots do not always reflect the original data faithfully, and results can change with settings.

Embeddings

A related modern idea is the embedding: a learned list of numbers that represents a word, sentence, image or product so that similar items have similar numbers. Embeddings, typically produced by neural networks, power semantic search, recommendations and many applications built on large language models. They are a form of compact, meaningful representation, closely related to dimensionality reduction.

Tip: Before reducing dimensions, try simply removing features that are obviously duplicated, irrelevant or almost always the same value. Simple feature selection is easier to explain and often nearly as effective.

Anomaly detection

Anomaly detection, also called outlier detection, identifies examples that differ markedly from the majority. Uses include spotting fraudulent transactions, detecting faults in machinery from sensor readings, identifying unusual network activity that may indicate a cyber attack and flagging data-entry errors. Anomaly detection is attractive because genuine problems are often too rare, or too varied, to provide enough labelled examples for supervised learning.

Common approaches include:

  • Statistical rules: flagging values far from the average, for example several standard deviations away. Simple and transparent, but limited to straightforward cases.
  • Distance and density methods: flagging points that are far from their neighbours or in sparse regions.
  • Isolation forests: randomly splitting the data repeatedly; anomalies tend to be isolated in fewer splits because they are unusual.
  • Reconstruction methods: training a model to compress and rebuild normal data, then flagging cases it rebuilds poorly.

The challenge of evaluation

Because anomaly detection typically lacks labels, it is hard to measure how well it works. Organisations usually review a sample of flagged cases with experts, track how many lead to genuine findings, and adjust sensitivity accordingly. An anomaly is simply unusual; it is not necessarily wrong or harmful. A large order from a new customer may be perfectly legitimate. Human review remains essential, and feedback from reviewers can later be used to build supervised models.

In practice

If you have many related measures, such as dozens of survey questions, PCA can reveal a few underlying themes and simplify reporting. If you need to spot rare problems without many past examples, start with simple statistical rules, then try an isolation forest or similar method, and set up a review process that records which flags were useful. Monitor how many alerts the system produces so that reviewers are not overwhelmed.

3.3 Preparing data and engineering features

Experienced practitioners often say that better data beats cleverer algorithms. Feature engineering is the process of creating, transforming and selecting the inputs a model uses. Together with careful data cleaning, it frequently makes a larger difference to performance than the choice of algorithm. It is also where domain knowledge contributes most directly.

Cleaning data

Before creating features, data must be made reliable. Typical tasks include removing duplicates, correcting obvious errors, standardising formats and categories, and checking that values fall within plausible ranges. Every cleaning decision should be recorded and applied in exactly the same way when the model is used, so cleaning steps are usually written as code rather than done by hand.

Handling missing values

Missing data is almost universal. Options include:

  • Removing rows or columns with many missing values, which is simple but can discard useful information and introduce bias.
  • Imputing values, for example with the median for numbers or the most common value for categories, or with more sophisticated methods that predict missing values from other features.
  • Adding an indicator feature showing whether the value was missing. Missingness is often informative: a customer who did not provide a phone number may behave differently from one who did.

Encoding categorical features

Most algorithms need numbers. Categorical features are converted using techniques such as:

TechniqueHow it worksSuitable when
One-hot encodingCreates a yes or no column for each categoryCategories are few and have no natural order
Ordinal encodingAssigns numbers that respect a natural order, such as small, medium, largeCategories have a meaningful order
Target or frequency encodingReplaces each category with a statistic, such as how often it occursThere are many categories, such as postcodes; needs care to avoid leakage

Scaling numerical features

Many algorithms, including k-nearest neighbours, k-means, regularised regression and neural networks, are sensitive to the scale of features. Standardisation rescales each feature to have an average of zero and a standard deviation of one; normalisation rescales to a fixed range such as 0 to 1. Skewed features, such as income, are often transformed with a logarithm. Tree-based models are largely unaffected by scaling.

Creating new features

The most valuable features often come from combining domain knowledge with raw data:

  • Ratios and differences: debt relative to income, price per square metre, change in spending since last month.
  • Aggregations: number of purchases in the past 30 days, average order value, days since last visit.
  • Date and time features: day of week, month, public holiday indicators, time since an event.
  • Text features: word counts, presence of key terms or embeddings that capture meaning.

Remember: Every feature must be available, in the same form, at the moment the prediction will be made. A feature that is only known later will make the model look excellent in testing and fail in real use.

Data leakage

This last point describes data leakage, one of the most common and damaging mistakes in machine learning. Leakage occurs when information that would not be available at prediction time, or that comes from the test set, influences training. Examples include using "account closed date" to predict whether a customer will leave, calculating scaling statistics on the whole dataset before splitting it, or including a field updated after the outcome was known. Leakage produces impressive test results that collapse in practice. Preventing it requires understanding exactly when and how each field is recorded.

Feature selection

More features are not always better. Irrelevant or redundant features add noise, slow training and complicate explanation. Feature selection methods include removing features with almost no variation, using model-based importance scores, and regularisation techniques that shrink unhelpful weights. Domain experts can also rule out features that are unreliable, unethical or legally sensitive.

Pipelines

Professional teams bundle cleaning, encoding, scaling and feature creation into a pipeline: a fixed sequence of steps learned from the training data only and then applied identically to validation, test and live data. Pipelines prevent leakage, ensure consistency and make models easier to deploy.

In practice

When reviewing a model, ask to see the list of features with a plain-language description of each, when it is recorded and where it comes from. Domain experts can often suggest powerful new features and spot ones that leak future information, which is one of the most valuable contributions non-technical colleagues can make.

Case study: Segmenting customers at an online garden retailer

Bramble & Root, a fictional online retailer of plants and garden supplies, sent the same promotional emails to all its customers and saw declining engagement. The marketing manager asked a data analyst to find meaningful customer groups.

The analyst engineered features from two years of order data: number of orders, average order value, days since last purchase, share of spending on plants versus tools, and the proportion of orders placed in spring. She scaled the features, removed a small number of test accounts and ran k-means with several values of k.

Five clusters proved both statistically reasonable and easy to describe, including "spring-only planters", "year-round enthusiasts" and "lapsed one-time buyers". The marketing team reviewed sample customers from each cluster to confirm that the descriptions made sense. Tailored campaigns were then tested against the standard email using a small control group for each segment. Several segments responded noticeably better, and the analyst scheduled the segmentation to be refreshed every quarter.

Activity

Take a dataset you work with or know well, such as customer, sales or operational records. List five raw fields and propose at least four engineered features you could create from them, explaining why each might help a model. Then identify one field that could cause data leakage for a prediction you choose and explain why.

Compare with a model answer

A good answer starts from realistic raw fields, for example order date, order value, product category, customer join date and delivery postcode. It proposes useful engineered features such as days since the customer's last order, number of orders in the past 90 days, average order value, the share of orders in a particular category and the customer's length of relationship in months, each with a short explanation linking it to behaviour.

It then names a prediction, such as whether a customer will order again in the next month, and identifies a leaking field, for example a "loyalty status" that is updated based on future purchases, or a "refund issued" flag recorded after the period being predicted. The best answers explain how to check when each field is recorded.

Key takeaways

  • Unsupervised learning finds structure in unlabelled data; clustering methods such as k-means group similar examples.
  • Clusters must be judged for usefulness and stability by people who understand the domain, since algorithms will always produce groups.
  • Dimensionality reduction, such as PCA, simplifies many features into fewer informative ones, while anomaly detection finds unusual cases for review.
  • Feature engineering, including handling missing values, encoding categories, scaling and creating new features, often matters more than the algorithm.
  • Data leakage occurs when information unavailable at prediction time influences training; pipelines and careful checks on when fields are recorded prevent it.

Unit check

Create a free account to answer the check, save your progress and receive your free certificate.

Create a free account Log in
← Unit 2 Unit 4 →
WhatsApp