Views
No views yet
local_model_path directory must contain:config.json — LSTMBERTConfig (RobertaConfig-derived) matching the saved weightspytorch_model.bin — Model weights saved by transformers (compatible with from_pretrained)vocab.json, merges.txt, or tokenizer.json) compatible with RobertaTokenizerpip install torch transformers1project_root/
2├── app/
3│ ├── config/
4│ │ └── model_config.py # Contains LSTMBERTConfig class
5│ ├── models/
6│ │ ├── base_model.py # Contains ModelClass
7│ │ ├── utils.py # Contains date_linear_impute, dates_to_log_deltas
8│ │ └── modeling.py # Contains LSTMBERT and PredictionPipeline
9└── main.py # Your execution script1from app.models.modeling import PredictionPipeline
2
3# 1. Initialize the pipeline with the path to your trained model artifacts
4model_path = "./saved_model"
5pipeline = PredictionPipeline(local_model_path=model_path)
6
7# 2. Prepare your input data
8# 'case': A list of strings, where each string is the text of one visit/document
9case_history = [
10 "Patient presents with mild headache and nausea.",
11 "Follow-up: Headache persists, recommended CT scan.",
12 "Scan results negative. Symptoms resolved."
13]
14
15# 'dates': A list of strings corresponding to the visits
16# Format: "DDMonYYYY" (e.g., "10Jan2024")
17# Use empty string "" for unknown/missing dates
18visit_dates = [
19 "10Jan2024",
20 "15Jan2024",
21 "20Feb2024"
22]
23
24# 3. Run Inference
25# Returns:
26# - probability: Float (Probability of the positive class, e.g., class 1)
27# - attention_weights: List[float] (Importance score for each visit)
28probability, attention_weights = pipeline.predict(case_history, visit_dates)
29
30print(f"Prediction Probability: {probability:.4f}")
31print("Visit Importance:")
32for date, weight in zip(visit_dates, attention_weights):
33 print(f" - {date}: {weight:.4f}")case): A List[str] of length $V$ representing the number of visits. Each string is tokenized and truncated/padded to cfg.max_length (default: 128 tokens).dates): A List[str] matching the length of the text list. Format: %d%b%Y (e.g., 10Jan2024).
"" to indicate missing/unknown datesdate_linear_impute and dates_to_log_deltas to convert dates into two floating-point features per visit(log_prev, log_start) — the log-delta since the previous visit and log-delta since the start of the historysyn_prob (float): Softmax probability for the positive class (class index 1). If your model uses different label mapping, adjust accordingly.attn_list (List[float]): Attention weights over visits (sums to approximately 1.0), representing how much the model focused on each specific visit in the sequence.LSTMBERTConfig class inheriting from RobertaConfig. Your config.json must include these parameters:| Parameter | Description | Example Value |
|---|---|---|
hidden_size | RoBERTa hidden dimension | 768 |
max_length | Maximum sequence length per visit | 128 |
lstm_hidden | Hidden size of the LSTM layer | 256 |
lstm_layers | Number of stacked LSTM layers | 1 |
attn_dim | Dimension of the internal attention projection | 64 |
output_dim | Number of classification labels | 2 |
visit_time_proj | Dimension to project the 2 time features into before LSTM | 8 |
architectures | Model class name | ["LSTMBERT"] |
config.json:1{
2 "hidden_size": 768,
3 "max_length": 128,
4 "lstm_hidden": 256,
5 "lstm_layers": 1,
6 "attn_dim": 64,
7 "output_dim": 2,
8 "visit_time_proj": 8,
9 "architectures": ["LSTMBERT"]
10}config.json produced at training time to ensure architecture compatibility.1import os
2os.environ['CUDA_VISIBLE_DEVICES'] = ""
3# Then initialize pipelinelocal_files_only=True for tokenizer/model loading — all files must be present locallyforward method expects input_ids, attention_mask, and requires visit_times shaped $(V, 2)$SequenceClassifierOutputValueError: visit_times shape must be (V, 2)dates length and case length, or format_dates produced incorrect shapelen(dates) == len(case) and all dates follow the %d%b%Y formatvocab.json, merges.txt or tokenizer.json) are present and compatible with RobertaTokenizerconfig.json doesn't match the saved model weightslocal_model_path or missing model filesconfig.json, pytorch_model.bin, and tokenizer files1def smoke_test(local_model_path):
2 """Basic validation that the model loads and runs"""
3 pipe = PredictionPipeline(local_model_path)
4 case = ['Hello world']
5 dates = ['01Jan2024']
6 p, a = pipe.predict(case, dates)
7
8 # Validate outputs
9 assert 0.0 <= p <= 1.0, "Probability must be between 0 and 1"
10 assert isinstance(a, list), "Attention must be a list"
11 assert len(a) == len(case), "Attention length must match case length"
12 assert abs(sum(a) - 1.0) < 0.01, "Attention weights should sum to ~1.0"
13
14 print("✓ Smoke test passed")
15
16# Run test
17smoke_test('./saved_model')1def integration_test(local_model_path):
2 """Test with realistic clinical scenario"""
3 pipe = PredictionPipeline(local_model_path)
4
5 case = [
6 "Pt reports cough and fever, started 2 days ago.",
7 "Follow-up: symptoms improving after antitussive.",
8 "Resolved, patient discharged."
9 ]
10 dates = ["10Jan2024", "12Jan2024", "15Jan2024"]
11
12 prob, attn = pipe.predict(case=case, dates=dates)
13
14 print(f"Positive probability: {prob:.4f}")
15 print("Attention weights per visit:")
16 for i, (date, weight) in enumerate(zip(dates, attn)):
17 print(f" Visit {i+1} ({date}): {weight:.4f}")
18
19# Run test
20integration_test('./saved_model')