Case-based reasoning: reuse experience, then check what happened
基于案例的推理
Retrieve a prior job, adapt its result and retain an observed outcome while exposing ties, abstention and evaluation leakage.
case-based-reasoningAn old job is evidence, not a promise
A community archive wants to estimate how long a scanning job will take. An earlier 80-page job took 24 minutes. Would 120 similar pages take 36 minutes? That is a usable first guess if time scales with page count. It can fail when setup, damaged sheets or quality checks dominate.
Case-based reasoning (CBR) solves a new problem by retrieving experience from earlier problems and deciding how that experience applies. A case can store the situation, a proposed solution, its outcome and an explanation. The representation may be a feature record, a structured design or a problem-solving trace; it need not be a row of numbers. Aamodt and Plaza organize the process into retrieve, reuse, revise and retain. Section 3.3
The example below completes a small version of that cycle. It retrieves one scanning job, scales its duration, compares the estimate with a supplied outcome and returns an extended case memory. All jobs and source labels are fictional. The program does not operate a scanner or verify a real time log.
| Stage | What this example does | What it does not establish |
|---|---|---|
| Retrieve | Rank jobs from the same workflow by page count and color setting | That similar descriptors imply the same processing rate |
| Reuse | Multiply the chosen duration by the ratio of page counts | That setup time is zero |
| Revise | Record the supplied duration and the prediction error | The cause of an error or a repaired adaptation rule |
| Retain | Append the observed case and its source label to a new memory | That every additional case improves future accuracy |
This separates CBR from simply displaying similar records. Reusing and evaluating a proposed answer requires further decisions. A nearest-neighbor lookup is one possible retrieval component, not the entire cycle.
Make similarity and adaptation separate choices
A job profile is (pages, color, workflow). A stored case adds a unique ID, a positive whole-number duration in minutes and a source label. Page counts are positive integers; color is Boolean. Workflow names are exact strings: flatbed and sheet-fed are incompatible in this example, regardless of how close their page counts are.
Within one workflow, define the distance between a query q and a case c:
Here p is the page count and z the color setting. A difference of 25 pages has the same distance cost as a color mismatch. These weights are declared modeling choices, not learned physical constants. The distance is a metric on the page/color profiles within one workflow. On complete cases it is only a pseudometric: different IDs or outcomes can have identical profiles and distance zero. It is neither an error bound nor a probability.
Let Cρ be the compatible cases with distance at most the nonnegative radius ρ. If this set is nonempty, select the smallest pair (distance, case_id); the ID breaks exact ties. Otherwise abstain. The default radius is one half. Sorting IDs makes a repeated run reproducible, but does not make the selected case more relevant than another tied case.
Reuse follows a separate proportional-time assumption:
Color participates in retrieval but this adapter has no color correction. A color mismatch can therefore survive retrieval while still making the duration transfer inappropriate. The source paper distinguishes copying a past solution, transforming it, and reusing the process that originally constructed it; this program uses only a small numerical transformation. Section 6
The fictional memory is:
| ID | Pages | Color | Workflow | Minutes |
|---|---|---|---|---|
| A | 80 | No | flatbed | 24 |
| B | 100 | Yes | flatbed | 50 |
| C | 160 | No | flatbed | 44 |
| D | 120 | No | sheet-fed | 8 |
For 120 non-color flatbed pages, A and C both have distance 2/5. Their adapted times differ: 36 and 33 minutes. B has distance 9/20 and adapts to 60 minutes. D is excluded by workflow even though its other descriptors match exactly. A is selected by the ID tie rule. The three candidate times are not a confidence interval.
Once a duration y is supplied, record the absolute error of the pre-insertion estimate:
If the solver abstained, the error field is None, not zero. Keeping those cases in an evaluation prevents an apparently perfect score obtained by ignoring unanswered jobs.
Keep estimates out of the observed case memory
The complete Python 3.10+ program uses Fraction for exact rational distances and times. It accepts lists or tuples of six-field cases and validates every row before filtering by workflow. A malformed incompatible case is still rejected. IDs and source labels must be nonempty strings, and duplicate case IDs are errors. Floats, booleans and negative values are not accepted as radius values; nonnegative integers and exact Fraction values are accepted.
ranked contains all compatible candidates, including candidates outside the radius, with their proposed adaptations for inspection. Only status proposed supplies a selected estimate. Status outside-radius and no-compatible-case leave the selected fields empty. An unaccepted value inside the diagnostic ranking is not an accepted estimate.
record_observation computes a proposal using the supplied memory before adding the outcome. It then appends the supplied duration, never the estimated duration. The old memory is copied into immutable tuples and remains unchanged. The source is a caller-provided label; it is not cryptographic provenance or an independently verified observation.
from fractions import Fraction
def name(value):
if type(value) is not str or not value:
raise ValueError('IDs and workflow names must be nonempty strings')
return value
def positive_int(value):
if type(value) is not int or value < 1:
raise ValueError('page counts and observed minutes must be positive integers')
return value
def profile(row):
if type(row) not in (tuple, list) or len(row) != 3:
raise ValueError('a profile is (pages, color, workflow)')
pages, color, workflow = row
if type(color) is not bool:
raise ValueError('color must be Boolean')
return positive_int(pages), color, name(workflow)
def memory(rows):
if type(rows) not in (tuple, list):
raise ValueError('the case memory must be a list or tuple')
result, ids = [], set()
for row in rows:
if type(row) not in (tuple, list) or len(row) != 6:
raise ValueError('a case is (id, pages, color, workflow, minutes, source)')
case_id, pages, color, workflow, minutes, source = row
case_id = name(case_id)
if case_id in ids:
raise ValueError('case IDs must be unique')
ids.add(case_id)
result.append((case_id, *profile((pages, color, workflow)),
positive_int(minutes), name(source)))
return tuple(result)
def propose(rows, query, radius=Fraction(1, 2)):
cases, query = memory(rows), profile(query)
if type(radius) not in (int, Fraction) or radius < 0:
raise ValueError('radius must be a nonnegative integer or Fraction')
pages, color, workflow = query
ranked = []
for case_id, old_pages, old_color, old_workflow, minutes, source in cases:
if workflow != old_workflow:
continue
distance = Fraction(abs(pages-old_pages), 100) + Fraction(color != old_color, 4)
ranked.append((distance, case_id, Fraction(minutes*pages, old_pages), source))
ranked.sort(key=lambda row: (row[0], row[1]))
if not ranked:
status, estimate, chosen, distance, source = 'no-compatible-case', None, None, None, None
elif ranked[0][0] > radius:
status, estimate, chosen, distance, source = 'outside-radius', None, None, None, None
else:
distance, chosen, estimate, source = ranked[0]
status = 'proposed'
return dict(status=status, estimate=estimate, chosen=chosen, distance=distance,
source=source, ranked=tuple(ranked))
def record_observation(rows, query, case_id, minutes, source, radius=Fraction(1, 2)):
cases, query = memory(rows), profile(query)
case_id, minutes, source = name(case_id), positive_int(minutes), name(source)
if any(row[0] == case_id for row in cases):
raise ValueError('new observation needs an unused case ID')
before = propose(cases, query, radius)
error = None if before['estimate'] is None else abs(before['estimate']-minutes)
added = (case_id, *query, minutes, source)
audit = dict(case_id=case_id, proposal=before, observed_minutes=minutes,
absolute_error=error, source=source)
return cases + (added,), audit
CASES = (
('A', 80, False, 'flatbed', 24, 'log-A'),
('B', 100, True, 'flatbed', 50, 'log-B'),
('C', 160, False, 'flatbed', 44, 'log-C'),
('D', 120, False, 'sheet-fed', 8, 'log-D'),
)
QUERY = (120, False, 'flatbed')
if __name__ == '__main__':
proposal = propose(CASES, QUERY)
print('ranked:', proposal['ranked'])
print('chosen:', proposal['chosen'], 'minutes:', proposal['estimate'])
updated, audit = record_observation(CASES, QUERY, 'E', 38, 'log-E')
print('review:', audit['observed_minutes'], audit['absolute_error'])
print('old/new sizes:', len(CASES), len(updated))
print('next query:', propose(updated, QUERY)['estimate'])
print('tight radius:', propose(CASES, QUERY, Fraction(39,100))['status'])
print('unknown workflow:', propose(CASES, (120,False,'drum'))['status'])
The complete main output is:
ranked: ((Fraction(2, 5), 'A', Fraction(36, 1), 'log-A'), (Fraction(2, 5), 'C', Fraction(33, 1), 'log-C'), (Fraction(9, 20), 'B', Fraction(60, 1), 'log-B'))
chosen: A minutes: 36
review: 38 2
old/new sizes: 4 5
next query: 38
tight radius: outside-radius
unknown workflow: no-compatible-case
The supplied new outcome is 38 minutes, so the earlier estimate was wrong by 2 minutes. E stores 38, and a repeated identical query now retrieves E at distance zero. That last result demonstrates a memory update, not success on an unseen job. Measuring accuracy only after inserting each job’s outcome would leak its answer into retrieval.
The ranking is correct relative to the stated policy because the loop visits every validated compatible case, exact arithmetic computes each distance, and the total (distance, ID) order selects its unique first entry. Testing that entry against the inclusive radius is equivalent to minimizing over Cρ. The adapter then applies the declared ratio; this proves the computation follows its definition, not that the estimated duration is physically correct.
For N stored cases, the implementation performs O(N) exact-rational calculations and O(N log(N+1)) key comparisons, using O(N) records of additional space. record_observation makes another validation pass and a new tuple, with the same asymptotic record count. These count operations and records, not bit-level costs: very large integers, rational comparisons and long strings have additional costs. The code has no index or pruning structure.
A convincing neighbor can still give a poor answer
Suppose the real time law in a separate hypothetical experiment is ten setup minutes plus one fifth of a minute per page. A 50-page case takes 20 minutes. Proportional reuse predicts 40 minutes for 100 pages, while this law gives 30. Algebra isolates the error caused by pretending setup scales with pages:
The formula concerns that chosen affine law; it is not a general CBR error theorem. Reducing retrieval distance does not repair a missing setup term. Repair could involve adding setup information, changing the adapter or choosing a direct timing baseline. None of those changes happens automatically when this program appends a case.
Conflicting outcomes also need a policy. If a new case B has exactly the profile of A but a different observed duration, both have distance zero. The ID tie rule still selects A. This implementation retains both observations but does not aggregate repetitions, prefer recent evidence, estimate uncertainty or diagnose drift. An application would need to decide whether those records describe noise, different contexts or a changed process.
The four knowledge containers discussed by Richter and Aamodt—vocabulary, similarity, case memory and adaptation knowledge—help locate these decisions. Adding more rows changes only one container; useful revision can require changes elsewhere. Section 3
For an evaluation, freeze a historical memory, predict each later job, record the prediction before observing its outcome, and only then decide whether to retain the case. This function reproduces that order for the memory passed to one call; it does not preserve a prediction issued earlier against a different memory. A deployed system should store that earlier prediction and its memory/policy version. Compare error, abstention rate and retrieval cost against a fixed operational baseline and a simple fitted time model. Choose weights and radius on separate development data. Source labels, shared jobs and near-duplicate records must not quietly cross the evaluation split.
CBR may reuse structured explanations, designs or search traces that this six-field record cannot express. kNN addresses the local voting/averaging model; retrieval-augmented generation is a separate planned topic. Retrieving text for a language model does not by itself define an adaptation, outcome review or memory-retention policy. Likewise, keeping an error log does not establish a causal explanation for the error.
Change one decision at a time
-
Why is D excluded, and why does A beat C? What if the radius is exactly 2/5 or just 39/100?
Answer: D belongs to another workflow. A and C tie at 2/5, and A wins only because its ID sorts first. The radius is inclusive, so 2/5 accepts the selected case; 39/100 causes abstention. The ranking still exposes the compatible candidates, but no selected estimate is returned.
-
The new job actually took 38 minutes. Which value belongs in E: 36 or 38? Is the repeated-query answer 38 a valid held-out accuracy result?
Answer: E stores the supplied outcome 38 with its source label; the separate audit preserves the estimate 36 and error 2. Querying E after retention demonstrates memorization. It is not a prediction made before that outcome was available and must not be counted as held-out success.
-
A 50-page case took 20 minutes under the separate law t(p)=10+p/5. Predict 100 pages with the adapter, compare with that law, and identify what knowledge is missing.
Answer: The adapter doubles 20 to 40; the law gives 30, so the error is 10. Setup should be paid once, not doubled. The adapter needs a way to separate fixed and per-page work. No amount of confidence in the old case’s recorded time supplies that missing assumption automatically.
-
Start a separate memory containing only A: 50 non-color flatbed pages, 20 minutes. Append B at exactly that profile with observed duration 50. Which duration is selected next? Did B disappear?
Answer: Both distances are zero, so A remains first and its duration 20 in this separate two-case experiment remains selected. B and its observed 50 are still in memory. The rule chooses by ID; it has no mechanism for resolving repeated-profile outcome disagreements. A different aggregation or recency rule would be a deliberate model change.
Read the cycle as a framework for decisions
Aamodt and Plaza’s author-hosted paper identifies the original publication as AI Communications 7(1), March 1994, pp.39–59. The accessible copy is repaginated to 20 pages, so the citations above use sections. Its §§3.3, 5–8 discuss the cycle, retrieval, adaptation, evaluation and retention. It does not prescribe our distance, radius, time ratio or append-only policy. Author-hosted paper
Richter and Aamodt’s foundations article appears in the September 2005 issue, while Cambridge records online publication on May 8, 2006 and a 2006 copyright. The filename alone cannot resolve those dates. Its knowledge-container discussion makes clear why vocabulary and adaptation are part of the model alongside the case collection. Author copy; publisher record.
The example, data and code here are original. Tests check exact selection using an independent integer-scaled ranking, cross-multiply the adaptation ratios, reverse input order, preserve old memories, reject malformed unused rows and compare pre-retention predictions with stored outcomes. They also exercise abstention, conflicting identical profiles, very large integer inputs and the fixed-overhead counterexample. These checks verify the teaching implementation, not operational scanner performance or a general guarantee that experience transfers.
Make a prediction, then check
A job was estimated at 36 minutes, then observed at 38. After retaining it, the same query returns 38. What follows?
Learning objectives
- Distinguish retrieval,reuse,revision and retention,including situation,outcome,source and adaptation knowledge.
- Implement auditable tie/radius selection and time adaptation,test with exact references,and explain why similarity does not guarantee transfer accuracy.
- Store estimates separately from observations,and use pre-insertion evaluation to examine leakage,abstentions and conflicting repeated contexts.
Prerequisites & connections
Explore related knowledge →References
- Case-Based Reasoning: Foundational Issues, Methodological Variations, and System Approaches
Agnar Aamodt; Enric Plaza · 1994 - Case-based reasoning foundations
Michael M. Richter; Agnar Aamodt · 2005
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent finite-state oracles, bilingual review and second-agent cross-checks; not independent human peer review.
- Full bilingual alignment:4displays,6stable main anchors,4answers,identical complete Python and full stdout. Fictional scanning jobs are not represented as real logs; distance,adaptation,observation and retention are separate. Exercise4 initially lacked its separate50-page/20-minute premise; supplied it explicitly to avoid confusing main-table A (80pages/24minutes), without changing code.
- Nine author tests passed. Independent integer ranking uses4|page difference|+100color mismatch over400, without calling the Fraction distance implementation. All two-case choices from12profiles×12queries×6radii give4752 full ranking/selection checks; adaptation verified by cross multiplication. All24input permutations agree, input lists remain unchanged, and200-digit integers remain exact.
- One hundred seeded sequential retentions check each full pre-insertion proposal,error,observed value/source and all prior cases. Empty-memory/outside-radius abstentions have None error rather than zero, but may be retained once an external outcome is supplied. Twenty-three invalid construction/value/radius/duplicate-ID cases include malformed workflow-incompatible records.
- Checked main A/C distance2/5 and adapted36/33,B9/20 and60,Dhard workflow exclusion; A wins tie, observed38 has error2, repeat38 after retention is only memorization. Separate fixed-overhead counterexample50pages/20minutes→100pages predicts40 versus30, and a same-profile B50 still loses to A20 byID. No automatic error repair,recency preference or probability interpretation.
- Proved policy fidelity by total-order minimum and inclusive radius. Distance is a metric on page/color profiles but only a pseudometric on full cases; adaptation carries no physical guarantee. Counts O(N)rational operations/O(Nlog(N+1))key comparisons/O(N)records, with separate bit/string costs. record_observation guarantees order for its supplied memory, not preservation of an earlier prediction against another version.
- Reread under the repository pinned English/Chinese Humanizer guidance, explaining concrete assumptions,counterexamples and sources rather than substituting phrase scans for editing. Strict MDX/current display-math/KaTeX actually React-renders4displays/4strong answers per locale, with no math errors or raw emphasis outside code; tests check all6main anchors. Currentlywritten awaiting independent AI cross-review, not human expert review or full-site acceptance.
- Read both full articles,4equations, complete Python,4answered exercises, metadata and all9 author tests; reran all9 successfully. Main scanning table remains separate from the50-page counterexample; the complete7-line stdout agrees across locales.
- Independent reference computes terminating distances exactly with sufficient-precision Decimal and determines ranks by counting pairwise predecessors, rather than the author’s4|page difference|+100color scaled-integer key or production sorting. Adaptation independently reduces numerator/denominator with Euclidean gcd; radius uses rational cross-comparison. Fraction only materializes final reduced pairs for result comparison; production distance/adaptation functions are not reused.
- Matched115,633 complete proposal results and173,262 ranked records. Includes every three-case choice from20profiles×20queries×5radii=114,000 checks;800random memories/queries with nonempty reversals, thirds and huge-denominator radii, exact boundaries and immediately-below values, and1/30/200/1000-digit-scale integers. Verified status,estimate,chosenID,distance,source and full ranked fields, with input preservation on every call.
- For805 retentions, independent pre-insertion proposals verified every old/appended memory row and audit proposal/observed value/error/source. No-compatible and outside-radius errors areNone, not zero. A version fixture adds an earlier-ID case to the passed memory: prediction recomputes as60, observation50 gives error10, confirming that the function uses its supplied version rather than preserving a past20-minute prediction from another memory.
- All166 invalid variants raiseValueError, covering six case fields, three query fields, outer containers/row widths,radius,new observationID/minutes/source,duplicateIDs and malformed incompatible rows. The entire memory validates before the hard workflow filter; Boolean page counts/radii are rejected while color requiresBoolean. Valid mutable containers are copied to tuples containing only immutable scalar values.
- Checked512 distance triples for symmetry,triangle inequality and zero-distance identity on same-workflow page/color profiles, with distinct complete records allowed at zero distance. For81affine time models, verified signed errora(pq/pc−1), including zero and positive setup. Same-profileA20/B50 both persist while the next query still selectsA20 byID, error30; none is presented as real-device performance.
- Reviewed policy proof: if the global minimum in the exact total order exceeds the inclusive radius, every compatible item does; otherwise it equals the restricted minimum. Ranking preserves rejected adaptations, but onlyproposed populates selected fields. Complexity is stated in rational calculations,key comparisons and record counts, with integer bit length,Fraction normalization/comparison and string costs separate from constant-time numeric claims.
- Independent strict MDX/remark-math/repository math plugins/KaTeX and actual React static HTML pass:4displays/6headings/4strong answers each, without math errors or emphasis remnants outside code. All4MathML TeX annotations exactly match the article display formulas; directly linked article files exist. No whole-site build,browser acceptance or scanning experiment was performed.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication copy check: restored normal English spacing around numbers and punctuation in the knowledge check. The technical meaning of the question, options, answer and explanation is unchanged; no article algorithm or equation was changed.
Source locations checked:
- Case-Based Reasoning: Foundational Issues, Methodological Variations, and System Approaches · Actually opened NTNU author-hosted20-page repaginated PDF. Header line0 identifies AI Communications7(1),March1994,pp39–59;§3.3 lines474–513 defines retrieve/reuse/revise/retain and general knowledge;§5 lines937–980 gives retrieval purpose/threshold and adaptation-aware retrieval;§6 lines1093–1153 distinguishes copying,transformational and derivational reuse;§7 lines1154–1206 treats evaluation and repair including unevaluated labeling;§8 lines1207–1248 selects what to retain,including externally solved cases and failures. Read those sections only, not all20pages or the cognitive studies it cites. The scanner scenario and operational policy are ours, not an upstream system reproduction.
- Case-based reasoning foundations · Actually opened five-page NTNU author copy,printed203–207. Read header copyright2006/DOI and§3 printed204 lines54–78 for CBR cycle refinements and vocabulary/similarity/case-base/adaptation containers. Independently opened official Cambridge DOI10.1017/S0269888906000695 record:line451 online8May2006;line500 September2005 issue20(3),203–207;line506copyright2006. Article states publication dimensions explicitly. No claim of reading all referenced works, running a source CBR engine or copying illustrations.
- Case-Based Reasoning: Foundational Issues, Methodological Variations, and System Approaches · Independently opened the20-page NTNU author-hosted repaginated PDF. Header line0 states AI Communications7(1),March1994,39–59. Read §3.3 lines474–513 retrieve/reuse/revise/retain and supporting general knowledge; §5 lines937–962 retrieval/threshold and similarity choices; §6 lines1093–1153 copying,transformational/derivational reuse; §7 lines1154–1206 external evaluation, unevaluated cases and repair; §8 lines1207–1248 selection of retained descriptions/outcomes/explanations/processes and failures. The chapter’s numerical scanner policy is explicitly original and narrower, including error recording without automatic repair. No full20-page audit, underlying cognitive-study replication, figure reuse or source code execution claimed.
- Case-based reasoning foundations · Independently opened five-page author PDF and read header printed203/DOI/copyright2006, plus §3 printed204 web lines54–78: refined CBR cycle and vocabulary/similarity/case-base/adaptation containers. Independently opened Cambridge DOI10.1017/S0269888906000695: web451 online8May2006,500 issue20(3)September2005/203–207,506copyright2006. These corroborate the article’s date distinction; no date inferred from filename. No claim to have read all cited works or tested a production CBR engine.
Related topics