
Longitudinal sequence tensors for deep sequence models
Source:R/tensors.R
extract_longitudinal_tensors.RdBuilds a 3D integer array (N x max_visits x max_tokens) of concept tokens for a cohort, one slice per prior
visit (most recent first) within the look-back window, using DuckDB queries. Tokens are
hash(concept_id) % (vocab_size - 1) + 1 for conditions, drugs and procedures (and, optionally, labs); 0 pads.
R port of omop_etl.tensor.extract_longitudinal_tensors(); token ids are identical to the Python ones for the
same DuckDB version. Rows follow ORDER BY subject_id, cohort_start_date. Use the result with torch/keras, e.g.
torch::torch_tensor(x, dtype = torch::torch_long()).
Usage
extract_longitudinal_tensors(
con,
cohort_table = "cohort",
max_visits = MAX_LONGITUDINAL_VISITS,
max_tokens = MAX_TOKENS_PER_VISIT,
vocab_size = VOCAB_SIZE,
lookback_days = 365L,
include_index_stay = FALSE,
include_labs = FALSE
)
MAX_LONGITUDINAL_VISITS
MAX_TOKENS_PER_VISIT
VOCAB_SIZEFormat
Integer constants: MAX_LONGITUDINAL_VISITS (20), MAX_TOKENS_PER_VISIT (30), VOCAB_SIZE (7477).
An object of class integer of length 1.
An object of class integer of length 1.
Arguments
- con
A DuckDB DBI connection to the CDM.
- cohort_table
Cohort table holding
subject_idandcohort_start_date.- max_visits
Maximum number of prior encounters per patient (default 20).
- max_tokens
Maximum number of concept tokens per encounter (default 30).
- vocab_size
Token dictionary size (default 7477).
- lookback_days
Look-back window in days before the index date (default 365).
- include_index_stay
If
TRUE, also tokenize a stay that starts ONcohort_start_date(default window isvisit_start_date < cohort_start_date). For cohorts anchored at admission this adds the index stay, whose later records may not be known at prediction time (leakage risk).- include_labs
If
TRUE, add measurement tokenshash(measurement_concept_id * 3 + flag)withflag0 = within or no reference range, 1 = belowrange_low, 2 = aboverange_high. Token ids come from DuckDBhash(), so they are stable only within one DuckDB version: train and score with the same one.