- Type 1 diabetes
- Energy expenditure
- METs
- Hierarchical LSTM
- Smartwatch data
- Transfer learning
- Automated insulin delivery
- PyTorch
An adult with type 1 diabetes cycles for about twelve minutes most days and follows an aerobic exercise video twice a week. His insulin system can read his glucose, but it has no idea when he gets on the bike. By the time the sensor shows his glucose sliding, the insulin that will push it lower is already on board. A watch on his wrist knows he is moving. The question this paper asks is whether that watch can tell the insulin system how hard he is moving, every fifteen minutes, all day.
Eleonora Aiello, Chiara Toffanin and colleagues from Harvard, the Sansum Diabetes Research Institute and the University of Pavia answer with a stack of LSTM networks. What sets the work apart from earlier energy expenditure models is the structure. One network learns from a whole cohort of people with type 1 diabetes, a second from people doing the same kind of exercise, and a third from a single wearer, and each level hands its estimate down to the next. The idea is to give a personal model the stability of crowd data without losing what makes one body different.
Key points
- Smartwatch heart rate and step count go in, and an estimate of metabolic equivalents comes out every 15 minutes, matching the update rate of most automated insulin systems.
- A population LSTM trained on 33 adults with type 1 diabetes feeds its estimate to a personal LSTM, and that two level model scored best overall.
- Every personalized and hierarchical result comes from one participant, so the paper is a proof of concept rather than a validation.
- The hierarchy lowered percentage error from 24.74 to about 22.9 percent, but most gains sit inside one standard deviation of the single person model.
- The training targets are the watch’s own MET values, and moderate intensity periods were caught only 17.35 percent of the time.
Why an insulin pump needs to know you are moving
Exercise is one of the hardest things for an automated insulin delivery system to handle. Muscles take up glucose faster during activity, insulin sensitivity rises, and the effect can last for hours. The paper summarises the clinical pattern clearly. Insulin needs usually do not change with sedentary activity, they fall during continuous light to moderate aerobic exercise, and they can rise soon after vigorous work. A system that does not know which of those is happening has to wait for the glucose trace to tell it, and glucose sensors lag behind the body.
Energy expenditure, expressed in metabolic equivalents or METs, is a natural way to describe that intensity. One MET is roughly the energy a person burns sitting quietly, about one kilocalorie per kilogram per hour. Walking slowly is around two or three METs, brisk walking three to six, running well above six. The authors also point to studies showing that people with type 1 diabetes tend to have a higher basal energy expenditure than people without it, partly because of poor glycemic control, which means generic MET tables and consumer fitness algorithms may misjudge them.
So the goal is specific. Estimate METs continuously, around the clock, from sensors people already wear, and do it well enough for one person that an insulin controller could use the number. Fifteen minutes is the right resolution because most automated insulin systems update their control action about that often.
What earlier models got right and where they stopped
Energy expenditure estimation from wearables is an old field. Freedson, Crouter and Sasaki built linear regressions on accelerometer counts. Schrack and colleagues worked from heart rate alone, which tends to be accurate during moderate and vigorous activity but drifts at low intensity, when heart rate responds to stress, caffeine and posture as much as to movement. Zakeri and Romero Ugalde combined accelerometry with heart rate and did better. Several groups found that separate models per activity type help.
For type 1 diabetes specifically, Jacobs and colleagues validated an existing linear model in 2015, and Carnero and colleagues built a stepwise regression in 2024. Both are population models. They fit one equation to everyone. Sevil and colleagues compared machine learning methods, including deep networks, and found LSTMs the most accurate, but on short controlled experiments rather than free living days. Meanwhile Cortes and colleagues showed in 2024 that LSTM models trained on an individual can beat population models for energy expenditure in general.
That leaves a gap this paper aims at. Personal models fit one body better but need a lot of data from that body. Population models are stable but blur individual differences. The hierarchical forecasting literature, which the authors borrow from economics and energy demand work by Athanasopoulos, Hyndman and others, offers a way to combine levels. We have seen the same tension between global and local models in a very different domain, in our piece on global versus local AI for canopy height mapping, and the trade offs rhyme.
Three LSTMs, from the crowd to one wrist
The data behind each level
The data come from 33 adults with type 1 diabetes enrolled in a four week at home exercise study run with the Jaeb Center for Health Research. Each participant was randomly assigned aerobic, interval or resistance exercise videos to follow twice a week and logged any other activity in a phone app. Everyone wore a Garmin Vivosmart 3, which recorded heart rate every 15 seconds and steps and METs in 15 minute blocks. The cohort averaged 31 years of age, 17 years since diagnosis, a body mass index of 26.2 and an HbA1c of 7.8 percent. Twenty four were men and nine women, and 31 of the 32 who reported their race were White.
| Level | People | Split | Samples | Chunks |
|---|---|---|---|---|
| Population | 33 | 22 train, 10 validation, 1 test | 70,583 | 562 |
| Activity, aerobic group | 11 | 7 train, 3 validation, 1 test | 25,047 | 198 |
| Subject | 1 | 80, 10 and 10 percent of that person’s data, 18 fold cross validation | 2,472 | 18 |
Heart rate was averaged into the same 15 minute windows as the steps and METs. Any window missing one of the three signals was removed, which cut the population data by 14 percent, the aerobic group by 16 percent and the single subject by 7 percent. Removing windows leaves holes, so each person’s series was split into continuous chunks at every gap, and chunks shorter than five samples, a little over an hour, were discarded. After cleaning, each participant had on average 22 days of usable data. Inputs were scaled to the zero to one range using training set minimums and maximums.
The LSTM cell itself
Every level uses the same building block, a single layer LSTM followed by a linear output. The gates are the standard ones from Hochreiter and Schmidhuber with the forget gate of Gers and colleagues.
Here \(u_k\) holds the inputs at window \(k\), heart rate and step count for a plain model, and \(y_k\) is the MET estimate for that same window. That detail matters later. The model estimates the present window from the present window’s sensors. It does not look ahead.
How the levels connect
Three single level models are trained first, LSTM p on the population, LSTM a on the aerobic group and LSTM s on the one subject. The hierarchy is then built by stacking. The upper model’s MET estimate joins heart rate and steps as a third input to the lower model.
Four stacked variants were tested. LSTM pa puts population above activity, LSTM ps puts population directly above the subject, LSTM as puts activity above the subject, and LSTM pas chains all three levels. Transfer learning carries knowledge from the data rich upper levels into the data poor lower ones, which the authors describe as the way to keep training time manageable.
Mechanically, this is a form of stacking that the machine learning world would recognise from ensemble methods. The upper model’s output becomes a learned feature for the lower model. It is simpler than formal hierarchical reconciliation, which forces forecasts at different levels to add up, and that simplicity is part of its appeal for a small dataset.
Training choices
Hidden sizes of 32, 64, 96 and 128 units, learning rates from 0.001 to 0.008, mini batches of 16, 32 and 64, and up to 750 epochs were searched with KerasTuner, using validation loss to choose. Adam minimised a squared error loss, with learning rate 0.005 and mini batch size 32 winning for every model and early stopping deciding the epoch count. Training used TensorFlow on a Precision 7920 tower workstation with a Xeon Silver 4208 processor, 16 GB of memory and a Radeon Pro WX 3100 card. The seven models took 20 days to train in total, from 35 minutes for the subject model to four days for the population model and six days for the three level chain.
A small note for anyone reimplementing. The paper calls this an MSE loss but prints it with absolute values, which would be mean absolute error. The text says MSE and the training description says squared error, so the version above follows the text.
The hierarchy is a pipeline of feature hand offs. A model trained on many people produces a MET estimate, and a model trained on one person learns how to correct that estimate for its wearer.
How close the estimates came
Regression accuracy was measured as mean absolute error, mean absolute percentage error and root mean squared error on held out data. For models trained on the single subject, results are averaged across the 18 cross validation folds.
| Model | Levels | MAE (MET) | MAPE (%) | RMSE (MET) |
|---|---|---|---|---|
| LSTM p | Population | 0.77 | 44.11 | 1.04 |
| LSTM a | Activity | 0.71 | 41.09 | 0.99 |
| LSTM pa | Population, activity | 0.68 | 38.66 | 0.95 |
| LSTM s | Subject | 0.44 (0.12) | 24.74 ± 4.72 | 0.62 (0.14) |
| LSTM as | Activity, subject | 0.43 ± 0.09 | 22.92 ± 4.62 | 0.62 (0.18) |
| LSTM ps | Population, subject | 0.44 ± 0.10 | 22.80 ± 5.37 | 0.67 ± 0.25 |
| LSTM pas | All three | 0.42 (0.10) | 22.93 ± 5.64 | 0.62 (0.18) |
The big jump is between population models and personal ones. Going from LSTM p to LSTM s roughly halves the percentage error, from 44 to 25 percent. That is strong evidence for the paper’s starting premise that individual bodies differ enough to need individual models.
The hierarchy’s own contribution is much smaller. Adding a population or activity level above the subject model moves MAE from 0.44 to between 0.42 and 0.44 and MAPE from 24.74 to about 22.9 percent. RMSE stays at 0.62 or rises to 0.67. The MAPE gain of about two points is smaller than the 4.72 point standard deviation of the subject model itself, and no significance test is reported. On regression alone, the honest reading is that hierarchy helps a little, possibly, for this one person.
When the numbers become insulin decisions
An insulin controller is more likely to act on an intensity class than on a raw MET value, so the authors also scored the estimates after sorting them into the four standard bands. Sedentary is 1.5 METs or less, light runs to 3.0, moderate to 6.0, and vigorous is anything above.
| Model | Accuracy | Balanced accuracy | Recall | Precision | F1 |
|---|---|---|---|---|---|
| LSTM p | 74.93 | 64.14 | 43.95 | 55.27 | 47.08 |
| LSTM a | 77.30 | 65.06 | 44.84 | 43.55 | 51.92 |
| LSTM s | 86.68 ± 3.62 | 71.46 ± 5.31 | 58.24 ± 8.24 | 70.09 ± 9.22 | 63.47 ± 11.05 |
| LSTM as | 87.22 ± 3.66 | 71.78 ± 5.33 | 58.40 ± 7.74 | 71.74 ± 12.60 | 68.08 ± 11.24 |
| LSTM ps | 87.32 ± 3.77 | 72.59 ± 6.59 | 60.02 ± 9.98 | 73.40 ± 10.92 | 67.89 ± 9.72 |
| LSTM pas | 87.19 ± 3.68 | 71.91 ± 6.07 | 58.74 ± 8.45 | 68.22 ± 11.03 | 67.04 ± 10.17 |
LSTM ps comes out on top in every column. The authors read the pattern as one level underfitting, three levels overfitting and two levels landing in between, and they argue that a top level trained on a broad population beats one trained on a narrow activity group, since LSTM ps edges LSTM as. Both readings are reasonable. Both also rest on differences of one or two points with standard deviations of six to twelve.
The headline accuracy of 87 percent needs care. Each class is scored one against the rest and then averaged, so a class that almost never occurs gets near perfect accuracy just by never being predicted. The vigorous class shows exactly that, 99.95 percent accuracy from a test set that contained two vigorous samples out of 2,472. Balanced accuracy, which weights hits and correct rejections equally, is the better summary, and for the best model it is 72.59 percent.
The per class results for LSTM ps tell the real story. Sedentary windows are recognised with 93.63 percent precision, so when the model says sedentary it is usually right. Light activity is caught 92.11 percent of the time but with 64.04 percent precision, meaning the model also calls many other windows light. Moderate activity, the band where an insulin system would most want to reduce delivery, is caught only 17.35 percent of the time. Vigorous activity cannot be judged at all.
The class an insulin controller most needs to see, moderate exercise, was recognised in fewer than one window in five.Reading of Table 7, Aiello, Toffanin et al., Engineering Applications of Artificial Intelligence 2025
The authors offer a fair explanation. The model was trained to estimate a continuous value, not to classify, and its errors of around two thirds of a MET are enough to push a true 3.2 into the light band. They propose attaching a reliability score that drops as an estimate nears a class edge, which is a sensible idea and one we include in the code below. It does not change the fact that, as trained, the model mostly reads moderate exercise as light.
There is a partly reassuring finding from a safety angle. The authors state that the model did not label any activity as sedentary, the mistake most likely to leave too much insulin on board during exercise. Table 7 complicates that slightly, because a sedentary precision of 93.63 percent means some windows predicted as sedentary were really something else, so the claim probably refers to logged exercise sessions rather than every window. False positives made up about 22 percent for the light class and about 1 percent for the moderate class, so false alarms concentrate in the lower intensity band where a wrong insulin cut would matter less.
The design choices that limit every claim
The target is the watch’s own guess
This is the issue I would put first. The MET values the network learns to reproduce are not measured energy expenditure. They are the MET values the Garmin Vivosmart 3 calculated from its own heart rate and step data. No indirect calorimetry, no doubly labelled water, no laboratory reference. A network trained on the watch’s heart rate and steps to predict the watch’s METs is, in large part, learning to imitate the watch’s algorithm.
That matters because the paper’s motivation is that people with type 1 diabetes burn energy differently and that commercial estimates may be off for them. If the consumer algorithm underestimates METs for this population, the hierarchical LSTM will learn the same underestimate. The work shows that a personal model can match one device’s output closely, which is useful. It does not show that the estimates are closer to true energy expenditure than the watch already was.
One person carries all the personal results
The population model saw 33 people. Everything personal, including the four hierarchical variants and the best model, was trained and tested on one participant, chosen at random from the aerobic group, using 18 fold cross validation over that person’s 18 data chunks. The authors are upfront about this and call it a proof of concept limited by training time. Still, one person cannot tell us whether the hierarchy helps people in general, how much the gain varies between people, or whether some people are hurt by it.
The paper also does not say whether this participant’s data were excluded when the population and activity models were trained. If they were included, part of the benefit of stacking could come from the upper models having already seen the test person. Population level results have a similar thinness, since the population and activity test sets each held a single participant.
Estimation, not prediction
The paper often uses the language of forecasting, but the model estimates the MET value of the current window from that window’s heart rate and steps. With 15 minute windows, an insulin controller learns about a bout of exercise up to fifteen minutes after it begins. That is still faster than waiting for glucose to fall, and the authors note that offline training keeps the online computation trivial. It is not the anticipation that would let a controller cut insulin before exercise starts.
The study shows that a personal model with a population model above it can reproduce one watch’s MET estimates for one person a little better than a personal model alone. Whether that generalises, or tracks true energy use, is still open.
Clinical translation gap
The intended use is clear. Feed predicted activity intensity into an automated insulin delivery system so it can reduce insulin during aerobic exercise, perhaps asking the user to confirm first. The authors’ group has published reviews of such systems and activity aware controllers, and the 15 minute cadence fits. The distance between this paper and that use is still large.
The model has not been tested in closed loop, in simulation or with patients. Nobody has measured whether feeding these estimates into a controller would change time in range or hypoglycemia. The classification errors that matter most, missed moderate exercise, would mean insulin stays too high during activity, which is the scenario automated systems already struggle with. False light flags could trigger unneeded insulin reductions and raise glucose. Any controller using this signal would need safety limits that assume the estimate is often wrong.
Device dependence is another gap. The model was trained on one watch model’s sensors and one watch model’s MET output. A different watch, a new firmware version or a loose strap changes both input and target. Regulators would treat software that adjusts insulin as a high risk medical device, which demands prospective clinical evidence that this work does not attempt.
The training cost is also unusual for a clinical tool. Twenty days of compute for seven small LSTMs on a workstation, and six days for one three level chain, is long for networks of this size on about seventy thousand samples. If every new user needs a personal model, the training pipeline would have to be much faster before deployment makes sense, perhaps by fine tuning only the lowest level as the transfer learning design already suggests.
Limitations
Sample size is the first limitation. The population is 33 adults, the aerobic group 11, and the personalized analysis one person with 2,472 windows. The test sets for the population and activity levels each hold one participant. Confidence intervals across people are not possible with this design.
The cohort is not diverse. It is mostly male, 24 of 33, mostly White, 31 of the 32 who reported race, and mostly physically active, with 20 participants classed as health enhancing physically active by the International Physical Activity Questionnaire. Children, older adults, people with obesity and people who exercise rarely are underrepresented or absent, and the selected subject cycled daily on top of the study exercise.
Class imbalance limits the clinical metrics. Most windows are sedentary or light, moderate windows are few and vigorous ones almost absent, so per class results for the most clinically relevant bands rest on small counts. The reported spread for moderate recall, ± 2.07, is identical to the spread for moderate specificity in the same row, which may be a typesetting slip and makes that figure hard to interpret.
Data removal may bias the series. Windows with any missing signal were deleted, 14 percent of the population data, and missingness is unlikely to be random. Wrist sensors can drop heart rate readings during vigorous motion, which is exactly when intensity is highest. Finally, the data cannot be shared, the code is not released, and the absence of a significance test for the hierarchical gains makes the comparison between LSTM s, LSTM as, LSTM ps and LSTM pas suggestive rather than settled.
Where hierarchical personalization could go next
The structure is more interesting than the specific numbers. Stacking a crowd model under a personal one is a cheap way to personalise any physiological time series where each person has little data and the population has a lot. Continuous glucose prediction, heart rate based stress detection and sleep staging from wearables all share that shape. The same instinct shows up in transfer learning for vibroacoustic surrogates, another Engineering Applications of Artificial Intelligence paper where a model pretrained on plentiful data is adapted to a scarce target.
For clinical decision support, the work also connects to the broader problem of fusing patchy health data that we covered in ETF UML for incomplete ICU data. In both cases the hard part is not the network but making a model trustworthy when each patient’s record is short and uneven.
Three extensions would make this line of work much stronger. A reference standard, even a small laboratory session with indirect calorimetry per participant, would turn MET imitation into MET measurement. Evaluating all 33 participants, ideally with a leave one person out design, would show whether the hierarchy helps people in general. And a short prediction horizon, estimating the next window rather than the current one, would give an insulin controller a head start. The authors list GRU and transformer architectures as future work, but data and evaluation design matter more here than the choice of recurrent cell.
Conclusion
The core achievement of this study is showing that a smartwatch’s heart rate and step count can support a personal, continuous estimate of activity intensity in type 1 diabetes, at the same 15 minute rhythm an automated insulin system uses. Personal models cut the percentage error of a population model nearly in half, and stacking a population model above the personal one produced the best classification scores in the study.
The conceptual move is to treat personalization as a hierarchy rather than a choice. Instead of picking between a stable crowd model and a sharp individual one, the network lets the individual model correct the crowd model’s estimate. It is a simple idea, close to stacking in ensemble learning, and it fits small medical datasets where every patient brings a few weeks of data and nothing more.
The idea should transfer to other wearable signals and other conditions where people differ widely, and the paper’s own suggestion of a reliability score near class edges is worth adopting in any classifier built on a continuous estimate.
The limits are just as real. All personal results come from one participant, the targets are the watch’s own MET values rather than measured energy use, moderate exercise is mostly missed, and the hierarchical gains are within the noise of the single person model. None of this has been tested in an insulin controller.
The next study should measure true energy expenditure, include every participant, and run the estimates through a closed loop simulator before any patient sees them. If the hierarchy still helps under those conditions, it could make exercise much less of a guessing game for automated insulin delivery. For now, it is a careful first step toward a pump that knows when its wearer is moving.
For more analysis of AI in clinical care, browse the Medical AI collection on aitrendblend.
A reference implementation in PyTorch
The code below is an educational reimplementation in PyTorch written from the paper’s description. The authors used TensorFlow and Keras and did not release code, so this is not their implementation. It includes preprocessing into 15 minute chunks, min and max scaling, the LSTM block, stacked hierarchical models, weight transfer from an upper level, Adam training with early stopping, chunk level cross validation, the regression and classification metrics, the reliability score the authors propose as future work, and a smoke test on synthetic wearers.
"""
Hierarchical LSTM for real time MET estimation from wrist heart rate and step count.
Educational PyTorch reimplementation written from the description in
Aiello, Toffanin et al., Engineering Applications of Artificial Intelligence 159 (2025) 111758.
The authors used TensorFlow and Keras and did not release code. This is not their code.
Levels
p population every participant in the cohort
a activity type participants assigned the same exercise video (aerobic)
s subject one individual
Stacked models feed the upper level MET estimate to the lower level as a third input.
"""
import math
import random
import numpy as np
import torch
import torch.nn as nn
STEP_MIN = 15 # 15 minute epochs, the watch MET and step resolution
MIN_CHUNK = 5 # chunks of 4 samples or fewer (under about an hour) are dropped
MET_EDGES = (1.5, 3.0, 6.0) # sedentary <= 1.5 < light <= 3.0 < moderate <= 6.0 < vigorous
CLASSES = ["Sedentary", "Light", "Moderate", "Vigorous"]
# ----------------------------------------------------------------------------
# Preprocessing
# ----------------------------------------------------------------------------
def aggregate_hr(hr_15s):
"""Heart rate arrives every 15 s. Average it over non overlapping 15 minute bins (60 samples)."""
n = len(hr_15s) // 60
return np.asarray(hr_15s[: n * 60], dtype=float).reshape(n, 60).mean(axis=1)
def split_chunks(hr, sc, met):
"""Drop samples with any missing value and split the series wherever a gap appears.
Keep only chunks long enough to cover the dominant dynamics."""
valid = ~(np.isnan(hr) | np.isnan(sc) | np.isnan(met))
chunks, start = [], None
for k, ok in enumerate(np.append(valid, False)):
if ok and start is None:
start = k
elif not ok and start is not None:
if k - start >= MIN_CHUNK:
chunks.append(np.stack([hr[start:k], sc[start:k], met[start:k]], axis=1))
start = None
return chunks
class MinMax:
"""Eq. 16. Fit on training data only, then reuse on validation and test data."""
def fit(self, x):
self.lo, self.hi = x.min(axis=0), x.max(axis=0)
return self
def __call__(self, x):
return (x - self.lo) / np.maximum(self.hi - self.lo, 1e-8)
# ----------------------------------------------------------------------------
# Models
# ----------------------------------------------------------------------------
class LSTMBlock(nn.Module):
"""Eq. 1 to 7. One LSTM layer followed by a linear output layer, y_k = W_y h_k + b_y."""
def __init__(self, n_inputs, hidden):
super().__init__()
self.lstm = nn.LSTM(n_inputs, hidden, batch_first=True)
self.head = nn.Linear(hidden, 1)
def forward(self, u): # u: (B, K, n_inputs)
h, _ = self.lstm(u)
return self.head(h).squeeze(-1) # (B, K), one MET estimate per time step
class StackedLSTM(nn.Module):
"""Eq. 11 to 14. A frozen upper level model produces y_upper, which joins HR and SC
as a third input of the lower level block."""
def __init__(self, upper: nn.Module, hidden):
super().__init__()
self.upper = upper
for p in self.upper.parameters():
p.requires_grad_(False)
self.lower = LSTMBlock(3, hidden)
def forward(self, u):
with torch.no_grad():
y_up = self.upper(u)
return self.lower(torch.cat([u, y_up.unsqueeze(-1)], dim=-1))
def transfer_weights(src: LSTMBlock, dst: LSTMBlock):
"""Transfer learning from a data rich level to a data poor one. Recurrent weights, biases
and the output head are copied when sizes match. Input weights for HR and SC are copied
and the extra input column (the upper level estimate) starts at zero."""
if src.lstm.hidden_size != dst.lstm.hidden_size:
return False
with torch.no_grad():
n_src = src.lstm.weight_ih_l0.shape[1]
dst.lstm.weight_ih_l0.zero_()
dst.lstm.weight_ih_l0[:, :n_src].copy_(src.lstm.weight_ih_l0)
dst.lstm.weight_hh_l0.copy_(src.lstm.weight_hh_l0)
dst.lstm.bias_ih_l0.copy_(src.lstm.bias_ih_l0)
dst.lstm.bias_hh_l0.copy_(src.lstm.bias_hh_l0)
dst.head.load_state_dict(src.head.state_dict())
return True
# ----------------------------------------------------------------------------
# Training
# ----------------------------------------------------------------------------
def to_tensors(chunks, scaler):
"""Each chunk becomes one sequence. Inputs are scaled HR and SC, the target is raw METs."""
out = []
for c in chunks:
x = torch.tensor(scaler(c[:, :2]), dtype=torch.float32)
y = torch.tensor(c[:, 2], dtype=torch.float32)
out.append((x, y))
return out
def batches(seqs, batch_size, shuffle=True):
idx = list(range(len(seqs)))
if shuffle:
random.shuffle(idx)
for i in range(0, len(idx), batch_size):
group = [seqs[j] for j in idx[i:i + batch_size]]
L = max(len(x) for x, _ in group)
X = torch.zeros(len(group), L, 2)
Y = torch.zeros(len(group), L)
M = torch.zeros(len(group), L)
for b, (x, y) in enumerate(group):
X[b, :len(x)], Y[b, :len(y)], M[b, :len(y)] = x, y, 1.0
yield X, Y, M
def masked_mse(pred, y, mask):
"""Eq. 15 is labelled MSE in the paper, so squared error is used here, ignoring padding."""
return ((pred - y) ** 2 * mask).sum() / mask.sum().clamp_min(1)
def fit(model, train, val, epochs=750, lr=5e-3, batch_size=32, patience=25, verbose=False):
"""Adam, learning rate 0.005, mini batch 32, early stopping on validation loss."""
opt = torch.optim.Adam([p for p in model.parameters() if p.requires_grad], lr=lr)
best, best_state, wait = math.inf, None, 0
for ep in range(epochs):
model.train()
for X, Y, M in batches(train, batch_size):
loss = masked_mse(model(X), Y, M)
opt.zero_grad()
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
v = evaluate_loss(model, val)
if v < best - 1e-5:
best, wait = v, 0
best_state = {k: t.clone() for k, t in model.state_dict().items()}
else:
wait += 1
if wait >= patience:
break
if verbose and ep % 10 == 0:
print(f" epoch {ep:3d} val mse {v:.4f}")
if best_state is not None:
model.load_state_dict(best_state)
return model
@torch.no_grad()
def evaluate_loss(model, seqs):
model.eval()
tot, n = 0.0, 0
for X, Y, M in batches(seqs, 64, shuffle=False):
tot += (((model(X) - Y) ** 2) * M).sum().item()
n += M.sum().item()
return tot / max(n, 1)
@torch.no_grad()
def predict(model, seqs):
model.eval()
ys, ps = [], []
for x, y in seqs:
ps.append(model(x.unsqueeze(0)).squeeze(0).numpy())
ys.append(y.numpy())
return np.concatenate(ys), np.concatenate(ps)
# ----------------------------------------------------------------------------
# Metrics
# ----------------------------------------------------------------------------
def regression_metrics(y, p):
"""Eq. 17 to 19."""
err = y - p
return {"MAE": float(np.abs(err).mean()),
"MAPE": float((np.abs(err) / np.maximum(np.abs(y), 1e-8)).mean() * 100),
"RMSE": float(np.sqrt((err ** 2).mean()))}
def met_class(m):
"""Quantize METs into the four intensity classes used in the paper."""
return np.digitize(m, MET_EDGES, right=True)
def classification_metrics(y, p):
"""One versus rest metrics per class (Eq. 20 to 25), then macro averaged.
Classes that never occur in the test set are skipped for recall based metrics."""
yc, pc = met_class(y), met_class(p)
per = {}
for c, name in enumerate(CLASSES):
tp = np.sum((pc == c) & (yc == c)); tn = np.sum((pc != c) & (yc != c))
fp = np.sum((pc == c) & (yc != c)); fn = np.sum((pc != c) & (yc == c))
rec = tp / (tp + fn) if tp + fn else np.nan
spe = tn / (tn + fp) if tn + fp else np.nan
pre = tp / (tp + fp) if tp + fp else np.nan
f1 = 2 * pre * rec / (pre + rec) if pre and rec and not np.isnan(pre + rec) else np.nan
per[name] = {"n": int(tp + fn), "accuracy": (tp + tn) / len(yc) * 100,
"balanced_accuracy": np.nanmean([rec, spe]) * 100,
"recall": rec * 100, "specificity": spe * 100,
"precision": pre * 100, "f1": f1 * 100}
macro = {k: float(np.nanmean([per[c][k] for c in CLASSES]))
for k in ["accuracy", "balanced_accuracy", "recall", "specificity", "precision", "f1"]}
return per, macro
def reliability(p, width=0.5):
"""Our addition, following the paper's own suggestion. Confidence in the predicted class
falls toward zero as the MET estimate approaches a class edge."""
d = np.min(np.abs(np.asarray(p)[:, None] - np.array(MET_EDGES)[None, :]), axis=1)
return np.clip(d / width, 0, 1)
# ----------------------------------------------------------------------------
# Splits
# ----------------------------------------------------------------------------
def participant_split(ids, seed=0):
"""Population and activity levels. 60 percent train, 30 percent validation, 10 percent test,
split by participant so nobody appears in two partitions."""
rng = random.Random(seed)
ids = ids[:]
rng.shuffle(ids)
n = len(ids)
n_tr, n_va = round(0.6 * n), round(0.3 * n)
return ids[:n_tr], ids[n_tr:n_tr + n_va], ids[n_tr + n_va:]
def chunk_kfold(chunks, k):
"""Subject level. K fold over chunks, with K equal to the number of chunks in the paper."""
for i in range(k):
test = [chunks[i]]
rest = [c for j, c in enumerate(chunks) if j != i]
n_val = max(1, len(rest) // 9)
yield rest[n_val:], rest[:n_val], test
# ----------------------------------------------------------------------------
# Synthetic cohort for the smoke test
# ----------------------------------------------------------------------------
def synthetic_person(days=3, aerobic=False, seed=0):
rng = np.random.default_rng(seed)
hr_rest = rng.uniform(55, 75)
gain = rng.uniform(0.8, 1.2) # person specific heart rate response
n = days * 96 # 96 samples of 15 minutes per day
t = np.arange(n)
activity = np.zeros(n)
for d in range(days):
start = d * 96 + rng.integers(28, 76)
activity[start:start + rng.integers(2, 5)] = rng.uniform(1.5, 4.5) # bouts of exercise
if aerobic:
s2 = d * 96 + 80
activity[s2:s2 + 2] = 3.5
sleep = ((t % 96) < 28).astype(float)
met = 1.0 + 0.4 * (1 - sleep) + activity + rng.normal(0, 0.1, n)
sc = np.clip(activity * 900 * gain + (1 - sleep) * rng.uniform(0, 150, n), 0, None)
hr15 = np.repeat(hr_rest + 18 * gain * (met - 1.0), 60) + rng.normal(0, 3, n * 60)
hr = aggregate_hr(hr15)
drop = rng.random(n) < 0.03
hr[drop] = np.nan
return split_chunks(hr, sc, met)
if __name__ == "__main__":
torch.manual_seed(0); random.seed(0); np.random.seed(0)
cohort = {i: synthetic_person(aerobic=(i % 3 == 0), seed=i) for i in range(12)}
aerobic_ids = [i for i in cohort if i % 3 == 0]
subject = aerobic_ids[0]
print("chunks for the chosen subject:", len(cohort[subject]))
# population level
tr, va, te = participant_split([i for i in cohort if i != subject])
train_chunks = [c for i in tr for c in cohort[i]]
scaler = MinMax().fit(np.concatenate(train_chunks)[:, :2])
pop = fit(LSTMBlock(2, 32), to_tensors(train_chunks, scaler),
to_tensors([c for i in va for c in cohort[i]], scaler), epochs=40)
# subject level, plain and stacked on the population model, with chunk level K fold
chunks = cohort[subject]
res = {"LSTM_s": [], "LSTM_ps": []}
allp = {"LSTM_s": ([], []), "LSTM_ps": ([], [])}
for k_tr, k_va, k_te in chunk_kfold(chunks, k=len(chunks)):
s_model = fit(LSTMBlock(2, 32), to_tensors(k_tr, scaler), to_tensors(k_va, scaler), epochs=40)
ps_model = StackedLSTM(pop, hidden=32)
transfer_weights(pop, ps_model.lower)
ps_model = fit(ps_model, to_tensors(k_tr, scaler), to_tensors(k_va, scaler), epochs=40)
for name, m in (("LSTM_s", s_model), ("LSTM_ps", ps_model)):
y, p = predict(m, to_tensors(k_te, scaler))
res[name].append(regression_metrics(y, p))
allp[name][0].append(y); allp[name][1].append(p)
for name in res:
mae = np.mean([r["MAE"] for r in res[name]])
rmse = np.mean([r["RMSE"] for r in res[name]])
y = np.concatenate(allp[name][0]); p = np.concatenate(allp[name][1])
_, macro = classification_metrics(y, p)
print(f"{name:8s} MAE {mae:.3f} RMSE {rmse:.3f} macro balanced acc {macro['balanced_accuracy']:.1f}")
print("reliability of three example estimates:", reliability([1.2, 2.9, 4.5]).round(2))
print("smoke test passed")
Frequently asked questions
What does the hierarchical LSTM predict?
It estimates metabolic equivalents, or METs, every 15 minutes from the heart rate and step count recorded by a wrist smartwatch. The estimate can be read as a number or grouped into sedentary, light, moderate and vigorous intensity.
Why does energy expenditure matter for people with type 1 diabetes?
Physical activity changes how much insulin the body needs. Insulin needs usually stay the same with sedentary activity, fall during continuous light to moderate aerobic exercise and can rise soon after vigorous work, so an automated insulin system that knows the current intensity could adjust delivery and lower the risk of hypoglycemia.
Which version of the model worked best?
The two level model that stacks a population LSTM on top of a subject LSTM, called LSTM ps, scored best on the classification metrics, with 87.32 percent macro accuracy and 72.59 percent balanced accuracy. Its mean absolute error of 0.44 MET matched the single subject model.
How many people was the personalized model tested on?
One. The population model was trained on data from 33 adults, but every subject level and hierarchical result comes from a single participant, evaluated with 18 fold cross validation over that person’s data. The authors describe it as a proof of concept.
Does the model measure true calorie burn?
No. The training targets are the MET values reported by the Garmin Vivosmart 3 watch itself, not a laboratory measurement such as indirect calorimetry. The model learns to reproduce the watch estimate from the watch sensors, which limits what it can say about real energy use.
Can this model be used to dose insulin today?
No. It detected only 17.35 percent of moderate intensity periods, the test set held just two vigorous samples, and it has not been tested inside an insulin delivery system. Insulin decisions should stay with a care team and approved devices.
Read the open access paper by Aiello, Toffanin and colleagues in Engineering Applications of Artificial Intelligence, or the clinical study that collected the exercise data.
Read the paper Source exercise studyAiello E. M., Toffanin C., Riddell M. C., Martin C. K., Patton S. R., Gal R. L., Doyle F. J. III. A hierarchical network model for the estimate of the energy expenditure in individuals with type 1 diabetes. Engineering Applications of Artificial Intelligence 159 (2025) 111758. Open access under a CC BY NC ND licence. doi.org/10.1016/j.engappai.2025.111758
This analysis is based on the published paper and an independent evaluation of its claims.
