Hierarchical Bayesian Regression for Battery Capacity: Predicting New Cells and Retiring Them
This post tests a hierarchical Beta regression of battery state of health on two cells that it never saw, compares it with one curve for all cells, one curve for each cell and a control without diagnostics, and turns the probabilities into the retirement decision of an operator, scored by its value at each cost-loss ratio.
Series: Bayesian Modelling for Industrial Applications, Part 3, second post. The first post of Part 3 built a hierarchical Beta regression of battery state of health, with cells in chemistries, and checked its priors and how well it fits the cells of the data.
A manufacturer that introduces a new chemistry has tested only a few cells of it, and the operator of a battery fleet must decide at every inspection whether to retire a cell or leave it in service. The fit to cells that the model has seen says little about either. What matters is how well the model predicts a cell that it has never seen, and what that prediction is worth in the decision that it serves.
This post answers both on two cells that the model did not see, one of each chemistry. It states the decision of the operator first, then tests the hierarchy against one curve for all cells, one curve for each cell and a control that has no diagnostics, and finally turns each strategy into a retirement rule and compares what the rules cost. As a predictor of a new cell the hierarchy helps in one setting only, after the cell has shown its first 100 cycles, and as a retirement rule its value depends on the cost ratio of the operator.
Show the setup of the notebook
from importlib.metadata import versionimport osfrom pathlib import Pathimport tempfileimport warningswarnings.filterwarnings("ignore")os.environ.setdefault("OMP_NUM_THREADS", "2")import numpy as npimport pandas as pdfrom sklearn.preprocessing import StandardScalerfrom bayes import decisionfrom bayes.data import calcefrom bayes.plot import change, concepts, hierarchyfrom bayes.plot.inline import showfrom bayes.regression import evaluate, hierarchical as hierFAST = os.environ.get("HIER_FAST") =="1"# a smoke test with a few draws, to check that the notebook runsCACHE = Path("cache-fast"if FAST else"cache")CACHE.mkdir(exist_ok=True)FEATURES = ["charge_current_auc", "charge_current_mean", "discharge_voltage_auc", "discharge_voltage_crest"]HELD_OUT = ["CS2_38", "CX2_38"] # the last cell of each chemistry, kept back for the tests of new cellsSEEN = (0, 100, 300) # cycles of a new cell that the model has seenGAP =50# embargo, in cycles, between the cycles seen and the cycles scoredMAIN = {"draws": 40if FAST else500, "tune": 40if FAST else750, "chains": 2if FAST else4}REFIT = {"draws": 40if FAST else500, "tune": 40if FAST else750, "chains": 2if FAST else4}THRESHOLD = evaluate.END_OF_LIFE # a cell below this state of health, in percent, is at its end of lifeRATIOS = np.round(np.arange(0.02, 0.96, 0.02), 2) # cost-loss ratios of the decisionPHI_PRIORS = { # log-normal priors of the precision: the mean and standard deviation of its logarithm"Narrow": (float(np.log(100.0)), 0.3), # centred on 100"Default": (float(np.log(100.0)), 1.0), # centred on 100"Wide": (float(np.log(1000.0)), 1.5), # centred on 1,000}print("pymc", version("pymc"), "| arviz", version("arviz"), "| fast mode:", FAST)
Show the loading of the data
data = calce.load(Path(tempfile.gettempdir()) /"calce-battery-features.parquet", FEATURES, every=8)train, held_out = calce.split(data, HELD_OUT)scaler = StandardScaler().fit(train[FEATURES]) # standardised on the training cells onlyCHEMISTRIES =list(dict.fromkeys(data["CellType"]))COLOURS = hierarchy.palette(CHEMISTRIES)CHEMISTRY_OF = data.drop_duplicates("cell").set_index("cell")["CellType"].to_dict()summary = data.groupby(["CellType", "cell"]).agg(rows=("cycle", "size"), last_cycle=("cycle", "max"))for chemistry, rows in summary.groupby("CellType"):print(f"{chemistry}: {len(rows)} cells, {rows['rows'].min()} to {rows['rows'].max()} kept cycles per cell, longest life {rows['last_cycle'].max()} cycles" )print(f"{len(data):,} cycles kept; {len(train):,} in the {train['cell'].nunique()} training cells; held out: {', '.join(HELD_OUT)}")print(f"SoH above 100%: {(data['soh'] >100).mean():.1%} of the kept cycles")
A model is useful to the operator only through the decision that it supports, so the decision is stated first. At an inspection the operator can retire the cell, at a cost that covers the replacement and the downtime, or leave it in service. A cell that is left in service while it is below the threshold of 80% causes a loss , for example a failure of the string that it belongs to, and a cell that is above the threshold costs nothing. The two costs enter the decision only through their ratio,
which is small when a failure is much more expensive than a replacement and close to one when retiring a cell costs almost as much as the loss that it prevents. The model supplies the probability that the state of health of the cell is below the threshold, which is read from the predictive distribution of the model. The operator expects to lose by leaving the cell and by retiring it, so retiring is the cheaper choice when
Figure 1 draws the decision as three steps and a threshold on the probability. This is the cost-loss model of decision making under a probability forecast.1 The rule is the best one for an operator whose probabilities are reliable, and it shows what the operator needs from a model: probabilities that are neither too confident nor too vague. A model that states a probability near zero for a cell that is below the threshold, or near one for a cell that is above it, is paid for in replacements that were not needed and failures that were not avoided. The value of a model to an operator is then the share of the possible saving that it achieves, against an operator who has only the long-run rate of cells below the threshold, and it is 0 for that operator and 1 for one who knows the outcome.2Forecast Value, Part 1 derives the same rule and the same relative economic value for a limit on a distribution network, where the probability of an event comes from a quantile or Laplace forecaster. Here the probability comes from the posterior of a hierarchical model and the event is a single cell below 80%, so the two posts apply one decision to two sources of probability. The sections that follow test the strategies as predictors of a new cell, and the last of them applies the rule to each strategy and shows what an operator would pay under each.
Show the code of the figure
show(concepts.decision())
Figure 1: The decision at an inspection: the model gives the probability p that the cell is below 80%, and the cell is retired when p exceeds the ratio α of the cost C of retiring to the loss L of a failure.
Test on Unseen Cells
The test uses the three strategies of the first post, all fitted to the 11 training cells with the four diagnostics as inputs: one curve for all cells, which is complete pooling, one curve for each cell, which is no pooling, and a level for each chemistry between the fleet and its cells, which is partial pooling. The two cells that were kept back are CS2_38 and CX2_38, the last cell of each chemistry of the CALCE data. The test gives each strategy a new cell and asks for its state of health over the rest of its life. A new cell has no parameters in the fitted model, so its curve cannot be read from the posterior. The parameters are drawn instead from what each strategy says about a new cell. Under partial pooling the cell takes the chemistry level of its type and adds the offsets and with fresh unit-normal draws, which carries the cell-to-cell spread into the prediction. Under complete pooling it takes the common parameters, and under no pooling it takes its prior, since no pooled information exists. In each case the diagnostics of the cell go through the fitted effects, and the noise of the Beta likelihood is added to give predictive draws.
The strategies are first given no cycle of the new cell, and then its first 100 or 300 cycles, which are added to the training data before the models are refitted. All settings are scored on the same cycles, those after cycle 350 of each held-out cell, 222 observations in all, so that the scores differ only because of what was seen. Each setting is scored with the error of the median in points of state of health, the coverage of the 90% interval and the interval score, which is the width of the interval plus times the distance by which an observation falls outside it, with and averaged over the observations. The interval score is a proper score, so it cannot be lowered by an interval that is too wide or too narrow for the truth.3 A fourth model, complete pooling without the diagnostics, serves as a control: if the diagnostics carry the information, removing them should hurt. The same predictive draws give, for each scored cycle, the probability that the state of health is below 80%, which the last section turns into a retirement rule. Every refit uses the settings of the first post, four chains of 500 draws after 750 tuning draws, and is stored in a cache folder, because sampling is the slow part: the eight refits took 34 minutes on a laptop, and the four refits of the scores under other priors, described at the end of the last section, took 27 minutes. None of the 12 fits of the test, the four on the training cells and the eight refits, has a divergent transition, the worst is 1.02 and the smallest bulk effective sample size is 392, for no pooling with no cycles seen, so the scores below do not rest on unconverged fits.
Show the test on unseen cells
result = evaluate.cold_start(train, held_out, scaler, FEATURES, SEEN, GAP, MAIN, REFIT, CACHE)scores, diagnostics, curves, windows = result
Prediction without Cycles
Figure 2 shows the predictions of complete pooling and of partial pooling for CS2_38 and CX2_38 when the model has seen none of their cycles, with the median as a line, the 90% interval as a band and the observations as points. The prediction of no pooling is its prior, which is too wide to draw usefully, with an interval of 73.6 points.
Figure 2: Predicted state of health of the two held-out cells before the model has seen any of their cycles. The line is the median, the band the 90% interval and the points the observations.
Complete pooling predicts both cells well. Its median is off by 3.0 points of state of health on average, its interval is 17.1 points wide, and the interval contains 95.5% of the observations. Partial pooling is less accurate and wider, with a median error of 4.7 points, an interval 31.5 points wide and a coverage of 100%. No pooling returns its prior, with a median error of 6.6 points and an interval 73.6 points wide. The control without diagnostics has a median error of 6.8 points and an interval score of 60.7, against 18.6 for complete pooling, so the diagnostics cut the error by more than half and the interval score to about a third.
The ranking is the opposite of what the hierarchy was built for, and it has a reason. One diagnostic nearly determines the state of health, so the average curve with the right diagnostics is already close. A hierarchical prediction adds the spread between cells on top of that, which makes the interval wide. The coverage of 100% against a nominal 90% means that the interval is conservative, not that it is accurate.
Over-Confidence after More Cycles
The prediction changes when the model has seen the first cycles of a new cell, which are added to the training data before the model is refitted. Figure 3 shows partial pooling for the same two cells after the first 100 and after the first 300 cycles. The band is a prediction for the rest of the life of the cell, so about nine of ten observations should fall inside it.
Show the code of the figure
for seen in (100, 300): shown = curves[(curves["strategy"] =="partial") & (curves["cycles_seen"] == seen)] show(lambda shown=shown, seen=seen: hierarchy.bands( shown, COLOURS, seen, THRESHOLD, size=(440, 300), key=seen ==100 ) )
(a) First 100 cycles seen
(b) First 300 cycles seen
Figure 3: Predicted state of health of the two held-out cells under partial pooling after the model has seen the first 100 and the first 300 cycles of each. The dashed line marks the cycles seen, and the key of the first panel serves both.
After 100 cycles the band of CS2_38 is wide and holds its observations, and none of them lies outside it. After 300 cycles the band is narrow and every scored observation of CS2_38 lies above it, because the model has learnt the early decline of the cell and extrapolates a steeper fall than the cell shows. The median is 8.4 points of state of health too low on average. The band of CX2_38 narrows as well, and 22% of its observations lie above it, against 6% after 100 cycles. The picture is that of an over-confident prediction: the model is surer after 300 cycles than the cell allows. The scores of the next section put numbers on it, with a coverage of the 90% intervals of 94.6% after 100 cycles and 52.3% after 300.
Show the code of the figure
ORDER = ["partial", "none", "control"]shown = evaluate.change_by_strategy(scores, "interval", "complete", ORDER, hierarchy.STRATEGIES)names = [hierarchy.STRATEGIES[name] for name in ORDER]for panel insorted(shown["panel"].unique()): show(lambda panel=panel: change.change( shown[shown["panel"] == panel], "Complete pooling", names, subject="Partial pooling", ncol=1, scale=shown ) )
(a) No cycles seen
(b) First 100 cycles seen
(c) First 300 cycles seen
Figure 4: Interval score of each strategy as the change in percent from complete pooling. Orange bars are worse than the reference, and partial pooling is blue where it is better.
Figure 4 expresses the interval score of each strategy as the change from complete pooling, and the text gives the coverage of the 90% intervals, which should be near 90%. Complete pooling is the reference because it has no cell-specific parameters to update: its error stays between 2.99 and 3.04 points, its coverage near 95% and its interval score at about 18.6 in every setting. The control without diagnostics is worse than the reference by more than 220% in every panel, which confirms that the diagnostics carry the information.
After 100 cycles, partial pooling has an error of 3.2 points and a coverage of 94.6%, so it matches the calibration of complete pooling with an interval of 9.9 points against 17.0. Its interval score is 10.3 against 18.7, 45% below the reference, the one result in the test in which the hierarchy beats the single curve by a wide margin. No pooling has the smallest error, 1.6 points, but a coverage of 100% and an interval 22 points wide, so its interval score is 18% above the reference. After 300 cycles the picture reverses. Partial pooling and no pooling have intervals of about 5 points and cover only 52% and 29% of the observations, so they are over-confident, and their interval scores are 133% and 109% above the reference. The Beta likelihood treats the residuals of successive cycles as independent noise of about one point, whereas the real residuals of one cell are strongly correlated along its life, so more data made the calibration worse. That is a sign that the observation model is too simple and not that partial pooling failed. Two held-out cells are a small test, and these differences should be read as observations and not as estimates of a general effect.
Retirement under Each Strategy
The decision of the first section can now be scored, in the same way as in Forecast Value, Part 1, with the posterior probability of the strategy in place of the probability from a quantile forecaster. The scored inspections are the 222 kept cycles of the two held-out cells after cycle 350, 72 of CS2_38 and 150 of CX2_38, and 144 of them, 64.9%, are below 80%. At each inspection the operator retires the cell when the probability of the strategy exceeds the ratio , and the expense is for a retired cell, 1 for a cell below the threshold that is left, and 0 otherwise, in units of the loss. Retiring every cell costs and retiring none costs 0.649, so a strategy is worth having only where its expense is lower than the cheaper of the two, which is what the relative economic value measures. Figure 5 draws the value of each strategy against the ratio, for a new cell that has shown no cycles, the first 100 and the first 300, up to a ratio of 0.9, because the possible saving that the value divides by tends to zero as the ratio approaches 1 and the value becomes unstable. A curve is read at one ratio: its height is the share of the possible saving that the strategy achieves, a curve at zero is no better than the operator without a model, and a curve below zero is worse. The orange curve is the control, which has no diagnostics and therefore shows what the diagnostics add.
for seen in SEEN: show(lambda seen=seen: hierarchy.value(values[values["cycles_seen"] == seen]))
(a) No cycles seen
(b) First 100 cycles seen
(c) First 300 cycles seen
Figure 5: Relative economic value of each strategy for retiring a cell, against the cost-loss ratio; values below -1 are drawn at -1. Zero is an operator who knows only the long-run rate, one an operator who knows the outcome. Orange is the control.
No strategy is best at every ratio, and the ratio decides what the extra information is worth. With no cycles seen, complete pooling is the best of the three strategies with diagnostics at every ratio that the text quotes: at , a failure that costs five times a retirement, its value is 0.37, while partial pooling has a value of zero. Its interval of 31.5 points puts above 0.2 for every cycle, so it retires every cell, which an operator could do without a model. After 100 cycles the cell-specific strategies pay. At the value of partial pooling is 0.33 against 0.12 for complete pooling, so a manufacturer that tests a new cell for 100 cycles and retires cells early saves about a third of what a perfect forecast would save. Partial pooling leads the three strategies only up to that ratio, however. Beyond it no pooling has the higher value over most of the range, 0.50 against 0.45 at and 0.64 against 0.55 at , so after 100 cycles the hierarchy is the better choice only for an operator whose failures cost ten times a retirement or more. After 300 cycles partial pooling is the best of the three for every ratio up to 0.36, with a value of 0.46 at against 0.12 for complete pooling, even though its intervals are over-confident. The two facts agree: the model has learnt that CS2_38 declines early and over-estimates the decline, and a probability that is too high costs little when the cost of a retirement is small. At , where retiring costs half of a failure, the picture reverses. Partial pooling has a value of 0.62 after 300 cycles, complete pooling 0.67 and no pooling 0.76, and the control without diagnostics, whose vague intervals keep near the middle, has the highest value of all, 0.85. An operator with balanced costs gains little from the sharper probabilities and loses by their over-confidence. The model matters most to the operator who must avoid failures, and for that operator the hierarchy is the better model once the new cell has shown 300 cycles, and after 100 only at the lowest ratios. This evidence rests on two cells.
Show the scores under other priors for the precision
others = {setting: phi_prior for setting, phi_prior in PHI_PRIORS.items() ifnot setting.startswith("Default")}phi_result = evaluate.phi_sensitivity( train, held_out, scaler, FEATURES, SEEN, GAP, REFIT, CACHE, others, {setting: sensitivity_fits[setting] for setting in others},)default = {"strategy": "Default"}partial = scores[scores["strategy"] =="partial"].assign(strategy="Default")phi_scores = pd.concat([partial, phi_result.scores], ignore_index=True)phi_windows = pd.concat( [windows[windows["strategy"] =="partial"].assign(strategy="Default"), phi_result.windows], ignore_index=True)phi_value = decision.value_frame(phi_windows, RATIOS, THRESHOLD)table = phi_scores.pivot(index="cycles_seen", columns="strategy", values=["coverage", "interval"]).round(3)print(table.to_string())for ratio in (0.1, 0.2, 0.5): rows = ( phi_value[np.isclose(phi_value["ratio"], ratio)] .pivot(index="cycles_seen", columns="strategy", values="value") .round(3) )print(f"value at ratio {ratio}:")print(rows.to_string())print(phi_result.diagnostics.round(3).to_string(index=False))
Scores under Other Priors
The precision also sets the width of every predictive interval, so the check of the prior is repeated on the scores. Partial pooling is refitted under the narrow and under the wide prior of the precision, with no cycles of the new cell seen and with the first 100 and the first 300, and scored on the same 222 inspections. The coverage of the 90% intervals is 100% in all three settings with no cycles seen, between 94.6% and 95.9% after 100 cycles and between 52.3% and 55.0% after 300, so the over-confidence does not come from the prior. The interval score is between 31.5 and 34.5 with no cycles seen, between 10.0 and 10.3 after 100 and between 42.3 and 43.4 after 300, which leaves the gain after 100 cycles and the loss after 300 where they were. The value of the retirement rule is the same to three decimals at , 0.333 after 100 cycles and 0.462 after 300, and it moves by at most 0.04 at and at , which is within the differences that the text called not meaningful. The four refits have a worst of 1.01 and a smallest bulk effective sample size of 572, with one divergent transition in each refit after 300 cycles. The data fix the precision at about 1,800 whatever the prior, so these results follow from the model of the residuals and not from the prior of one parameter.
Show the numbers quoted in the text
# Numbers that the text quotes. This cell prints them and is hidden on the page.print(scores.round(3).to_string(index=False))print(diagnostics.round(3).to_string(index=False))for ratio in (0.1, 0.2, 0.3, 0.5): row = ( values[np.isclose(values["ratio"], ratio)] .pivot_table(index="strategy", columns="cycles_seen", values="expense") .round(3) )print(f"expense at ratio {ratio} (units of the loss):")print(row.to_string()) row = ( values[np.isclose(values["ratio"], ratio)] .pivot_table(index="strategy", columns="cycles_seen", values="value") .round(3) )print(f"value at ratio {ratio}:")print(row.to_string())
Limits of the Study
The test is small: two cells, one of each chemistry, are held out, and every coverage figure rests on two curves, so a different pair, or a cross-validation over cells, would give a firmer answer. The retirement decision rests on the same two cells and on 222 inspections of them, which are neighbouring cycles of two lives and not independent, so the curves of Figure 5 are uneven and differences of a few hundredths in value are not meaningful. The scoring treats every cycle as an inspection at which a cell can be retired, whereas a real operator retires a cell once, and 64.9% of the scored inspections are below the threshold, a share that belongs to the window after cycle 350 and not to a fleet in service. The costs are stated only through their ratio, and the value of a model depends on that ratio, as the last section shows. The residuals are treated as independent, although the over-confidence after 300 cycles points to correlation within a cell, and a model with an autoregressive error or a cell-level smooth term would be the next step.
The prior of the precision is tight and the posterior lies far in its upper tail, and the refits of the last section show that the scores of partial pooling do not depend on it. Only partial pooling was refitted, so the comparison with complete pooling rests on the default prior for both. The curve is simple, since a saturating exponential with a linear effect of the diagnostics has no knee, which the end of life of these cells shows, and every eighth cycle is used, which shortens the run and discards little, although the observations that remain are still correlated.
Summary of Findings
As a predictor for new cells, the hierarchy is better than one common curve in a single setting. After 100 cycles it gave the same coverage as complete pooling, 94.6% against 95.0%, with an interval score of 10.3 against 18.7. With no cycles seen it was too wide, with an interval score of 31.5 against 18.6, and after 300 cycles it was over-confident, with a coverage of 52% and an interval score of 43.3. The reason is that one diagnostic nearly determines the state of health here, and the observation model treats successive residuals as independent.
For an operator who must decide whether to retire a cell, the same results become a rule with a cost. With no cycle of a new cell seen, the hierarchy has no value at ratios up to 0.2, because its intervals are too wide to separate any cell from the rest. After 300 cycles it has the highest value of the three strategies for an operator for whom a failure costs at least three times a retirement, with 0.46 against 0.12 for one common curve at a ratio of 0.1, and after 100 cycles only for an operator for whom a failure costs ten times as much. For an operator with balanced costs the sharper probabilities add nothing, and a vague model does better. Where the question concerns cells and chemistries, the hierarchy answers it. Where it is prediction or retirement, it should be compared with complete pooling and with a control that has no diagnostics before it is adopted, in the way done here, and the comparison should be made at the cost ratio of the operator.
Reproducible Results
The notebook is in the bayesian-modelling repository and runs from the first cell to the last in the uv environment of the repository, with PyMC 5.25, ArviZ 0.22 and lets-plot 4.11, and downloads the feature file when it first runs. The model, the sampling, the scores and the figures are functions of the bayes package, which has unit tests, and the cells of the notebook only call them. The sampling settings are in the first cell, and setting the environment variable HIER_FAST=1 runs the whole notebook with a few draws in a minute or two, to check that it works before the full run. The fits are stored in cache/, so a repeat of the full run reads them back, and the first fits are those of the first post of Part 3.
References
[1] A. H. Murphy, “The value of climatological, categorical and probabilistic forecasts in the cost-loss ratio situation,” Mon. Weather Rev., vol. 105, no. 7, pp. 803-816, 1977.↩︎
[2] D. S. Richardson, “Skill and relative economic value of the ECMWF ensemble prediction system,” Q. J. R. Meteorol. Soc., vol. 126, no. 563, pp. 649-667, 2000.↩︎
[3] T. Gneiting and A. E. Raftery, “Strictly proper scoring rules, prediction, and estimation,” J. Amer. Statist. Assoc., vol. 102, no. 477, pp. 359-378, 2007.↩︎
Citation
BibTeX citation:
@online{faustine2026,
author = {Faustine, Anthony},
title = {Hierarchical {Bayesian} {Regression} for {Battery}
{Capacity:} {Predicting} {New} {Cells} and {Retiring} {Them}},
date = {2026-11-28},
url = {https://sambaiga.github.io/pages/blog/posts/2026/11/2026-11-28-hierarchical-bayesian-retirement.html},
langid = {en}
}