### Example: Initialize SimulationModel Source: https://github.com/square/pysurvival/blob/master/docs/models/simulations.html Basic setup for initializing a simulation model with a Gompertz distribution. ```python import pandas as pd from pysurvival.models.simulations import SimulationModel %pylab inline # Initializing the simulation model sim = SimulationModel( survival_distribution = 'gompertz', risk_type = 'linear', ``` -------------------------------- ### SmoothKaplanMeierModel Example Usage Source: https://github.com/square/pysurvival/blob/master/docs/models/smooth_kaplan_meier.html Example demonstrating how to initialize, fit, and display the SmoothKaplanMeierModel. ```APIDOC ## Example Usage ### Description This example demonstrates how to initialize the `SmoothKaplanMeierModel`, fit it with sample data, and visualize the survival function and its confidence intervals. ### Code ```python # Importing modules import numpy as np from matplotlib import pyplot as plt from pysurvival.models.non_parametric import SmoothKaplanMeierModel from pysurvival.utils.display import display_non_parametric # %matplotlib inline # Uncomment when using Jupyter # Generating random times and event indicators T = np.round(np.abs(np.random.normal(10, 10, 1000)), 1) E = np.random.binomial(1, 0.3, 1000) # Initializing the SmoothKaplanMeierModel skm_model = SmoothKaplanMeierModel(bandwidth=1., kernel='Cosine') # Fitting the model and display the survival function and confidence intervals skm_model.fit(T, E, alpha=0.95) # Displaying the survival function and confidence intervals display_non_parametric(skm_model) # Figure 1 - Representation of the Smooth Kaplan Meier Survival function # ![PySurvival - Smooth Kaplan Meier - Representing the Survival function](images/smooth_kaplan_meier.png "PySurvival - Smooth Kaplan Meier - Representing the Survival function") ``` ``` -------------------------------- ### Importing required packages Source: https://github.com/square/pysurvival/blob/master/docs/models/nonlinear_coxph.html Initial setup for data manipulation, visualization, and model training. ```python import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split from pysurvival.models.simulations import SimulationModel from pysurvival.models.semi_parametric import NonLinearCoxPHModel from pysurvival.utils.metrics import concordance_index from pysurvival.utils.display import integrated_brier_score #%pylab inline ``` -------------------------------- ### Install PySurvival using pip Source: https://github.com/square/pysurvival/blob/master/README.md Use this command to install PySurvival. Ensure you have a working GCC installation. ```bash pip install pysurvival ``` -------------------------------- ### Importing PySurvival and dependencies Source: https://github.com/square/pysurvival/blob/master/docs/models/conditional_survival_forest.html Initial setup for the modeling environment. ```python import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split from pysurvival.models.simulations import SimulationModel from pysurvival.models.survival_forest import ConditionalSurvivalForestModel from pysurvival.utils.metrics import concordance_index from pysurvival.utils.display import integrated_brier_score %pylab inline ``` -------------------------------- ### Install GCC on Ubuntu Source: https://github.com/square/pysurvival/blob/master/docs/installation.html Install GCC version 8 and its C++ counterpart on Ubuntu. Adjust the version number if a newer GCC is available. ```bash sudo apt install gcc-8 g++-8 ``` -------------------------------- ### Importing PySurvival and dependencies Source: https://github.com/square/pysurvival/blob/master/docs/models/random_survival_forest.html Initial setup for the modeling environment, including data manipulation, plotting, and survival analysis utilities. ```python import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split from pysurvival.models.simulations import SimulationModel from pysurvival.models.survival_forest import RandomSurvivalForestModel from pysurvival.utils.metrics import concordance_index from pysurvival.utils.display import integrated_brier_score %pylab inline ``` -------------------------------- ### PySurvival Quick Modeling Example Source: https://github.com/square/pysurvival/blob/master/README.md This example demonstrates building and evaluating both CoxPH and MTLR models using PySurvival. It includes loading data, fitting models, and calculating concordance index. ```python # Loading the modules from pysurvival.models.semi_parametric import CoxPHModel from pysurvival.models.multi_task import LinearMultiTaskModel from pysurvival.datasets import Dataset from pysurvival.utils.metrics import concordance_index # Loading and splitting a simple example into train/test sets X_train, T_train, E_train, X_test, T_test, E_test = \ Dataset('simple_example').load_train_test() # Building a CoxPH model coxph_model = CoxPHModel() coxph_model.fit(X=X_train, T=T_train, E=E_train, init_method='he_uniform', l2_reg = 1e-4, lr = .4, tol = 1e-4) # Building a MTLR model mtlr = LinearMultiTaskModel() mtlr.fit(X=X_train, T=T_train, E=E_train, init_method = 'glorot_uniform', optimizer ='adam', lr = 8e-4) # Checking the model performance c_index1 = concordance_index(model=coxph_model, X=X_test, T=T_test, E=E_test ) print("CoxPH model c-index = {:.2f}".format(c_index1)) c_index2 = concordance_index(model=mtlr, X=X_test, T=T_test, E=E_test ) print("MTLR model c-index = {:.2f}".format(c_index2)) ``` -------------------------------- ### Compare actual and predicted values using compare_to_actual Source: https://github.com/square/pysurvival/blob/master/docs/miscellaneous/tips.html Examples showing how to compare predicted and actual values for loans that were fully repaid versus those that are still active. ```python from pysurvival.utils.display import compare_to_actual results = compare_to_actual(neural_mtlr, X_test, T_test, E_test, is_at_risk = False, figure_size=(16, 6), metrics = ['rmse', 'mean', 'median']) ``` ```python results = compare_to_actual(neural_mtlr, X_test, T_test, E_test, is_at_risk = True, figure_size=(16, 6), metrics = ['rmse', 'mean', 'median']) ``` -------------------------------- ### Example Usage of SmoothKaplanMeierModel Source: https://github.com/square/pysurvival/blob/master/docs/models/smooth_kaplan_meier.html Demonstrates the complete workflow of using the SmoothKaplanMeierModel, including data generation, model initialization, fitting, and displaying the survival function with confidence intervals. ```python # Importing modules import numpy as np from matplotlib import pyplot as plt from pysurvival.models.non_parametric import SmoothKaplanMeierModel from pysurvival.utils.display import display_non_parametric # %matplotlib inline #Uncomment when using Jupyter # Generating random times and event indicators T = np.round(np.abs(np.random.normal(10, 10, 1000)), 1) E = np.random.binomial(1, 0.3, 1000) # Initializing the SmoothKaplanMeierModel skm_model = SmoothKaplanMeierModel(bandwidth=1., kernel='Cosine') # Fitting the model and display the survival function and confidence intervals skm_model.fit(T, E, alpha=0.95) # Displaying the survival function and confidence intervals display_non_parametric(skm_model) ``` -------------------------------- ### Install GCC on MacOS Source: https://github.com/square/pysurvival/blob/master/docs/installation.html Use this command to install the latest version of GCC on MacOS if you have Homebrew installed. ```bash brew install gcc ``` -------------------------------- ### List GCC Files on MacOS Source: https://github.com/square/pysurvival/blob/master/docs/installation.html This command lists all installed GCC files, which is useful for identifying the correct paths for environment variables. ```bash brew ls gcc ``` -------------------------------- ### Get Model Parameters Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Retrieves the estimated parameters of a fitted survival model. These parameters define the shape and scale of the survival distribution. ```python from pysurvival.models.parametric import Weibull from pysurvival.utils.data import simulate_data # Assume weibull_model is already fitted with time, event, X # time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) # weibull_model.fit(time, event, X) # Get the model parameters # params = weibull_model.get_parameters() # print(params) ``` -------------------------------- ### Set C++ Compiler Environment Variables on Ubuntu Source: https://github.com/square/pysurvival/blob/master/docs/installation.html Set the C++ compiler and C compiler paths for Ubuntu. Ensure the version number matches your GCC installation. ```bash export CXX=/usr/bin/g++-8 export CC=/usr/bin/gcc-8 ``` -------------------------------- ### Get Model Parameters for Survival Forest Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Retrieves the parameters of a fitted Survival Forest model. This typically includes information about the trees, such as their structure and split points. ```python from pysurvival.models.non_parametric import SurvivalForest from pysurvival.utils.data import simulate_data # Simulate survival data time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) # Initialize and fit a Survival Forest model survival_forest = SurvivalForest() survival_forest.fit(time, event, X) # Get the model parameters # params = survival_forest.get_params() # print(params) ``` -------------------------------- ### Get Model Summary for CoxPH Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Provides a summary of the fitted CoxPH model, including coefficients, standard errors, p-values, and overall model fit statistics. ```python from pysurvival.models.coxph import CoxPH from pysurvival.utils.data import simulate_data # Assume coxph_model is already fitted with time, event, X # time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) # coxph_model.fit(time, event, X) # Get the model summary # summary = coxph_model.summary() # print(summary) ``` -------------------------------- ### Get Model Summary for Survival Forest Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Provides a summary of the fitted Survival Forest model, which may include information about the number of trees, feature importances, and potentially performance metrics. ```python from pysurvival.models.non_parametric import SurvivalForest from pysurvival.utils.data import simulate_data # Simulate survival data time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) # Initialize and fit a Survival Forest model survival_forest = SurvivalForest() survival_forest.fit(time, event, X) # Get the model summary # summary = survival_forest.summary() # print(summary) ``` -------------------------------- ### Get Model Parameters for CoxPH Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Retrieves the estimated coefficients (log hazard ratios) from a fitted CoxPH model. These coefficients quantify the effect of each covariate on the hazard rate. ```python from pysurvival.models.coxph import CoxPH from pysurvival.utils.data import simulate_data # Assume coxph_model is already fitted with time, event, X # time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) # coxph_model.fit(time, event, X) # Get the model parameters (coefficients) # params = coxph_model.get_params() # print(params) ``` -------------------------------- ### Get Model Summary for DeepSurv Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Provides a summary of the fitted DeepSurv model, typically including information about the training process, loss values, and potentially performance metrics like the C-index. ```python from pysurvival.models.deep_surv import DeepSurv from pysurvival.utils.data import simulate_data # Simulate survival data time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) # Initialize and fit a DeepSurv model deepsurv_model = DeepSurv() deepsurv_model.fit(time, event, X) # Get the model summary # summary = deepsurv_model.summary() # print(summary) ``` -------------------------------- ### Get Survival Times from Survival Forest Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Retrieves the predicted survival times from a fitted Survival Forest model. This provides an estimate of the time until the event occurs for each individual. ```python from pysurvival.models.non_parametric import SurvivalForest from pysurvival.utils.data import simulate_data # Simulate survival data time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) # Initialize and fit a Survival Forest model survival_forest = SurvivalForest() survival_forest.fit(time, event, X) # Predict survival times for new data (e.g., X_new) # survival_times = survival_forest.predict_time(X_new) ``` -------------------------------- ### Get Model Parameters for DeepSurv Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Retrieves the learned parameters (weights and biases) of a fitted DeepSurv model. These parameters define the neural network's structure and learned relationships. ```python from pysurvival.models.deep_surv import DeepSurv from pysurvival.utils.data import simulate_data # Simulate survival data time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) # Initialize and fit a DeepSurv model deepsurv_model = DeepSurv() deepsurv_model.fit(time, event, X) # Get the model parameters (weights and biases) # params = deepsurv_model.get_params() # print(params) ``` -------------------------------- ### Get Model Summary for Parametric Models Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Provides a summary of the fitted parametric survival model, including estimated parameters, standard errors, and convergence information. This helps in assessing model fit and parameter significance. ```python from pysurvival.models.parametric import Weibull from pysurvival.utils.data import simulate_data # Assume weibull_model is already fitted with time, event, X # time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) # weibull_model.fit(time, event, X) # Get the model summary # summary = weibull_model.summary() # print(summary) ``` -------------------------------- ### Get Survival Function for CoxPH with Baseline Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Calculates the survival function for a given set of covariates using the baseline survival function from a fitted CoxPH model. This accounts for the effect of covariates. ```python from pysurvival.models.coxph import CoxPH from pysurvival.utils.data import simulate_data import numpy as np # Assume coxph_model is already fitted with time, event, X # time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) # coxph_model.fit(time, event, X) # Define a specific covariate vector # X_specific = X[0, :] # Get the survival function at specific time points # time_points = np.array([10, 50, 100]) # survival_at_times = coxph_model.get_survival_function(X_specific, time_points) # print(survival_at_times) ``` -------------------------------- ### Get Hazard Function for CoxPH with Baseline Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Calculates the hazard function for a given set of covariates using the baseline hazard function from a fitted CoxPH model. This accounts for the effect of covariates on the instantaneous risk. ```python from pysurvival.models.coxph import CoxPH from pysurvival.utils.data import simulate_data import numpy as np # Assume coxph_model is already fitted with time, event, X # time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) # coxph_model.fit(time, event, X) # Define a specific covariate vector # X_specific = X[0, :] # Get the hazard function at specific time points # time_points = np.array([10, 50, 100]) # hazard_at_times = coxph_model.get_hazard_function(X_specific, time_points) # print(hazard_at_times) ``` -------------------------------- ### Get Survival Function for Multiple Individuals with CoxPH and SurvivalDataFrame Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Calculates survival functions for multiple individuals using a fitted CoxPH model and a SurvivalDataFrame containing their covariate information. This allows for efficient comparison of survival trajectories. ```python from pysurvival.models.coxph import CoxPH from pysurvival.utils.data import SurvivalDataFrame from pysurvival.utils.data import simulate_data # Simulate survival data and create a SurvivalDataFrame time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) survival_df = SurvivalDataFrame(X, time, event) # Assume coxph_model is already fitted with survival_df # coxph_model.fit(survival_df) # Create a SurvivalDataFrame for prediction (features only) # X_new_multi, _, _ = simulate_data(n_samples=5, n_features=5, n_informative=3) # survival_df_new_multi = SurvivalDataFrame(X_new_multi) # Predict survival functions for multiple individuals # survival_probabilities_multi = coxph_model.predict_survival_function(survival_df_new_multi) ``` -------------------------------- ### Get Hazard Function for Multiple Individuals with CoxPH and SurvivalDataFrame Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Calculates hazard functions for multiple individuals using a fitted CoxPH model and a SurvivalDataFrame containing their covariate information. This enables efficient comparison of instantaneous risk profiles. ```python from pysurvival.models.coxph import CoxPH from pysurvival.utils.data import SurvivalDataFrame from pysurvival.utils.data import simulate_data # Simulate survival data and create a SurvivalDataFrame time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) survival_df = SurvivalDataFrame(X, time, event) # Assume coxph_model is already fitted with survival_df # coxph_model.fit(survival_df) # Create a SurvivalDataFrame for prediction (features only) # X_new_multi, _, _ = simulate_data(n_samples=5, n_features=5, n_informative=3) # survival_df_new_multi = SurvivalDataFrame(X_new_multi) # Predict hazard functions for multiple individuals # hazard_rates_multi = coxph_model.predict_hazard(survival_df_new_multi) ``` -------------------------------- ### Get Survival Function for CoxPH with Baseline and SurvivalDataFrame Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Calculates the survival function for a given covariate vector (from a SurvivalDataFrame) using the baseline survival function from a fitted CoxPH model. This accounts for the effect of covariates. ```python from pysurvival.models.coxph import CoxPH from pysurvival.utils.data import SurvivalDataFrame from pysurvival.utils.data import simulate_data import numpy as np # Simulate survival data and create a SurvivalDataFrame time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) survival_df = SurvivalDataFrame(X, time, event) # Assume coxph_model is already fitted with survival_df # coxph_model.fit(survival_df) # Create a SurvivalDataFrame for prediction (features only) # X_specific_df = SurvivalDataFrame(X[0, :].reshape(1, -1)) # Define specific time points for prediction # time_points = np.array([10, 50, 100]) # Get the survival function at specific time points # survival_at_times = coxph_model.get_survival_function(X_specific_df, time_points) # print(survival_at_times) ``` -------------------------------- ### Initialize Application Source: https://github.com/square/pysurvival/blob/master/docs/models/conditional_survival_forest.html Initializes the application with version and base URL information. This is a common pattern for web applications. ```javascript app.initialize({version:"1.0.4",url:{base:".."}}) ``` -------------------------------- ### Get Hazard Function for CoxPH with Baseline and SurvivalDataFrame Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Calculates the hazard function for a given covariate vector (from a SurvivalDataFrame) using the baseline hazard function from a fitted CoxPH model. This accounts for the effect of covariates on the instantaneous risk. ```python from pysurvival.models.coxph import CoxPH from pysurvival.utils.data import SurvivalDataFrame from pysurvival.utils.data import simulate_data import numpy as np # Simulate survival data and create a SurvivalDataFrame time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) survival_df = SurvivalDataFrame(X, time, event) # Assume coxph_model is already fitted with survival_df # coxph_model.fit(survival_df) # Create a SurvivalDataFrame for prediction (features only) # X_specific_df = SurvivalDataFrame(X[0, :].reshape(1, -1)) # Define specific time points for prediction # time_points = np.array([10, 50, 100]) # Get the hazard function at specific time points # hazard_at_times = coxph_model.get_hazard_function(X_specific_df, time_points) # print(hazard_at_times) ``` -------------------------------- ### Install GCC on CentOS7 Source: https://github.com/square/pysurvival/blob/master/docs/installation.html Install GCC version 8 and its C++ counterpart on CentOS 7 using yum. Adjust the version number if a newer GCC is available. ```bash sudo yum install centos-release-scl sudo yum install devtoolset-8-gcc devtoolset-8-gcc-c++ -y ``` -------------------------------- ### Initialize and fit KaplanMeierModel Source: https://github.com/square/pysurvival/blob/master/docs/models/kaplan_meier.html Demonstrates importing the model, generating synthetic data, fitting the model, and displaying the survival function. ```python # Importing modules import numpy as np from matplotlib import pyplot as plt from pysurvival.models.non_parametric import KaplanMeierModel from pysurvival.utils.display import display_non_parametric # %matplotlib inline #Uncomment when using Jupyter # Generating random times and event indicators T = np.round(np.abs(np.random.normal(10, 10, 1000)), 1) E = np.random.binomial(1, 0.3, 1000) # Initializing the KaplanMeierModel km_model = KaplanMeierModel() # Fitting the model km_model.fit(T, E, alpha=0.95) # Displaying the survival function and confidence intervals display_non_parametric(km_model) ``` -------------------------------- ### LinearSVMModel Initialization and Fitting Source: https://github.com/square/pysurvival/blob/master/docs/models/linear_svm.html This snippet shows how to initialize and fit the LinearSVMModel with various parameters. ```APIDOC ## LinearSVMModel Initialization and Fitting ### Description Initializes and fits the LinearSVMModel to the provided survival data. ### Method `fit(X, T, E, init_method='glorot_uniform', lr=1e-4, max_iter=100, l2_reg=1e-4, alpha=0.95, tol=1e-3, verbose=True)` ### Parameters #### Input Data - **X** (array-like) - Input samples (n_samples, n_features). - **T** (array-like) - Target values (event or censoring times). - **E** (array-like) - Event indicators (1 for event, 0 for censoring). #### Model Parameters - **init_method** (str, default='glorot_uniform') - Initialization method for weights. Options include 'glorot_uniform', 'he_uniform', 'uniform', 'glorot_normal', 'he_normal', 'normal', 'ones', 'zeros', 'orthogonal'. - **lr** (float, default=1e-4) - Learning rate for optimization. - **max_iter** (int, default=100) - Maximum number of iterations for the optimization. - **l2_reg** (float, default=1e-4) - L2 regularization parameter. - **alpha** (float, default=0.95) - Confidence level. - **tol** (float, default=1e-3) - Tolerance for stopping criteria. - **verbose** (bool, default=True) - Whether to output detailed logging. #### Optional Parameters - **with_bias** (bool, default=True) - Whether to include a bias term. ### Returns - self : object - The fitted LinearSVMModel instance. ### Request Example ```python from pysurvival.models.svm import LinearSVMModel svm_model = LinearSVMModel() svm_model.fit(X_train, T_train, E_train, init_method='he_uniform', lr=1e-3, max_iter=200) ``` ``` -------------------------------- ### Initialize SmoothKaplanMeierModel Source: https://github.com/square/pysurvival/blob/master/docs/models/smooth_kaplan_meier.html How to instantiate the Smooth Kaplan Meier model class. ```APIDOC ## Instance ### Description To create an instance of the Smooth Kaplan Meier model, use the `pysurvival.models.non_parametric.SmoothKaplanMeierModel` class. ### Usage ```python from pysurvival.models.non_parametric import SmoothKaplanMeierModel model = SmoothKaplanMeierModel() ``` ``` -------------------------------- ### Importing necessary packages Source: https://github.com/square/pysurvival/blob/master/docs/models/coxph.html Import all required libraries for data simulation, modeling, and evaluation. ```python import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split from pysurvival.models.simulations import SimulationModel from pysurvival.models.semi_parametric import CoxPHModel from pysurvival.utils.metrics import concordance_index from pysurvival.utils.display import integrated_brier_score ``` -------------------------------- ### Upgrade GCC on MacOS Source: https://github.com/square/pysurvival/blob/master/docs/installation.html Use this command to upgrade to the latest version of GCC on MacOS if you have already installed it via Homebrew. ```bash brew upgrade gcc ``` -------------------------------- ### Generating simulation dataset Source: https://github.com/square/pysurvival/blob/master/docs/models/nonlinear_coxph.html Initialize a simulation model and generate random samples for training. ```python # Initializing the simulation model sim = SimulationModel( survival_distribution = 'weibull', risk_type = 'gaussian', censored_parameter = 2.1, alpha = 0.1, beta=3.2 ) # Generating N random samples N = 1000 dataset = sim.generate_data(num_samples = N, num_features=3) # Showing a few data-points dataset.head(2) ``` -------------------------------- ### KernelSVMModel Initialization Source: https://github.com/square/pysurvival/blob/master/docs/models/kernel_svm.html Parameters for initializing the KernelSVMModel. ```APIDOC ## KernelSVMModel Parameters ### kernel - **type**: `str` - **default**: "gaussian" - **description**: The type of kernel used to fit the model. Available kernels: Polynomial, Gaussian, Exponential, Tanh, Sigmoid, Rational Quadratic, Inverse Multiquadratic, Multiquadratic. ### scale - **type**: `float` - **default**: 1 - **description**: Scale parameter of the kernel function. ### offset - **type**: `float` - **default**: 0 - **description**: Offset parameter of the kernel function. ### degree - **type**: `float` - **default**: 1 - **description**: Degree parameter of the polynomial/kernel function. ``` -------------------------------- ### Get Baseline Survival Function from CoxPH Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Retrieves the estimated baseline survival function from a fitted CoxPH model. This represents the survival probability when all covariates are zero. ```python from pysurvival.models.coxph import CoxPH from pysurvival.utils.data import simulate_data # Assume coxph_model is already fitted with time, event, X # time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) # coxph_model.fit(time, event, X) # Get the baseline survival function (times and values) # baseline_survival_times, baseline_survival_values = coxph_model.baseline_survival_function # print(baseline_survival_times) # print(baseline_survival_values) ``` -------------------------------- ### Load and Inspect Dataset Source: https://github.com/square/pysurvival/blob/master/notebooks/Churn Prediction - Predicting when your customers will churn.ipynb Imports necessary libraries and loads the churn dataset. Prints the shape of the raw dataset and displays the first two rows. ```python # Importing modules import pandas as pd import numpy as np from matplotlib import pyplot as plt from pysurvival.datasets import Dataset %pylab inline # Reading the dataset raw_dataset = Dataset('churn').load() print("The raw_dataset has the following shape: {}.".format(raw_dataset.shape)) raw_dataset.head(2) ``` -------------------------------- ### Get Baseline Hazard Function from CoxPH Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Retrieves the estimated baseline hazard function from a fitted CoxPH model. This represents the hazard rate when all covariates are zero. ```python from pysurvival.models.coxph import CoxPH from pysurvival.utils.data import simulate_data # Assume coxph_model is already fitted with time, event, X # time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) # coxph_model.fit(time, event, X) # Get the baseline hazard function (times and values) # baseline_hazard_times, baseline_hazard_values = coxph_model.baseline_hazard_function # print(baseline_hazard_times) # print(baseline_hazard_values) ``` -------------------------------- ### Preparing training and testing datasets Source: https://github.com/square/pysurvival/blob/master/docs/models/conditional_survival_forest.html Splitting the generated data into features and target variables for training. ```python # Defining the features features = sim.features # Building training and testing sets # index_train, index_test = train_test_split( range(N), test_size = 0.2) data_train = dataset.loc[index_train].reset_index( drop = True ) data_test = dataset.loc[index_test].reset_index( drop = True ) # Creating the X, T and E input X_train, X_test = data_train[features], data_test[features] T_train, T_test = data_train['time'].values, data_test['time'].values E_train, E_test = data_train['event'].values, data_test['event'].values ``` -------------------------------- ### Initialize SmoothKaplanMeierModel Source: https://github.com/square/pysurvival/blob/master/docs/models/smooth_kaplan_meier.html Initializes the SmoothKaplanMeierModel with specified bandwidth and kernel type. Bandwidth controls smoothing, and kernel defines the smoothing function. ```python SmoothKaplanMeierModel(bandwidth=0.1, kernel='normal') ``` -------------------------------- ### SimulationModel Instance Creation Source: https://github.com/square/pysurvival/blob/master/docs/models/simulations.html How to initialize the SimulationModel class to prepare for generating survival data. ```APIDOC ## SimulationModel Initialization ### Description Creates an instance of the SimulationModel class to generate random survival times. ### Method Constructor ### Endpoint pysurvival.models.simulations.SimulationModel ### Request Example from pysurvival.models.simulations import SimulationModel sim = SimulationModel() ``` -------------------------------- ### Initialize and Fit KernelSVMModel Source: https://github.com/square/pysurvival/blob/master/docs/models/kernel_svm.html Creates an instance of the KernelSVMModel and fits it to the training data using specified hyperparameters. ```python svm_model = KernelSVMModel(kernel='Gaussian', scale=0.25) svm_model.fit(X_train, T_train, E_train, init_method='orthogonal', with_bias = True, lr = 0.8, tol = 1e-3, l2_reg = 1e-4) ``` -------------------------------- ### Set C++ Compiler Environment Variables on CentOS7 Source: https://github.com/square/pysurvival/blob/master/docs/installation.html Set the C++ compiler and C compiler paths for CentOS 7. Ensure the version number matches your GCC installation. ```bash export CXX=/opt/rh/devtoolset-8/root/usr/bin/x86_64-redhat-linux-g++ export CC=/opt/rh/devtoolset-8/root/usr/bin/x86_64-redhat-linux-gcc ``` -------------------------------- ### Import necessary libraries Source: https://github.com/square/pysurvival/blob/master/docs/models/kernel_svm.html Import all required libraries for data simulation, model training, and evaluation. ```python import numpy as np import pandas as pd from matplotlib import pyplot as plt from pysurvival.models.svm import KernelSVMModel from pysurvival.models.simulations import SimulationModel from pysurvival.utils.metrics import concordance_index from sklearn.model_selection import train_test_split from scipy.stats.stats import pearsonr ``` -------------------------------- ### SmoothKaplanMeierModel Initialization Source: https://github.com/square/pysurvival/blob/master/docs/models/smooth_kaplan_meier.html Initializes the SmoothKaplanMeierModel with specified bandwidth and kernel type. ```APIDOC ## SmoothKaplanMeierModel(bandwidth=0.1, kernel='normal') ### Description Initialize the estimator. ### Parameters #### Parameters - **bandwidth** (double) - Optional - controls the degree of the smoothing. The smaller it is the closer to the original KM the function will be, but it will increase the computation time. If it is very large, the resulting model will be smoother than the estimator of KM, but it will stop being as accurate. (default=0.1) - **kernel** (str) - Optional - defines the type of kernel the model will be using. Here are the possible options: - `Uniform`: f(x) = 0 if |x|<1 else f(x) = 0.5 - `Epanechnikov`: f(x) = 0 if |x| \leq 1 else f(x) = 0.75 \cdot (1 - x^2 ) - `Normal`: f(x) = \exp( -x^2/2) / \sqrt{2 \cdot \pi} - `Biweight`: f(x) = 0 if |x| \leq 1 else f(x)=(15/16) \cdot (1-x^2)^2 - `Triweight`: f(x) = 0 if |x| \leq 1 else f(x)=(35/32) \cdot (1-x^2)^3 - `Cosine`: f(x) = 0 if |x| \leq 1 else f(x)=(\pi/4) \cdot \cos( \pi \cdot x/2. ) (default='normal') ``` -------------------------------- ### Load Built-in Datasets Source: https://context7.com/square/pysurvival/llms.txt Use the Dataset class to load tutorial datasets with automatic train/test splitting and feature extraction. Available datasets include 'churn', 'maintenance', 'credit_risk', 'employee_attrition', and 'simple_example'. ```python from pysurvival.datasets import Dataset # Load a dataset - available options: 'simple_example', 'maintenance', # 'credit_risk', 'employee_attrition', 'churn' dataset = Dataset('churn') # Load and automatically split into train/test sets (30% test by default) X_train, T_train, E_train, X_test, T_test, E_test = dataset.load_train_test(test_size=0.3) # Or load the full dataset as a DataFrame data = dataset.load() print(f"Dataset: {dataset.name}") print(f"Time column: {dataset.time_column}") print(f"Event column: {dataset.event_column}") print(f"Features: {dataset.features}") ``` -------------------------------- ### Get Feature Importance for Survival Forest Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Retrieves the feature importance scores from a fitted Survival Forest model. This helps identify which features are most influential in predicting survival outcomes. ```python from pysurvival.models.non_parametric import SurvivalForest from pysurvival.utils.data import simulate_data # Simulate survival data time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) # Initialize and fit a Survival Forest model survival_forest = SurvivalForest() survival_forest.fit(time, event, X) # Get feature importances # feature_importances = survival_forest.feature_importance # print(feature_importances) ``` -------------------------------- ### Split dataset into training and testing sets Source: https://github.com/square/pysurvival/blob/master/docs/models/kernel_svm.html Prepare the dataset for model training by defining features and splitting the data into training and testing subsets. This is a standard practice for model evaluation. ```python # Defining the features features = sim.features ``` -------------------------------- ### NeuralMultiTaskModel Constructor Source: https://github.com/square/pysurvival/blob/master/docs/models/neural_mtlr.html Initializes an instance of the NeuralMultiTaskModel. ```APIDOC ## NeuralMultiTaskModel Constructor ### Description Initializes an instance of the NeuralMultiTaskModel. ### Method `__init__` ### Endpoint `pysurvival.models.multi_task.NeuralMultiTaskModel` ### Parameters #### Request Body - **structure** (list of dictionaries) - Required - Provides the structure of the MLP built within the N-MTLR. Example: `[{'activation': 'ReLU', 'num_units': 128}]`. - **bins** (int) - Optional - Number of subdivisions of the time axis (default=100). - **auto_scaler** (boolean) - Optional - Determines whether a sklearn scaler should be automatically applied (default=True). ``` -------------------------------- ### Load and inspect dataset Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.ipynb Imports necessary libraries and loads the maintenance dataset for initial inspection. ```python # Importing modules import pandas as pd import numpy as np from matplotlib import pyplot as plt %pylab inline # Reading the dataset raw_dataset = Dataset('maintenance').load() print("The raw_dataset has the following shape: {}.".format(raw_dataset.shape)) raw_dataset.head(3) ``` ```python raw_dataset.info() ``` -------------------------------- ### Get Hazard Ratios from CoxPH Model Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Retrieves the hazard ratios from a fitted CoxPH model. Hazard ratios indicate the multiplicative change in the hazard rate for a one-unit increase in a covariate. ```python from pysurvival.models.coxph import CoxPH from pysurvival.utils.data import simulate_data # Assume coxph_model is already fitted with time, event, X # time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) # coxph_model.fit(time, event, X) # Get hazard ratios # hazard_ratios = coxph_model.hazard_ratios # print(hazard_ratios) ``` -------------------------------- ### Importing necessary libraries Source: https://github.com/square/pysurvival/blob/master/docs/models/linear_svm.html Import all required libraries for data manipulation, modeling, and visualization. ```python import numpy as np import pandas as pd from matplotlib import pyplot as plt from pysurvival.models.svm import LinearSVMModel from pysurvival.models.simulations import SimulationModel from pysurvival.utils.metrics import concordance_index from sklearn.model_selection import train_test_split from scipy.stats.stats import pearsonr # %pylab inline # to use in jupyter notebooks ``` -------------------------------- ### Set C++ Compiler Environment Variables on MacOS Source: https://github.com/square/pysurvival/blob/master/docs/installation.html Assign the C++ compiler and C compiler paths to the CC and CXX environment variables. Adjust the version number to match your GCC installation. ```bash export CXX=/usr/local/Cellar/gcc/8.2.0/bin/g++-8 export CC=/usr/local/Cellar/gcc/8.2.0/bin/gcc-8 ``` -------------------------------- ### Initializing and fitting Linear SVM model Source: https://github.com/square/pysurvival/blob/master/docs/models/linear_svm.html Create an instance of LinearSVMModel and fit it to the training data using specified initialization method. ```python svm_model = LinearSVMModel() svm_model.fit(X_train, T_train, E_train, init_method='he_uniform', ``` -------------------------------- ### Initialize NeuralMultiTaskModel Source: https://github.com/square/pysurvival/blob/master/docs/models/neural_mtlr.html Instantiate the NeuralMultiTaskModel with a specified structure for the MLP. The structure defines the layers and activation functions. Optional parameters include the number of time bins and whether to use an auto-scaler. ```python structure = [ {'activation': 'ReLU', 'num_units': 128}, ] model = NeuralMultiTaskModel(structure=structure) ``` -------------------------------- ### Get Baseline Hazard Function from CoxPH with SurvivalDataFrame Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Retrieves the estimated baseline hazard function from a fitted CoxPH model that was trained using a SurvivalDataFrame. This represents the hazard rate when all covariates are zero. ```python from pysurvival.models.coxph import CoxPH from pysurvival.utils.data import SurvivalDataFrame from pysurvival.utils.data import simulate_data # Simulate survival data and create a SurvivalDataFrame time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) survival_df = SurvivalDataFrame(X, time, event) # Assume coxph_model is already fitted with survival_df # coxph_model.fit(survival_df) # Get the baseline hazard function (times and values) # baseline_hazard_times, baseline_hazard_values = coxph_model.baseline_hazard_function # print(baseline_hazard_times) # print(baseline_hazard_values) ``` -------------------------------- ### Get Baseline Survival Function from CoxPH with SurvivalDataFrame Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Retrieves the estimated baseline survival function from a fitted CoxPH model that was trained using a SurvivalDataFrame. This represents the survival probability when all covariates are zero. ```python from pysurvival.models.coxph import CoxPH from pysurvival.utils.data import SurvivalDataFrame from pysurvival.utils.data import simulate_data # Simulate survival data and create a SurvivalDataFrame time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) survival_df = SurvivalDataFrame(X, time, event) # Assume coxph_model is already fitted with survival_df # coxph_model.fit(survival_df) # Get the baseline survival function (times and values) # baseline_survival_times, baseline_survival_values = coxph_model.baseline_survival_function # print(baseline_survival_times) # print(baseline_survival_values) ``` -------------------------------- ### Build and Train CoxPH and MTLR Models Source: https://github.com/square/pysurvival/blob/master/docs/index.html This snippet demonstrates loading data, building a CoxPH model and a LinearMultiTaskModel, training them, and evaluating their performance using concordance index. Ensure necessary modules are imported. ```python # Loading the modules from pysurvival.models.semi_parametric import CoxPHModel from pysurvival.models.multi_task import LinearMultiTaskModel from pysurvival.datasets import Dataset from pysurvival.utils.metrics import concordance_index # Loading and splitting a simple example into train/test sets X_train, T_train, E_train, X_test, T_test, E_test \ = Dataset('simple_example').load_train_test() # Building a CoxPH model coxph_model = CoxPHModel() coxph_model.fit(X=X_train, T=T_train, E=E_train, init_method='he_uniform', l2_reg = 1e-4, lr = .4, tol = 1e-4) # Building a MTLR model mtlr = LinearMultiTaskModel() mtlr.fit(X=X_train, T=T_train, E=E_train, init_method = 'glorot_uniform', optimizer ='adam', lr = 8e-4) # Checking the model performance c_index1 = concordance_index(model=coxph_model, X=X_test, T=T_test, E=E_test ) print("CoxPH model c-index = {:.2f}".format(c_index1)) c_index2 = concordance_index(model=mtlr, X=X_test, T=T_test, E=E_test ) print("MTLR model c-index = {:.2f}".format(c_index2)) ``` -------------------------------- ### Initialize Survival Model with Custom Parameters Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Initializes a survival model with specific parameters, allowing for fine-tuning or setting initial values. ```python from pysurvival.models.parametric import Weibull # Initialize a Weibull model with custom parameters (e.g., shape=1.5, scale=100) # weibull_model = Weibull(alpha=1.5, beta=100.0) ``` -------------------------------- ### Get Feature Importance for CoxPH Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Feature importance for CoxPH models is typically derived from the magnitude and significance of the estimated coefficients. Larger absolute coefficient values suggest a stronger impact on the hazard rate. ```python from pysurvival.models.coxph import CoxPH from pysurvival.utils.data import simulate_data # Assume coxph_model is already fitted with time, event, X # time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) # coxph_model.fit(time, event, X) # Feature importance can be inferred from coxph_model.hazard_ratios # and their associated p-values from coxph_model.summary() # Example: # hazard_ratios = coxph_model.hazard_ratios # print("Hazard Ratios (Feature Importance proxy):") # print(hazard_ratios) ``` -------------------------------- ### Generating simulation data Source: https://github.com/square/pysurvival/blob/master/docs/models/neural_mtlr.html Initializes a simulation model and generates a dataset for training. ```python # Initializing the simulation model sim = SimulationModel( survival_distribution = 'Log-Logistic', risk_type = 'gaussian', censored_parameter = 10.1, alpha = 0.1, beta=3.2 ) # Generating N random samples N = 1000 dataset = sim.generate_data(num_samples = N, num_features = 3) # Showing a few data-points dataset.head(2) ``` -------------------------------- ### Initialize RandomSurvivalForestModel Source: https://github.com/square/pysurvival/blob/master/docs/models/random_survival_forest.html Instantiate the Random Survival Forest model. The `num_trees` parameter controls the number of trees in the forest. ```python RandomSurvivalForestModel(num_trees = 10) ``` -------------------------------- ### Get Feature Importance for DeepSurv Source: https://github.com/square/pysurvival/blob/master/notebooks/Predictive Maintenance - Predicting when a machine will break.html Retrieves feature importance scores from a fitted DeepSurv model. This requires specific methods or analysis of the trained neural network, as it's not a direct output like in tree-based models. ```python from pysurvival.models.deep_surv import DeepSurv from pysurvival.utils.data import simulate_data # Simulate survival data time, event, X = simulate_data(n_samples=100, n_features=5, n_informative=3) # Initialize and fit a DeepSurv model deepsurv_model = DeepSurv() deepsurv_model.fit(time, event, X) # Feature importance calculation for neural networks often requires specific techniques # (e.g., permutation importance, SHAP values) and might not be a direct method. # Example placeholder: # feature_importances = deepsurv_model.calculate_feature_importance(X, y) ``` -------------------------------- ### Prepare Training and Testing Inputs Source: https://github.com/square/pysurvival/blob/master/notebooks/Churn Prediction - Predicting when your customers will churn.ipynb Extracts features, time, and event columns from training and testing datasets. ```python X_train, X_test = data_train[features], data_test[features] T_train, T_test = data_train[time_column], data_test[time_column] E_train, E_test = data_train[event_column], data_test[event_column] ``` -------------------------------- ### Loading a pySurvival Model Source: https://github.com/square/pysurvival/blob/master/docs/miscellaneous/save_load.html Demonstrates how to restore a previously saved model from a .zip file using load_model. ```python # Let's assume we have built and saved a SVM model at the following location # /Users/xxx/Desktop/svm_model_2018_08_26.zip from pysurvival.utils import load_model svm_model = load_model('/Users/xxx/Desktop/svm_model_2018_08_26.zip') ``` -------------------------------- ### Load Employee Attrition Dataset Source: https://github.com/square/pysurvival/blob/master/notebooks/Employee retention - Knowing when your employees will quit.ipynb Imports necessary libraries and loads the employee attrition dataset for analysis. ```python # Importing modules import pandas as pd import numpy as np from matplotlib import pyplot as plt from pysurvival.datasets import Dataset %pylab inline # Reading the dataset raw_dataset = Dataset('employee_attrition').load() print("The raw_dataset has the following shape: {}.".format(raw_dataset.shape)) raw_dataset.head(3) ```