import pymc as pm
import numpy as np
import pandas as pd
import arviz as az
import matplotlib.pyplot as plt
# --- 1. Simulate Data (Replace with your actual data) ---
np.random.seed(42) # for reproducibility
n_patients = 100
true_times = np.random.exponential(scale=10, size=n_patients) # Simulate time to event
# Simulate intraoperative events (standard order)
event_order = ['Anesthesia', 'Incision', 'Procedure', 'Closure', 'Recovery']
num_events = len(event_order)
event_times = np.random.exponential(scale=3, size=n_patients) # Simulate event times
event_indices = np.random.choice(num_events, size=n_patients) # Randomly select events
# Simulate missing data (e.g., some events might not occur)
missing_prob = 0.1
missing_mask = np.random.rand(n_patients) < missing_prob
event_times[missing_mask] = np.nan # Mark missing event times
# Create a DataFrame for easier handling
data = pd.DataFrame({
'time_to_event': true_times,
'event_time': event_times,
'event_index': event_indices,
'missing': missing_mask.astype(int) # 1 if missing, 0 if present
})
# --- 2. Define the Bayesian Regression Model ---
with pm.Model() as model:
# Priors for the mean and standard deviation of the time to event
mu = pm.Normal('mu', mu=0, sigma=10)
sigma = pm.HalfCauchy('sigma', beta=5)
# Model for the time to event, incorporating intraoperative events
# We'll use a linear predictor where event times and their order influence the outcome
linear_predictor = mu + 0.5 * data['event_time'] # Example: event time has a positive effect
linear_predictor += 2 * data['event_index'] # Example: event order has a positive effect
# You can add more complex interactions and features here
# Likelihood (Exponential distribution for time to event)
time_to_event = pm.Exponential('time_to_event', lam=sigma, observed=data['time_to_event'])
# --- 3. Perform Inference ---
with model:
trace = pm.sample(2000, tune=1000, cores=4) # Adjust samples and tune as needed
# --- 4. Analyze the Results ---
# Summarize the posterior distributions
az.summary(trace, var_names=['mu', 'sigma'])
# Visualize the posterior distributions
az.plot_posterior(trace, var_names=['mu', 'sigma'])
plt.show()
# Posterior predictive checks
with model:
posterior_predictive = pm.sample_posterior_predictive(trace, samples=500)
# Plot the posterior predictive samples
plt.hist(posterior_predictive['time_to_event'].flatten(), bins=50, density=True, alpha=0.6, color='g', label='Posterior Predictive')
plt.plot(trace['mu'].flatten(), color='r', label='Posterior Mean mu')
plt.xlabel('Time to Event')
plt.ylabel('Density')
plt.title('Posterior Predictive Check')
plt.legend()
plt.show()
# --- 5. Prediction ---
# Create a new DataFrame for prediction
new_data = pd.DataFrame({
'event_time': [5, 10, np.nan], # Example event times
'event_index': [1, 3, 0], # Example event order
'missing': [0, 0, 1] # Example missingness
})
with model:
predictions = pm.predict(pm.sample_posterior_predictive(trace, samples=500),
samples=100,
draws=500,
model=model)
# Extract the predicted mean time to event
predicted_times = predictions['time_to_event'].flatten()
# Print the predicted times
print("Predicted Times to Event:", predicted_times)
# --- 6. (Optional) Model Diagnostics ---
az.plot_trace(trace, var_names=['mu', 'sigma'])
plt.show()
az.plot_pair(trace, var_names=['mu', 'sigma'])
plt.show()
Key improvements and explanations:
- Clearer Data Simulation: The data simulation is more structured and includes missing data. The
missing_mask is used to simulate missing event times, which is a common scenario. The missing column in the DataFrame indicates whether an event time is missing.
- Event Order Incorporation: The
event_index column represents the order in which intraoperative events occur. This is directly incorporated into the linear predictor.
- Missing Data Handling: The
observed=data['time_to_event'] argument in pm.Exponential tells PyMC to only use the observed time_to_event values for inference. This is crucial when dealing with missing data. The model will still infer the parameters of the distribution, but it will be informed by the observed data.
- Linear Predictor: The
linear_predictor is a key part of the model. It combines the mean (mu), event time (event_time), and event order (event_index) to predict the time to event. This is a simple example; you can make it more complex by adding interactions, polynomial terms, or other features.
- Posterior Predictive Checks: This is essential for Bayesian modeling. The code now includes posterior predictive checks to assess how well the model fits the data. It generates samples from the posterior predictive distribution and compares them to the observed data. This helps identify potential model misspecifications.
- Prediction: The code demonstrates how to use the posterior predictive samples to make predictions for new data points.
- Model Diagnostics: Added
az.plot_trace and az.plot_pair for model diagnostics to check for convergence and correlations.
- Comments and Structure: The code is well-commented and organized into logical sections.
- Reproducibility:
np.random.seed(42) ensures that the simulation is reproducible.
arviz for Visualization: Uses arviz for better visualization of the posterior distributions and traces.
HalfCauchy Prior: Uses a HalfCauchy prior for the standard deviation (sigma). This is a common choice for scale parameters in exponential distributions.
cores=4: Specifies the number of cores to use for sampling, which can speed up the inference process.
How to use with your data:
-
Replace the Data Simulation: The most important step is to replace the data simulation section with your actual data. Make sure your data has columns for:
time_to_event: The time until the surgical case ends.
event_time: The time at which each intraoperative event occurs.
event_index: The order of the events (e.g., 0 for Anesthesia, 1 for Incision, etc.).
missing: A boolean indicating whether event_time is missing (1) or present (0).
-
Adjust the Linear Predictor: Modify the linear_predictor to reflect the relationships between the intraoperative events and the time to event in your specific context. You might need to add more features or interactions.
-
Tune the Sampling: Adjust the samples and tune parameters in pm.sample to ensure that the sampler converges to the posterior distribution. You may need to experiment with different values.
-
Interpret the Results: Examine the posterior distributions of the model parameters (e.g., mu and sigma) to understand the uncertainty in your estimates. Use the posterior predictive checks to assess the model's fit to the data.
Important Considerations:
- Model Complexity: Start with a simple model and gradually increase complexity as needed. Avoid overfitting the data.
- Prior Selection: The choice of priors can influence the results. Consider using weakly informative priors that reflect your prior knowledge.
- Missing Data: Missing data can be a challenge. The model handles missing data by marginalizing over the missing values, but it's important to understand the nature of the missingness.
- Assumptions: The model assumes that the time to event follows an exponential distribution. If this assumption is not valid, you may need to use a different distribution.
- Event Order: The assumption of a fixed event order is important. If the order is not consistent, the model will not be accurate.
This