Insurance fraud is a ranking problem, not a classification problem
A fraud unit has a fixed capacity: say it can investigate fifty cases a week, not one more. Your system does not have to say "this claim is a fraud" with certainty; it has to rank the cases so that those fifty contain as many frauds as possible. This changes everything: you do not need 99% accuracy, you need a good ranking at the top, and a rigorous discipline about how the model sees the data, because in this field the most serious errors are not in the algorithm but in the way the features are built.
In this article you work on synthetic data with a fixed seed, actually run with Python 3.14, scikit-learn 1.8.0 and NetworkX 3.7. I decided the signal myself when I generated the data, so the scores are a didactic model and not an estimate of how well a real system works. The market figures on fraud (billions of losses, growth rates of the sector) I do not report: I did not find a verifiable primary source, and a number without a source in a technical article only serves to impress. The context of claims triage is that of the previous article in the series, from which comes the fraud score that the rules consume.
The Italian legal framework deserves a line right away, because it shapes the process. Article 148, paragraph 2-bis, of the Codice delle assicurazioni private (the Italian Private Insurance Code) provides that the insurer consults the integrated computer archive and, if anomaly indicators defined by IVASS or other fraud indicators emerge, may make no offer within the ordinary deadlines, stating the need for further investigation: the communication goes to the injured party and to IVASS, and the final determinations arrive within thirty days. An anti-fraud system in Italy does not decide "suspicious yes or no": it feeds a procedure that has documents and deadlines.
Types of fraud and the signals they leave
Each type of fraud leaves different traces, and the tool depends on this: an individual fraud shows in the data of a single case, an organised fraud shows only in the relationships between cases.
| Type | Example | Where it shows | Natural tool |
|---|---|---|---|
| Opportunistic | inflating the damage of a real claim | in the amount compared with similar claims | features of the single claim, anomalies |
| Planned | reporting damage that occurred before the policy | in the dates: young policy, late report | temporal features |
| Organised | several people, same workshop, same lawyer, same doctor | in the relationships between cases | graphs and communities |
| Internal | an operator who approves irregular cases | in the behaviour of whoever decides | analysis of process logs |
The table explains why a single model is not enough. An organised fraud can be made up of claims that are perfectly normal taken one by one, and will be ignored by any model that looks at one case at a time; on the contrary, a graph says nothing about who inflates an invoice by a little. That is why the article uses two tools, a model on the features and a graph analysis, and puts them side by side.
A synthetic test bench, and the accuracy trap
To try the models you need claims with a fraud label, and real ones cannot be published. The
function genera_sinistri creates 8,000 in time order with a fixed seed. Three choices matter.
Frauds are about 4%, because rarity is the normal condition of the problem. Each feature carries a
weak signal (a fraud has on average a longer reporting delay, but very many honest cases have the
same delay), as in reality. And I placed three "hot" workshops where fraud is more frequent, and 1,600 doctors
who are instead a rare entity with no signal at all: they will shortly serve to show an error.
import numpy as np
import pandas as pd
def genera_sinistri(n: int = 8000, seme: int = 2026) -> pd.DataFrame:
"""SYNTHETIC claims in time order. I decide the signal: it is a didactic model."""
rng = np.random.default_rng(seme)
officina = rng.integers(0, 60, n)
officina_sospetta = officina < 3 # three "hot" workshops
p_frode = np.where(officina_sospetta, 0.35, 0.03) # overall prevalence of about 4%
frode = rng.random(n) < p_frode
df = pd.DataFrame({
"officina": officina,
"medico": rng.integers(0, 1600, n), # RARE entity (about 5 claims each) with no signal at all
"frode": frode,
# One weak signal per feature: none decides on its own.
"ritardo_denuncia_gg": rng.gamma(2.0, np.where(frode, 6.0, 3.0)),
"importo": rng.lognormal(np.where(frode, 7.6, 7.2), 0.5),
"polizza_giovane": rng.random(n) < np.where(frode, 0.30, 0.08),
"sinistri_12m": rng.poisson(np.where(frode, 1.2, 0.4)),
"avvocato": rng.random(n) < np.where(frode, 0.40, 0.12),
"importo_tondo": rng.random(n) < np.where(frode, 0.20, 0.03),
})
return df
if __name__ == "__main__":
df = genera_sinistri()
print("claims:", len(df), " frauds:", int(df.frode.sum()), f" prevalence: {df.frode.mean():.1%}")
print("frauds in workshops 0-2:", int(df[df.officina < 3].frode.sum()), "out of", int((df.officina < 3).sum()))
print("accuracy of someone who always answers 'no fraud':", f"{1 - df.frode.mean():.1%}")
# Output:
# claims: 8000 frauds: 351 prevalence: 4.4%
# frauds in workshops 0-2: 144 out of 402
# accuracy of someone who always answers 'no fraud': 95.6%
The last line of the output is the trap to avoid: someone who always answers "it is not a fraud" has an accuracy of 95.6% and finds nothing. With classes this unbalanced accuracy measures nothing. You use instead the average precision (AP), which summarises the precision-recall curve as described in the scikit-learn documentation, and the measure closest to the real work: how many frauds you find in the first fifty cases. The reference value for AP is the prevalence itself: a random draw gets about 4-5%.
Features, the split in time and the error that inflates results
The next listing imports dati.py and compares four models with a scikit-learn gradient boosting
(HistGradientBoostingClassifier). Two methodological rules keep it honest. First, the
split is in time: you train on the first 6,000 cases and evaluate on the last 2,000,
because in production the model will only see the future. Second, features built on the history of an entity
(the fraud rate of a workshop) use only claims older than 500 positions, to reproduce a concrete
fact: the outcome of an investigation arrives after months, not on the day of the report. Smoothing with five
pseudo-observations prevents "1 fraud out of 1 claim" from becoming a 100% that scares the model.
from collections import defaultdict
import numpy as np
from sklearn.ensemble import HistGradientBoostingClassifier, IsolationForest
from sklearn.metrics import average_precision_score
from dati import genera_sinistri
df = genera_sinistri()
BASE = ["ritardo_denuncia_gg", "importo", "polizza_giovane", "sinistri_12m", "avvocato", "importo_tondo"]
TAGLIO, RITARDO_ETICHETTE = 6000, 500 # train on the past, evaluate on the future
def tasso_dal_passato(colonna: str, m: int = 5) -> np.ndarray:
"""Fraud rate of the entity using ONLY claims older than RITARDO_ETICHETTE positions:
the outcome of an investigation arrives after months, not on the day of the report.
Smoothing (m pseudo-observations at the overall rate) keeps 1 fraud out of 1 from counting as 100%."""
chiavi, esiti = df[colonna].to_numpy(), df["frode"].to_numpy()
n, f, tot_n, tot_f, out = defaultdict(int), defaultdict(int), 0, 0, []
for i, k in enumerate(chiavi):
j = i - RITARDO_ETICHETTE
if j >= 0:
n[chiavi[j]] += 1; f[chiavi[j]] += esiti[j]; tot_n += 1; tot_f += esiti[j]
generale = tot_f / tot_n if tot_n else 0.04
out.append((f[k] + m * generale) / (n[k] + m))
return np.array(out)
# WRONG: the mean over the whole dataset includes the row I am evaluating and its future.
tasso_con_leak = df.groupby("medico")["frode"].transform("mean").to_numpy()
y_test = df.frode.iloc[TAGLIO:].to_numpy()
def valuta(extra: dict, nome: str) -> None:
X = df[BASE].astype(float).copy()
for colonna, valori in extra.items():
X[colonna] = valori
modello = HistGradientBoostingClassifier(max_iter=150, learning_rate=0.05, random_state=0)
modello.fit(X.iloc[:TAGLIO], df.frode.iloc[:TAGLIO])
punteggi = modello.predict_proba(X.iloc[TAGLIO:])[:, 1]
primi = np.argsort(-punteggi)[:50] # an investigation unit that works 50 cases
print(f"{nome:<36} AP={average_precision_score(y_test, punteggi):.2f} frauds in the top 50: {int(y_test[primi].sum())}")
print(f"test: {len(y_test)} claims, {int(y_test.sum())} frauds: prevalence {y_test.mean():.1%}, i.e. the AP of a random draw")
valuta({}, "single-claim features only")
valuta({"officina": tasso_dal_passato("officina")}, "+ workshop rate (past only)")
valuta({"medico": tasso_dal_passato("medico")}, "+ doctor rate (past only)")
valuta({"medico": tasso_con_leak}, "+ doctor rate WITH LEAK")
# Without labels: Isolation Forest on the same features, trained on the past
foresta = IsolationForest(n_estimators=200, random_state=0).fit(df[BASE].astype(float).iloc[:TAGLIO])
anomalia = -foresta.score_samples(df[BASE].astype(float).iloc[TAGLIO:])
print(f"{'Isolation Forest (no labels)':<36} AP={average_precision_score(y_test, anomalia):.2f}")
# Output:
# test: 2000 claims, 95 frauds: prevalence 4.8%, i.e. the AP of a random draw
# single-claim features only AP=0.44 frauds in the top 50: 32
# + workshop rate (past only) AP=0.58 frauds in the top 50: 34
# + doctor rate (past only) AP=0.44 frauds in the top 50: 26
# + doctor rate WITH LEAK AP=0.74 frauds in the top 50: 42
# Isolation Forest (no labels) AP=0.38
Read the output from the top. With only the features of the single claim the model gets an AP of 0.44 against the 4.8% of the random draw, and it is already a good result for weak signals: 32 frauds among the first 50. Adding the historical rate of the workshop, computed only from the past, brings the AP to 0.58. The historical rate of the doctor, computed in the same way, leaves the AP at 0.44 and lowers the frauds in the first 50 to 26: rightly, because that entity has no signal and the model learned noise.
The last line is the error to recognise: computing the doctor's rate with the mean over the whole dataset, including the row you are evaluating, the AP jumps to 0.74 and the frauds in the first 50 to 42, for an entity that carries no information at all. It is a leak of information (leakage): the answer is already inside the feature. In production that feature would be worth zero, because the outcome of the claim is not known when you evaluate it.
Before trusting a brilliant result, check these three points, which are the most common origins of leakage in historical features:
- the feature includes the outcome of the row you are evaluating, directly or through a mean that contains it;
- the feature uses information later than the moment of the decision, such as the outcome of investigations still under way on that date;
- the split between training and evaluation is random instead of temporal, and mixes past and future.
Suspicion falls on rare entities: a doctor with five claims has their own label equal to a fifth of the mean. If a feature looks too good to you, it is almost always one of these three. The last line of the listing adds a comparison that is useful when labels are missing: the Isolation Forest, which according to the scikit-learn documentation "isolates" observations by choosing a feature at random and a cut value, gets an AP of 0.38 without seeing any label. Worse than the supervised one (0.44), better than the random draw (0.048): a tool to start with when you have no history of investigations, not a replacement.
The graph: finding the networks that single cases hide
A fraud network is recognised by repetitions: the same subjects recur, together, in different claims.
You build a graph in which each node is a subject (policyholder, workshop, lawyer, doctor), you link two subjects
when they appear in the same claim and give the link a weight equal to the number of claims in common. Then you look for
communities: groups of nodes more connected among themselves than with the rest. The Louvain algorithm, described by
Blondel and colleagues, starts with each node in a community of its own and
merges them until the modularity no longer improves; the
NetworkX implementation
accepts a seed because the algorithm is heuristic, and without a seed two runs can give different communities.
The listing creates 700 ordinary claims, with a large honest body shop (workshop 0, which handles a quarter of the claims) and a planned ring: 14 claims by 9 people, always with the same workshop, the same lawyer and the same doctor. The point is to tell the two apart: workshop 0 has a huge number of links, but it is not a ring.
import itertools
import random
from collections import Counter
import networkx as nx
rng = random.Random(11)
sinistri = [] # (id, policyholder, workshop, lawyer, doctor, confirmed_fraud)
# 1. Ordinary claims: 700 distinct policyholders, 30 workshops, 20 lawyers, 20 doctors.
# Workshop 0 is a large honest body shop: on its own it handles many.
for i in range(700):
officina = 0 if rng.random() < 0.25 else rng.randrange(1, 30)
sinistri.append((f"S{i}", f"P{i}", f"shop{officina}", f"law{rng.randrange(20)}", f"doc{rng.randrange(20)}", rng.random() < 0.02))
# 2. A planned ring: 14 claims by 9 people, always the same workshop, the same lawyer, the same doctor.
persone_anello = [f"R{k}" for k in range(9)]
for i in range(14):
sinistri.append((f"A{i}", persone_anello[i % 9], "shop90", "law90", "doc90", rng.random() < 0.6))
# Co-occurrence graph: two subjects are linked if they appear in the same claim.
G = nx.Graph()
for sid, ass, off, avv, med, _ in sinistri:
for a, b in itertools.combinations([ass, off, avv, med], 2):
peso = G[a][b]["weight"] + 1 if G.has_edge(a, b) else 1
G.add_edge(a, b, weight=peso)
comunita = nx.community.louvain_communities(G, weight="weight", seed=42)
frode_per_assicurato = {ass: fr for _, ass, _, _, _, fr in sinistri}
righe = []
for membri in comunita:
assicurati = {m for m in membri if m.startswith(("P", "R"))}
if len(assicurati) < 3:
continue
conferme = sum(frode_per_assicurato[a] for a in assicurati)
centrale = max((m for m in membri if not m.startswith(("P", "R"))), key=lambda m: G.degree(m, weight="weight"))
righe.append((len(assicurati), nx.density(G.subgraph(membri)), conferme / len(assicurati), centrale))
print("policyholders density confirmed_fraud_share central_subject")
for ass, dens, quota, centro in sorted(righe, key=lambda r: -r[1]):
print(f"{ass:>13} {dens:>7.2f} {quota:>21.1%} {centro}")
print("total communities:", len(comunita), "- with at least 3 policyholders:", len(righe))
# Output:
# policyholders density confirmed_fraud_share central_subject
# 9 0.45 55.6% shop90
# 40 0.05 0.0% law12
# 57 0.05 0.0% law4
# 66 0.04 1.5% law3
# 99 0.04 1.0% shop0
# 72 0.04 2.8% doc2
# 70 0.04 1.4% doc7
# 75 0.03 1.3% doc12
# 109 0.03 0.0% law2
# 112 0.03 3.6% doc10
# total communities: 10 - with at least 3 policyholders: 10
The ring stands out for its density: 0.45, meaning almost half of the possible links exist, against 0.03-0.05 for all the other communities. It is a small community (9 policyholders) with 55.6% of confirmed frauds. The community of workshop 0 is large, 99 policyholders, and has a low density and 1.0% of frauds: it is a hub, not a ring. If you sorted by size, or by number of links of the central node, you would put the honest body shop at the top and waste the investigation. The practical rule is that the number of links does not indicate suspicion; what indicates it is an unusual concentration compared with what you would expect from the size.
Two limits, both honest. The "confirmed frauds" are a label that in the synthetic graph I assigned myself; in a real system they reach you from investigations, late and few. And a graph built on the same data from which you then want to measure fraud brings back the risk of leakage just seen: if you use the outcome of a case to flag the community and then evaluate on the same case, the result is circular.
From ranking to decision: the threshold is the capacity
With a ranking in hand, the operational question is where to cut. You do not choose a "round" probability threshold such as 0.5: you start from how many cases the unit can investigate and look at what you get. The listing reuses the base model and computes, for different capacities, how many frauds you find, with what precision and what recall.
import time
import numpy as np
from sklearn.ensemble import HistGradientBoostingClassifier
from dati import genera_sinistri
df = genera_sinistri()
BASE = ["ritardo_denuncia_gg", "importo", "polizza_giovane", "sinistri_12m", "avvocato", "importo_tondo"]
TAGLIO = 6000
X = df[BASE].astype(float)
modello = HistGradientBoostingClassifier(max_iter=150, learning_rate=0.05, random_state=0).fit(X.iloc[:TAGLIO], df.frode.iloc[:TAGLIO])
punteggi = modello.predict_proba(X.iloc[TAGLIO:])[:, 1]
y = df.frode.iloc[TAGLIO:].to_numpy()
# The threshold is not chosen from a round number: it is chosen from the investigation capacity.
print("claims_investigated frauds_found precision recall")
for capacita in (20, 50, 100, 200):
primi = np.argsort(-punteggi)[:capacita]
trovate = int(y[primi].sum())
print(f"{capacita:>19} {trovate:>12} {trovate / capacita:>9.0%} {trovate / y.sum():>6.0%}")
# Can the score of a single claim be computed in real time?
una_riga = X.iloc[[TAGLIO]]
tempi = []
for _ in range(200):
t0 = time.perf_counter()
modello.predict_proba(una_riga)
tempi.append((time.perf_counter() - t0) * 1000)
print("median over 200 calls under 50 ms:", float(np.median(tempi)) < 50)
# Output:
# claims_investigated frauds_found precision recall
# 20 16 80% 17%
# 50 32 64% 34%
# 100 48 48% 51%
# 200 56 28% 59%
# median over 200 calls under 50 ms: True
With a capacity of 20 cases you find 16 frauds (80% precision) but only 17% of the total; with 100 cases you find 48 with 48% precision and 51% recall; with 200 the recall rises only to 59% and the precision drops to 28%. It is the real trade-off: beyond a certain capacity, every additional case costs a lot and yields little, and every honest case investigated is also a customer treated with suspicion. The two figures to bring to whoever decides are the precision and the recall at that capacity, not the AP.
The last line of the listing measures whether the score of a single claim can be computed in real time. The result depends on the machine: in three series of 200 calls on a 12-thread machine the median was 1.7-1.8 ms and the 95th percentile between 2.1 and 3.2 ms. This, however, is the cost of the model alone; in production the retrieval of the historical features (database, cache) weighs more, and I did not measure it. A design decision follows: compute in batch the historical features, the ones that change slowly, and inline only those of the incoming case.
Fairness, explainability and rules
A fraud score affects how a person is treated, so three precautions belong in the project from the start. The first is article 22 of the GDPR: nobody must be subject to a decision based solely on automated processing that produces legal effects or similarly significant effects, save for exceptions (contract, law, consent) with safeguards. The path of article 148 goes in the right direction, because suspicion produces an investigation, not an automatic refusal. The second concerns the AI Act, Annex III, point 5: among the high-risk systems are those for assessing risks and prices in life and health insurance, while the exception for "financial fraud" is written next to the creditworthiness systems. The classification of an insurance anti-fraud system is not in the literal text, and must be assessed with the compliance officer.
The third precaution is technical: features that seem harmless (the postcode, the profession, the nationality) can act as proxies for protected characteristics. Before putting them in production, compare the flagging rate between groups at equal observed risk. For each flag keep these elements:
- the score and the version of the model that produced it;
- the features with their value at the time of the decision, not today's;
- the rule or threshold that brought the case to investigation;
- the final outcome of the investigation, which becomes the label of the next training.
The last element closes the loop: without outcomes fed back into the system, the model does not learn from its mistakes and the future labels will only be those of the cases that the model itself chose to investigate, a skewed sample. The theme links this article to the one on integration between systems, where the outcome must travel between applications, and to compliance, which requires being able to reconstruct every piece of data.
What you can do now
You can set up an anti-fraud system as a ranking problem under a fixed capacity, and measure it with the average precision and with the number of frauds in the first N cases instead of with accuracy. You can split the data in time, build historical features with a realistic label delay and recognise leakage when a result is too good. You can find networks with the communities of a graph and tell them apart from honest hubs using the density. Finally, you can connect the score to a process with documents and deadlines, that of article 148, and to precautions on fairness and traceability. What remains outside is what synthetic data cannot tell you: how well your real data will work, and that is measured only with your own investigations.
Frequently asked questions
Why is a fraud model not measured with accuracy?
Because frauds are rare: with 4% positive cases someone who always says "it is not a fraud" has 96% accuracy and finds nothing. You use the average precision, and above all precision and recall at the real investigation capacity, that is, how many frauds you find in the first N cases the unit can investigate.
What is leakage and how do I recognise it in a feature?
It is the presence, inside a feature, of the information the model is supposed to predict, for example a fraud rate computed including the case itself. You recognise it when a feature on a rare entity improves the results too much: in this article a doctor with no signal takes the AP from 0.44 to 0.74.
Is a graph enough to uncover organised fraud?
The tool is useful but not enough. Communities flag anomalous groups, and a ring (small, dense community) must be told apart from an honest hub (large and sparse). Every flag remains a hypothesis to verify with an investigation, not a proof.
Sources
- Legislative Decree 209/2005 (Codice delle assicurazioni private), article 148, on Normattiva (Italian text) - paragraph 2-bis on the consultation of the integrated archive and on the procedure when fraud indicators are present, consulted on 2026-11-12
- Regulation (EU) 2016/679 (GDPR), article 22, on EUR-Lex - solely automated decisions and the related exceptions, consulted on 2026-11-12
- Regulation (EU) 2024/1689 (AI Act), Annex III point 5, on EUR-Lex - the high-risk systems for essential private services and the exception on financial fraud, consulted on 2026-11-12
- IsolationForest, scikit-learn documentation - the principle of isolation through random cuts, consulted on 2026-11-12
- average_precision_score, scikit-learn documentation - the definition of average precision as a weighted mean of precisions, consulted on 2026-11-12
- Blondel, Guillaume, Lambiotte, Lefebvre, Fast unfolding of communities in large networks (arXiv:0803.0476) - the Louvain algorithm, consulted on 2026-11-12
- louvain_communities, NetworkX documentation - the function and the
seedparameter, consulted on 2026-11-12
The listings were run with Python 3.14, scikit-learn 1.8.0, NetworkX 3.7 on synthetic data with a fixed seed, twice in a row with the same output; the latency measurements are intervals on a 12-thread machine and change from machine to machine. The scores are those of a didactic model, not the performance of a real system.
Commenti
Caricamento commenti...
Sign in to comment