Sub topic 12
Behavioral and Machine-Learning Detection Alongside Rules
This chapter assumes you have read the earlier chapters on scenarios, thresholds, segmentation and alert generation. You should know that a rule compares transactions against fixed parameters and creates an alert record when they are met. You should also be able to read short Python programs that use lists, dictionaries and the standard library.
Why rules alone are not enough
A rule-based scenario detects what someone thought of in advance. The structuring rule from the earlier chapters looks for several cash deposits between 8,000 and 10,000 within seven days. It does not fire for a customer who deposits 7,900 five times, or for a customer whose activity changed sharply but never crossed a line.
Rules have three recurring weaknesses:
- Fixed lines are easy to learn. Once a launderer knows roughly where a threshold sits, they can stay under it.
- One threshold fits a whole segment. A deposit of 12,000 is ordinary for a small business and unusual for a salaried employee. Segmentation reduces this problem but does not remove it, because customers inside one segment still differ.
- Rules need a typology first. Someone must describe the pattern before it can be coded. New or unusual patterns go undetected until a person notices them.
Behavioral and machine-learning (ML) detection addresses these gaps. It compares activity to what is normal for the customer or for similar customers, so the question changes from "did this cross a fixed line?" to "is this unusual?"
Behavioral detection: comparing a customer to a baseline
Behavioral detection builds a baseline of expected activity and measures how far current activity departs from it. There are two common baselines.
| Baseline | What it compares | Strength | Weakness |
|---|---|---|---|
| Self history | This month against the same customer's past months | Adapts to each customer | Needs enough history; a new account has none |
| Peer group | This customer against similar customers in the same segment | Works for new customers | Only as good as the peer grouping |
Both usually reduce activity to a feature: a number computed from transactions over a window, such as total cash deposited in 30 days, count of distinct counterparties, or share of funds sent abroad. The deviation from the baseline is then expressed as a z-score, which is the distance from the average measured in standard deviations.
The function below compares a customer's current monthly total with their own past months.
from statistics import mean, stdev
def self_history_zscore(history, current, min_history=6):
"""Return how many standard deviations `current` is above the
customer's own history, or None when there is too little history."""
if len(history) < min_history:
return None
mu = mean(history)
# Floor the spread so a very steady customer does not produce
# enormous scores from a tiny change.
sigma = max(stdev(history), 0.1 * mu, 1.0)
return (current - mu) / sigma
monthly_cash = [4000, 4200, 3900, 4100, 4300, 4000]
print(round(self_history_zscore(monthly_cash, 12000), 1)) # 19.4
print(self_history_zscore([4000, 4200], 12000)) # NoneTwo details matter in practice. The min_history guard stops the model from scoring accounts it knows too little about. The floor on sigma handles a customer with almost no variation: without it, a change of a few percent could yield a very large z-score.
Peer-group comparison
When a customer has no history, you can compare them with their segment. Averages and standard deviations are pulled around by outliers, and the peer group may contain the very customers you are hunting. A more robust choice uses the median and the median absolute deviation (MAD).
from statistics import median
def peer_robust_zscore(peer_values, value):
"""Robust z-score of `value` against a peer group, using median and MAD."""
med = median(peer_values)
mad = median(abs(v - med) for v in peer_values)
mad = max(mad, 1.0) # avoid dividing by zero for identical peers
return 0.6745 * (value - med) / mad
peers = [3800, 4100, 4500, 3900, 4200, 4000, 4300]
print(round(peer_robust_zscore(peers, 12000), 1)) # 26.6The constant 0.6745 rescales the MAD so that the score is comparable to an ordinary z-score when the data are roughly normal.
Machine-learning detection
ML models extend the same idea to many features at once. Instead of a single total, a model may look at amounts, counts, timing, counterparties, countries and channels together, and learn what combinations are normal. There are two broad families.
- Unsupervised models have no labels. They flag records that are unusual compared with the rest. Examples are isolation forests, clustering that finds customers far from any cluster, and autoencoders that struggle to reconstruct unusual records. They can surface patterns no one wrote a rule for.
- Supervised models learn from labeled outcomes, typically past alert dispositions or confirmed suspicious activity reports. They predict how likely a new alert or customer is to be escalated. They suit prioritization well, but they depend on the quality of the labels.
The labels are a known difficulty. Analysts closed most past alerts because the rules were noisy, not because the activity was proven innocent. Confirmed laundering cases are rare, and the positives that exist were found by the existing rules. A supervised model trained on them tends to learn to reproduce the rules' view of the world, and it cannot learn about activity the rules never surfaced.
Where ML fits in the alert pipeline
ML does not usually replace the rule engine. It is attached at one of three points.
- As a detector. The model score or an anomaly flag is itself a scenario, and crossing its threshold creates an alert.
- As a prioritizer. Rules create alerts as before, and a model scores each one so the analysts see the likeliest ones first.
- As a filter. A model recommends closing or deprioritizing alerts that look like past false positives. This carries the most risk, because a wrong model silently hides true activity. Many institutions require extra validation, sampling of the suppressed alerts, or both.
The alert record from an ML detector must still say why it was created. A rule alert can state "3 deposits between 8,000 and 10,000 in 7 days." A model alert needs an equivalent, such as the features that moved most, the baseline value and the observed value. Without this, analysts cannot decide quickly, and a reviewer or regulator cannot see why the system flagged the customer.
Combining signals: a worked example
Suppose the structuring rule fires for customer C1, and the behavioral check also shows a large deviation from C1's own history. Each signal alone is useful, and together they are stronger evidence. A simple way to use both is to carry the behavioral score on the alert and let it affect the priority.
def prioritize(alerts, zscores):
"""Order alerts so those with the largest behavioral deviation come first.
`zscores` maps customer_id to a z-score, or None when unavailable."""
def key(alert):
z = zscores.get(alert["customer_id"])
return z if z is not None else 0.0
return sorted(alerts, key=key, reverse=True)
alerts = [
{"customer_id": "C1", "scenario": "structuring_cash"},
{"customer_id": "C2", "scenario": "structuring_cash"},
{"customer_id": "C3", "scenario": "structuring_cash"},
]
zscores = {"C1": 19.4, "C2": 1.2, "C3": None}
for a in prioritize(alerts, zscores):
print(a["customer_id"], zscores[a["customer_id"]])
# C1 19.4
# C2 1.2
# C3 NoneThis example treats a missing score as 0.0, which puts that alert last. That choice has a cost: an alert with no behavioral score is not evidence of low risk. A real system might instead keep the rule-based priority for those alerts. The decision is a policy choice, and it should be written down.
Trade-offs against rules
| Aspect | Rules | Behavioral and ML |
|---|---|---|
| Explainability | High: the logic is readable | Lower: needs feature-level explanations |
| Coverage of new patterns | Only patterns already described | Can surface unexpected ones |
| Tuning | Change a threshold and see the effect | Retrain, then re-test; effects are less direct |
| Data needs | Modest | Long history, clean features, stable definitions |
| Failure mode | Misses anything just below a line | Drift, biased labels, hidden misses |
| Audit and validation | Straightforward | Requires model risk governance |
Common errors
- Scoring accounts with too little history. Early months produce unstable baselines. Set a minimum history and fall back to peer comparison or to rules.
- Using a poor peer group. A peer group that mixes different business types makes ordinary customers look unusual. Segmentation quality sets the ceiling for peer-based methods.
- Ignoring drift. Customer behavior changes with seasons, prices and product launches. A model that was valid last year may produce a flood of alerts or a silence this year. Monitor input distributions and alert volume over time.
- Training on alert outcomes alone. As described above, labels reflect past rules and analyst habits. Mix in sampled reviews of alerts and of non-alerted activity so the model sees cases the rules missed.
- Treating an anomaly as suspicion. Unusual is not the same as suspicious. A customer who sold a house has a large deposit that is unusual and legitimate. The anomaly should start a review, not replace it.
- No reason on the alert. If the alert shows only a score, analysts will either distrust it or follow it blindly. Include the top contributing features.
Measuring whether it helps
The same alert-quality measures used for rules apply here. Alert precision, the share of reviewed alerts that analysts escalate, tells you whether the model's alerts are worth reviewing. Precision alone is not enough, though, because a detector that fires on almost nothing has high precision and little value. You also need to estimate what it misses, for example by reviewing a random sample of activity that did not alert. The next chapter covers tuning and validation, including how to run a new model beside the existing rules before relying on it.
Exercise
A new customer has been with the bank for two months and has no meaningful history. A behavioral model that compares customers only to their own past activity cannot score them. Name one way to still apply behavioral detection to this customer, and one risk of relying on it.
Show answer
Compare the customer with a peer group, meaning other customers in the same segment, for example with a robust z-score using the median and MAD of the peers' activity. The risk is that the result depends on how well the peer group was chosen. If the segment mixes dissimilar customers, ordinary activity looks unusual and unusual activity can look normal. Rules and onboarding information should still cover the customer in the meantime.
Exercise
An ML model is trained on past alert dispositions, with "escalated" as the positive label. Give one reason this model might be weak at finding laundering that the current rules do not detect.
Show answer
The labels come only from alerts the rules created, so the model learns what the rules already consider suspicious and what analysts chose to escalate. Activity that never produced an alert has no label, so the model has no examples of it. Reviewing a sample of non-alerted activity and adding an unsupervised detector can reduce this blind spot.