### Install CausalML with Test Dependencies Source: https://causalml.readthedocs.io/en/latest/_sources/installation.rst Installs CausalML along with the necessary dependencies to run the library's tests. This is useful for contributors or for verifying the installation. ```bash pip install -e ".[test]" ``` -------------------------------- ### Install CausalML via uv Source: https://causalml.readthedocs.io/en/latest/_sources/installation.rst Installs the CausalML library using the uv package installer. This command initializes uv and adds the causalml package. ```bash uv init uv add causalml ``` -------------------------------- ### Install CausalML from Source with PyTorch Source: https://causalml.readthedocs.io/en/latest/_sources/installation.rst Installs CausalML from source in editable mode with PyTorch dependencies. This is for developers requiring CEVAE support. ```bash pip install -e ".[torch]" ``` -------------------------------- ### Install CausalML from Source Source: https://causalml.readthedocs.io/en/latest/_sources/installation.rst Clones the CausalML repository and installs the package in editable mode using pip. This method is for developers or those needing the latest code. ```bash git clone https://github.com/uber/causalml.git cd causalml pip install -e . ``` -------------------------------- ### Get CausalML Library Version Source: https://causalml.readthedocs.io/en/latest/examples/causal_trees_with_synthetic_data Retrieves and prints the installed version of the causalml library using `importlib.metadata`. This is useful for verifying the environment setup and ensuring compatibility. ```python import importlib print(importlib.metadata.version('causalml')) ``` -------------------------------- ### Install CausalML with PyTorch (Pip) Source: https://causalml.readthedocs.io/en/latest/_sources/installation.rst Installs CausalML along with PyTorch dependencies, required for models like CEVAE. Uses pip for installation. ```bash pip install causalml[torch] ``` -------------------------------- ### Install CausalML via PyPI Source: https://causalml.readthedocs.io/en/latest/installation Installs the CausalML package from the Python Package Index (PyPI) using pip. This is the standard method for installing Python packages. ```shell pip install causalml ``` -------------------------------- ### Initialize and Add CausalML with uv Source: https://causalml.readthedocs.io/en/latest/installation Initializes a project for the uv package manager and then adds the CausalML package. uv is a fast Python package installer and resolver. ```shell uv init uv add causalml ``` -------------------------------- ### Install CausalML from Source with PyTorch Source: https://causalml.readthedocs.io/en/latest/installation Installs CausalML from source in editable mode, including PyTorch dependencies for models like CEVAE. This command extends the base source installation. ```shell pip install -e ".[torch]" ``` -------------------------------- ### Install CausalML from Source Source: https://causalml.readthedocs.io/en/latest/installation Clones the CausalML repository from GitHub and installs the package in editable mode using pip. This method is suitable for developers who want to contribute to or modify the library. ```shell git clone https://github.com/uber/causalml.git cd causalml pip install -e . ``` -------------------------------- ### Install Miniconda Source: https://causalml.readthedocs.io/en/latest/_sources/installation.rst Steps to download and install Miniconda on Linux for environment management. This is a prerequisite for using conda for CausalML installation. ```bash wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh bash Miniconda3-latest-Linux-x86_64.sh -b source miniconda3/bin/activate conda init source ~/.bashrc ``` -------------------------------- ### Import Libraries and Setup Source: https://causalml.readthedocs.io/en/latest/_sources/examples/meta_learners_with_synthetic_data_multiple_treatment.ipynb Imports necessary libraries for causal inference, machine learning, and data manipulation, and configures logging and plotting. ```python import pandas as pd import numpy as np from matplotlib import pyplot as plt from sklearn.linear_model import LinearRegression, LogisticRegression from sklearn.model_selection import train_test_split import statsmodels.api as sm from xgboost import XGBRegressor, XGBClassifier import warnings # from causalml.inference.meta import XGBTLearner, MLPTLearner from causalml.inference.meta import BaseSRegressor, BaseTRegressor, BaseXRegressor, BaseRRegressor from causalml.inference.meta import BaseSClassifier, BaseTClassifier, BaseXClassifier, BaseRClassifier from causalml.inference.meta import LRSRegressor from causalml.match import NearestNeighborMatch, MatchOptimizer, create_table_one from causalml.propensity import ElasticNetPropensityModel from causalml.dataset import * from causalml.metrics import * warnings.filterwarnings('ignore') plt.style.use('fivethirtyeight') pd.set_option('display.float_format', lambda x: '%.4f' % x) # imports from package import logging from sklearn.dummy import DummyRegressor from sklearn.metrics import mean_squared_error as mse from sklearn.metrics import mean_absolute_error as mae import statsmodels.api as sm from copy import deepcopy logger = logging.getLogger('causalml') logging.basicConfig(level=logging.INFO) %matplotlib inline ``` -------------------------------- ### Install CausalML with PyTorch (uv) Source: https://causalml.readthedocs.io/en/latest/_sources/installation.rst Installs CausalML with PyTorch dependencies using the uv package installer. This is for users who prefer uv and need PyTorch support. ```bash uv add "causalml[torch]" ``` -------------------------------- ### Run CausalML Tests via Make Source: https://causalml.readthedocs.io/en/latest/installation Executes the CausalML test suite using the make build utility. This provides a convenient shortcut for running the predefined test command. ```shell make test ``` -------------------------------- ### Run CausalML Tests via Make Source: https://causalml.readthedocs.io/en/latest/_sources/installation.rst An alternative method to run CausalML tests using the 'make' command, often configured in the project's Makefile. ```bash make test ``` -------------------------------- ### Install CausalML via Pip Source: https://causalml.readthedocs.io/en/latest/_sources/installation.rst Installs the CausalML library using pip, the standard Python package installer. This is a common method for Python projects. ```bash pip install causalml ``` -------------------------------- ### Python CausalML Installation Source: https://causalml.readthedocs.io/en/latest/_sources/examples/dr_learner_with_synthetic_data.ipynb Instructions for installing the CausalML library using pip. This includes the basic installation command and optional dependencies. ```bash pip install causalml ``` ```bash # Install with optional dependencies for specific features pip install causalml[all] ``` -------------------------------- ### Install CausalML with TensorFlow (Pip) Source: https://causalml.readthedocs.io/en/latest/_sources/installation.rst Installs CausalML along with TensorFlow dependencies, required for models like DragonNet. Uses pip for installation. ```bash pip install causalml[tf] ``` -------------------------------- ### Install Graphviz for Source Installation Source: https://causalml.readthedocs.io/en/latest/installation Installs Graphviz, a dependency required for certain CausalML features when building from source. Instructions are provided for conda, Homebrew (macOS), and apt (Linux). ```shell conda install python-graphviz brew install graphviz # MacOS sudo apt-get install graphviz # Linux ``` -------------------------------- ### Install Graphviz for Source Installation Source: https://causalml.readthedocs.io/en/latest/_sources/installation.rst Installs Graphviz, a dependency for certain CausalML features, using different package managers. Choose the command appropriate for your system (conda, brew, or apt). ```bash conda install python-graphviz # Conda brew install graphviz # MacOS sudo apt-get install graphviz # Linux ``` -------------------------------- ### Install Test Dependencies Source: https://causalml.readthedocs.io/en/latest/installation Installs the necessary dependencies for running tests with CausalML, including pytest and coverage tools. This is typically done when developing or verifying the library's functionality. ```shell pip install -e ".[test]" ``` -------------------------------- ### Run CausalML Tests Source: https://causalml.readthedocs.io/en/latest/_sources/installation.rst Executes all tests for the CausalML library using pytest. Includes options to run TensorFlow/PyTorch specific tests and measure code coverage. ```bash pytest -vs tests/ --cov causalml/ --runtf --runtorch ``` -------------------------------- ### Install CausalML from Source with TensorFlow Source: https://causalml.readthedocs.io/en/latest/_sources/installation.rst Installs CausalML from source in editable mode with TensorFlow dependencies. This is for developers requiring DragonNet support. ```bash pip install -e ".[tf]" ``` -------------------------------- ### Install CausalML with PyTorch via PyPI Source: https://causalml.readthedocs.io/en/latest/installation Installs CausalML along with the necessary dependencies for PyTorch support, enabling the use of models like CEVAE. This command uses pip with an extra specifier. ```shell pip install causalml[torch] ``` -------------------------------- ### Install CausalML from Source with TensorFlow Source: https://causalml.readthedocs.io/en/latest/installation Installs CausalML from source in editable mode, including TensorFlow dependencies for models like DragonNet. This command extends the base source installation. ```shell pip install -e ".[tf]" ``` -------------------------------- ### Synthetic Data Generation - Single Simulation Source: https://causalml.readthedocs.io/en/latest/quickstart Provides examples for generating synthetic data for a single simulation using CausalML. It covers data simulation, generating predictions, and visualizing learner performance with scatter and distribution plots. ```python from causalml.dataset import * # Generate synthetic data for single simulation y, X, treatment, tau, b, e = synthetic_data(mode=1) y, X, treatment, tau, b, e = simulate_nuisance_and_easy_treatment() # Generate predictions for single simulation single_sim_preds = get_synthetic_preds(simulate_nuisance_and_easy_treatment, n=1000) # Generate multiple scatter plots to compare learner performance for a single simulation scatter_plot_single_sim(single_sim_preds) # Visualize distribution of learner predictions for a single simulation distr_plot_single_sim(single_sim_preds, kind='kde') ``` -------------------------------- ### Install Miniconda Source: https://causalml.readthedocs.io/en/latest/installation Steps to download and install the latest Miniconda distribution for Linux. This sets up the conda environment manager, which is recommended for managing Python packages and dependencies. ```shell wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh bash Miniconda3-latest-Linux-x86_64.sh -b source miniconda3/bin/activate conda init source ~/.bashrc ``` -------------------------------- ### Jupyter Notebook Setup Source: https://causalml.readthedocs.io/en/latest/examples/binary_policy_learner_example Configures the Jupyter environment to automatically reload modules before executing code. This is useful for iterative development and ensuring the latest code changes are reflected. ```Python %load_ext autoreload %autoreload 2 ``` -------------------------------- ### Install TensorFlow Dependency Source: https://causalml.readthedocs.io/en/latest/examples/dragonnet_example Installs the TensorFlow library, a prerequisite for using DragonNet. This command should be executed in your terminal or command prompt. ```bash pip install tensorflow ``` -------------------------------- ### Install CausalML via Conda Source: https://causalml.readthedocs.io/en/latest/_sources/installation.rst Installs the CausalML library directly from the conda-forge channel. This is a recommended method for users who prefer using conda environments. ```bash conda install -c conda-forge causalml ``` -------------------------------- ### Python Environment Setup and Imports Source: https://causalml.readthedocs.io/en/latest/examples/dragonnet_example Configures the Python environment for CausalML examples. It enables autoreload for code changes and imports essential libraries for data manipulation, machine learning, and causal inference, along with plotting configurations. ```python %load_ext autoreload %autoreload 2 ``` ```python import pandas as pd import numpy as np from matplotlib import pyplot as plt import seaborn as sns from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split, StratifiedKFold from sklearn.linear_model import LogisticRegressionCV, LogisticRegression from xgboost import XGBRegressor from lightgbm import LGBMRegressor from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_error as mse from scipy.stats import entropy import warnings from causalml.inference.meta import LRSRegressor from causalml.inference.meta import XGBTRegressor, MLPTRegressor from causalml.inference.meta import BaseXRegressor, BaseRRegressor, BaseSRegressor, BaseTRegressor from causalml.inference.tf import DragonNet from causalml.match import NearestNeighborMatch, MatchOptimizer, create_table_one from causalml.propensity import ElasticNetPropensityModel from causalml.dataset.regression import * from causalml.metrics import * import os, sys %matplotlib inline warnings.filterwarnings('ignore') plt.style.use('fivethirtyeight') sns.set_palette('Paired') plt.rcParams['figure.figsize'] = (12,8) ``` -------------------------------- ### Install CausalML with TensorFlow via PyPI Source: https://causalml.readthedocs.io/en/latest/installation Installs CausalML along with the necessary dependencies for TensorFlow support, enabling the use of models like DragonNet. This command uses pip with an extra specifier. ```shell pip install causalml[tf] ``` -------------------------------- ### Add CausalML with PyTorch using uv Source: https://causalml.readthedocs.io/en/latest/installation Adds CausalML with PyTorch dependencies to a project managed by uv. This command ensures that both CausalML and PyTorch are installed correctly. ```shell uv add "causalml[torch]" ``` -------------------------------- ### CausalML Setup and Imports Source: https://causalml.readthedocs.io/en/latest/examples/causal_trees_interpretation Initializes the environment for CausalML examples, including autoreload, matplotlib backend, and importing necessary libraries like pandas, numpy, shap, and causalml modules for tree inference and metrics. ```python %reload_ext autoreload %autoreload 2 %matplotlib inline import pandas as pd import numpy as np import multiprocessing as mp np.random.seed(42) from sklearn.model_selection import train_test_split from sklearn.inspection import permutation_importance # Currently causalml shap support is experimental and is available by installing from source # PR: https://github.com/shap/shap/pull/3273 import shap import causalml from causalml.metrics import plot_gain, plot_qini, qini_score from causalml.dataset import synthetic_data from causalml.inference.tree import plot_dist_tree_leaves_values, get_tree_leaves_mask from causalml.inference.tree import CausalRandomForestRegressor, CausalTreeRegressor from causalml.inference.tree.utils import timeit import matplotlib.pyplot as plt import seaborn as sns %config InlineBackend.figure_format = 'retina' ``` -------------------------------- ### Setup Plotting Grid for CATE Comparison Source: https://causalml.readthedocs.io/en/latest/examples/causal_trees_with_synthetic_data Configures a grid of subplots for visualizing the estimated vs. true Individual Treatment Effects (ITE) for multiple models. This involves setting up the figure size and the arrangement of axes. ```Python import matplotlib.pyplot as plt import numpy as np rows = 2 cols = 7 row_idxs = np.arange(rows) col_idxs = np.arange(cols) ax_idxs = np.dstack(np.meshgrid(col_idxs, row_idxs)).reshape(-1, 2) ``` -------------------------------- ### Counterfactual Value Estimator Example Source: https://causalml.readthedocs.io/en/latest/_sources/quickstart.rst Demonstrates the usage of the CounterfactualValueEstimator for predicting the best treatment allocation based on estimated conditional average treatment effects (CATE). It includes setting up the estimator with prediction probabilities, treatment effects, and costs, then predicting the best treatment index and calculating the average value. ```python from causalml.inference.tree import CounterfactualValueEstimator import matplotlib.pyplot as plt # Assuming df_test, conditions, y_proba, tm_pred, conversion_value_array, cc_array, ic_array, test_idx, df, actual_value, random_allocation_value, best_ate_value, tm_value, test_idx are defined elsewhere # run the counterfactual calculation with TwoModel prediction cve = CounterfactualValueEstimator(treatment=df_test['treatment_group_key'], control_name='control', treatment_names=conditions[1:], y_proba=y_proba, cate=tm_pred, value=conversion_value_array[test_idx], conversion_cost=cc_array[test_idx], impression_cost=ic_array[test_idx]) cve_best_idx = cve.predict_best() cve_best = [conditions[idx] for idx in cve_best_idx] actual_is_cve_best = df.loc[test_idx, 'treatment_group_key'] == cve_best cve_value = actual_value.loc[test_idx][actual_is_cve_best].mean() labels = [ 'Random allocation', 'Best treatment', 'T-Learner', 'CounterfactualValueEstimator' ] values = [ random_allocation_value, best_ate_value, tm_value, cve_value ] # plot the result plt.bar(labels, values) plt.show() ``` -------------------------------- ### ATE Estimation using Meta-Learners and Uplift Trees Source: https://causalml.readthedocs.io/en/latest/_sources/quickstart.rst Provides examples for estimating Average Treatment Effect (ATE) using various meta-learners (LRSRegressor, XGBTRegressor, MLPTRegressor, BaseXRegressor, BaseRRegressor) and uplift trees. It includes synthetic data generation and printing estimated ATE values with confidence intervals. ```python from causalml.inference.meta import LRSRegressor from causalml.inference.meta import XGBTRegressor, MLPTRegressor from causalml.inference.meta import BaseXRegressor from causalml.inference.meta import BaseRRegressor from xgboost import XGBRegressor from causalml.dataset import synthetic_data y, X, treatment, _, _, e = synthetic_data(mode=1, n=1000, p=5, sigma=1.0) lr = LRSRegressor() te, lb, ub = lr.estimate_ate(X, treatment, y) print('Average Treatment Effect (Linear Regression): {:.2f} ({:.2f}, {:.2f})'.format(te[0], lb[0], ub[0])) xg = XGBTRegressor(random_state=42) te, lb, ub = xg.estimate_ate(X, treatment, y) print('Average Treatment Effect (XGBoost): {:.2f} ({:.2f}, {:.2f})'.format(te[0], lb[0], ub[0])) nn = MLPTRegressor(hidden_layer_sizes=(10, 10), learning_rate_init=.1, early_stopping=True, random_state=42) te, lb, ub = nn.estimate_ate(X, treatment, y) print('Average Treatment Effect (Neural Network (MLP)): {:.2f} ({:.2f}, {:.2f})'.format(te[0], lb[0], ub[0])) xl = BaseXRegressor(learner=XGBRegressor(random_state=42)) te, lb, ub = xl.estimate_ate(X, treatment, y, e) print('Average Treatment Effect (BaseXRegressor using XGBoost): {:.2f} ({:.2f}, {:.2f})'.format(te[0], lb[0], ub[0])) rl = BaseRRegressor(learner=XGBRegressor(random_state=42)) te, lb, ub = rl.estimate_ate(X=X, p=e, treatment=treatment, y=y) print('Average Treatment Effect (BaseRRegressor using XGBoost): {:.2f} ({:.2f}, {:.2f})'.format(te[0], lb[0], ub[0])) ``` -------------------------------- ### API Documentation Revamp Source: https://causalml.readthedocs.io/en/latest/_sources/changelog.rst The CausalML API documentation has been significantly revamped. It now includes the latest methodology, references, installation guides, notebook examples, and visualizations, providing a more comprehensive resource for users. ```APIDOC API Documentation: URL: https://causalml.readthedocs.io/en/latest/about.html Content: - Latest Methodology - References - Installation Guide - Notebook Examples - Graphs and Visualizations Purpose: To provide a comprehensive and up-to-date guide for using the CausalML library. ``` -------------------------------- ### Sensitivity Analysis with BaseXLearner Source: https://causalml.readthedocs.io/en/latest/quickstart Illustrates how to perform sensitivity analysis using the BaseXLearner class from CausalML. It involves initializing the learner and the Sensitivity class with relevant data and features to generate a summary report. ```python from causalml.metrics.sensitivity import Sensitivity from causalml.metrics.sensitivity import SensitivitySelectionBias from causalml.inference.meta import BaseXLearner from sklearn.linear_model import LinearRegression # Calling the Base XLearner class and return the sensitivity analysis summary report learner_x = BaseXLearner(LinearRegression()) sens_x = Sensitivity(df=df, inference_features=INFERENCE_FEATURES, p_col='pihat', treatment_col=TREATMENT_COL, outcome_col=OUTCOME_COL, learner=learner_x) ``` -------------------------------- ### Initialize CounterfactualValueEstimator for Treatment Optimization Source: https://causalml.readthedocs.io/en/latest/quickstart Shows the initialization of `CounterfactualValueEstimator` for treatment optimization tasks. It includes data splitting and placeholders for model training, referencing external notebooks for full implementation details. ```python from causalml.optimize import CounterfactualValueEstimator from causalml.optimize import get_treatment_costs, get_actual_value # load data set and train test split df_train, df_test = train_test_split(df) train_idx = df_train.index test_idx = df_test.index # some more code here to initiate and train the Model, and produce tm_pred # please refer to the counterfactual_value_optimization notebook for complete example ``` -------------------------------- ### Install CausalML with TensorFlow (uv) Source: https://causalml.readthedocs.io/en/latest/_sources/installation.rst Installs CausalML with TensorFlow dependencies using the uv package installer. This is for users who prefer uv and need TensorFlow support. ```bash uv add "causalml[tf]" ``` -------------------------------- ### Import CausalML and Related Inference Modules Source: https://causalml.readthedocs.io/en/latest/examples/binary_policy_learner_example Imports key components from the CausalML library, including the PolicyLearner for causal inference optimization, and utilities for plotting decision trees. It also imports LightGBM for gradient boosting regression and BaseXRegressor for meta-learner inference. ```Python from causalml.optimize import PolicyLearner from sklearn.tree import plot_tree from lightgbm import LGBMRegressor from causalml.inference.meta import BaseXRegressor ``` -------------------------------- ### CausalML Setup and Imports Source: https://causalml.readthedocs.io/en/latest/examples/cevae_example Imports necessary libraries for causal inference, machine learning, data manipulation, and visualization. Configures logging and plotting styles for the benchmark analysis. ```Python import pandas as pd import numpy as np from matplotlib import pyplot as plt import seaborn as sns import torch from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from xgboost import XGBRegressor from lightgbm import LGBMRegressor from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_error as mse from scipy.stats import entropy import warnings import logging from causalml.inference.meta import BaseXRegressor, BaseRRegressor, BaseSRegressor, BaseTRegressor from causalml.inference.torch import CEVAE from causalml.propensity import ElasticNetPropensityModel from causalml.metrics import * from causalml.dataset import simulate_hidden_confounder %matplotlib inline warnings.filterwarnings('ignore') logger = logging.getLogger('causalml') logger.setLevel(logging.DEBUG) plt.style.use('fivethirtyeight') sns.set_palette('Paired') plt.rcParams['figure.figsize'] = (12,8) ``` -------------------------------- ### Notebook Setup and Imports Source: https://causalml.readthedocs.io/en/latest/examples/sensitivity_example_with_synthetic_data Configures the notebook environment by loading necessary extensions and importing key libraries for data manipulation, plotting, machine learning, and CausalML's inference and dataset modules. ```python %matplotlib inline %load_ext autoreload %autoreload 2 import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression import warnings import matplotlib from causalml.inference.meta import BaseXLearner from causalml.dataset import synthetic_data from causalml.metrics.sensitivity import Sensitivity from causalml.metrics.sensitivity import SensitivityRandomReplace, SensitivitySelectionBias plt.style.use('fivethirtyeight') matplotlib.rcParams['figure.figsize'] = [8, 8] warnings.filterwarnings('ignore') pd.options.display.float_format = '{:.4f}'.format ``` -------------------------------- ### Sensitivity Analysis with Synthetic Data Source: https://causalml.readthedocs.io/en/latest/_sources/quickstart.rst Illustrates how to perform sensitivity analysis using CausalML's `Sensitivity` class with synthetic data. It shows the instantiation of the `Sensitivity` object with a learner and data, followed by running various sensitivity analysis methods like 'Placebo Treatment' and 'Selection Bias'. ```python from causalml.metrics.sensitivity import Sensitivity from causalml.metrics.sensitivity import SensitivitySelectionBias from causalml.inference.meta import BaseXLearner from sklearn.linear_model import LinearRegression # Assuming df, INFERENCE_FEATURES, pihat, TREATMENT_COL, OUTCOME_COL are defined elsewhere # Calling the Base XLearner class and return the sensitivity analysis summary report learner_x = BaseXLearner(LinearRegression()) sens_x = Sensitivity(df=df, inference_features=INFERENCE_FEATURES, p_col='pihat', treatment_col=TREATMENT_COL, outcome_col=OUTCOME_COL, learner=learner_x) # Here for Selection Bias method will use default one-sided confounding function and alpha (quantile range of outcome values) input sens_sumary_x = sens_x.sensitivity_analysis(methods=['Placebo Treatment', 'Random Cause', 'Subset Data', 'Random Replace', 'Selection Bias'], sample_size=0.5) # Selection Bias: Alignment confounding Function ``` -------------------------------- ### Python Environment Setup Source: https://causalml.readthedocs.io/en/latest/_sources/examples/iv_nlsym_synthetic_data.ipynb Configures the Python environment for interactive sessions, enabling automatic reloading of modules and inline plotting for data visualization. ```python %reload_ext autoreload %autoreload 2 %matplotlib inline ``` -------------------------------- ### Install CausalML via Conda Source: https://causalml.readthedocs.io/en/latest/installation Installs the CausalML package directly from the conda-forge channel using the conda package manager. This is a straightforward method for users who prefer conda environments. ```shell conda install -c conda-forge causalml ``` -------------------------------- ### Initialize and Fit PolicyLearner Source: https://causalml.readthedocs.io/en/latest/examples/binary_policy_learner_example Initializes a PolicyLearner with a DecisionTreeClassifier for the policy and sets calibration to True. The learner is then fitted to the generated data (features X, treatment W, and outcome Y). ```python from causalml.inference.meta.policy import PolicyLearner from sklearn.tree import DecisionTreeClassifier policy_learner = PolicyLearner(policy_learner=DecisionTreeClassifier(max_depth=2), calibration=True) policy_learner.fit(X, W, Y) ``` -------------------------------- ### Add CausalML with TensorFlow using uv Source: https://causalml.readthedocs.io/en/latest/installation Adds CausalML with TensorFlow dependencies to a project managed by uv. This command ensures that both CausalML and TensorFlow are installed correctly. ```shell uv add "causalml[tf]" ``` -------------------------------- ### Treatment Optimization with CounterfactualValueEstimator Source: https://causalml.readthedocs.io/en/latest/_sources/quickstart.rst Demonstrates treatment optimization using CounterfactualValueEstimator and related functions. This snippet shows the initialization and data splitting for training a model to optimize treatment assignment. It requires additional steps for model training and prediction. ```python from causalml.optimize import CounterfactualValueEstimator from causalml.optimize import get_treatment_costs, get_actual_value # load data set and train test split df_train, df_test = train_test_split(df) train_idx = df_train.index test_idx = df_test.index # some more code here to initiate and train the Model, and produce tm_pred ``` -------------------------------- ### Check CausalML Version Source: https://causalml.readthedocs.io/en/latest/examples/uplift_trees_with_synthetic_data Retrieves and prints the currently installed version of the causalml library. This is useful for ensuring compatibility and tracking dependencies. ```python import importlib print(importlib.metadata.version('causalml')) ``` -------------------------------- ### Import CausalML and Supporting Libraries Source: https://causalml.readthedocs.io/en/latest/examples/meta_learners_with_synthetic_data_multiple_treatment Imports necessary libraries for causal inference, machine learning, and data manipulation, including pandas, numpy, scikit-learn, xgboost, and causalml components. Sets up logging and plotting styles. ```Python import pandas as pd import numpy as np from matplotlib import pyplot as plt from sklearn.linear_model import LinearRegression, LogisticRegression from sklearn.model_selection import train_test_split import statsmodels.api as sm from xgboost import XGBRegressor, XGBClassifier import warnings # from causalml.inference.meta import XGBTLearner, MLPTLearner from causalml.inference.meta import BaseSRegressor, BaseTRegressor, BaseXRegressor, BaseRRegressor from causalml.inference.meta import BaseSClassifier, BaseTClassifier, BaseXClassifier, BaseRClassifier from causalml.inference.meta import LRSRegressor from causalml.match import NearestNeighborMatch, MatchOptimizer, create_table_one from causalml.propensity import ElasticNetPropensityModel from causalml.dataset import * from causalml.metrics import * warnings.filterwarnings('ignore') plt.style.use('fivethirtyeight') pd.set_option('display.float_format', lambda x: '%.4f' % x) # imports from package import logging from sklearn.dummy import DummyRegressor from sklearn.metrics import mean_squared_error as mse from sklearn.metrics import mean_absolute_error as mae import statsmodels.api as sm from copy import deepcopy logger = logging.getLogger('causalml') logging.basicConfig(level=logging.INFO) %matplotlib inline ``` -------------------------------- ### Import CausalML Inference and Visualization Modules Source: https://causalml.readthedocs.io/en/latest/examples/validation_with_tmle Imports specific modules from the causalml library for meta-learners, TMLE, and visualization utilities. It also prints the installed causalml version. ```python import causalml from causalml.dataset import synthetic_data from causalml.inference.meta import BaseXRegressor, TMLELearner from causalml.metrics.visualize import * import importlib print(importlib.metadata.version('causalml') ) ``` -------------------------------- ### Estimate ATE with CausalML Meta-Learners (LR, XGBoost, MLP, X, R) Source: https://causalml.readthedocs.io/en/latest/quickstart Demonstrates estimating the Average Treatment Effect (ATE) using various meta-learners from `causalml`, including LR, XGBoost, MLP, BaseXRegressor, and BaseRRegressor. It shows initialization and ATE estimation with synthetic data, printing the results. ```python from causalml.inference.meta import LRSRegressor from causalml.inference.meta import XGBTRegressor, MLPTRegressor from causalml.inference.meta import BaseXRegressor from causalml.inference.meta import BaseRRegressor from xgboost import XGBRegressor from causalml.dataset import synthetic_data y, X, treatment, _, _, e = synthetic_data(mode=1, n=1000, p=5, sigma=1.0) lr = LRSRegressor() te, lb, ub = lr.estimate_ate(X, treatment, y) print('Average Treatment Effect (Linear Regression): {:.2f} ({:.2f}, {:.2f})'.format(te[0], lb[0], ub[0])) xg = XGBTRegressor(random_state=42) te, lb, ub = xg.estimate_ate(X, treatment, y) print('Average Treatment Effect (XGBoost): {:.2f} ({:.2f}, {:.2f})'.format(te[0], lb[0], ub[0])) nn = MLPTRegressor(hidden_layer_sizes=(10, 10), learning_rate_init=.1, early_stopping=True, random_state=42) te, lb, ub = nn.estimate_ate(X, treatment, y) print('Average Treatment Effect (Neural Network (MLP)): {:.2f} ({:.2f}, {:.2f})'.format(te[0], lb[0], ub[0])) xl = BaseXRegressor(learner=XGBRegressor(random_state=42)) te, lb, ub = xl.estimate_ate(X, treatment, y, e) print('Average Treatment Effect (BaseXRegressor using XGBoost): {:.2f} ({:.2f}, {:.2f})'.format(te[0], lb[0], ub[0])) rl = BaseRRegressor(learner=XGBRegressor(random_state=42)) te, lb, ub = rl.estimate_ate(X=X, p=e, treatment=treatment, y=y) print('Average Treatment Effect (BaseRRegressor using XGBoost): {:.2f} ({:.2f}, {:.2f})'.format(te[0], lb[0], ub[0])) ``` -------------------------------- ### Run CausalML Tests Source: https://causalml.readthedocs.io/en/latest/installation Executes the test suite for CausalML using pytest. The command runs tests verbosely, calculates code coverage, and can optionally include TensorFlow or PyTorch specific tests. ```shell pytest -vs tests/ --cov causalml/ --runtf --runtorch ``` -------------------------------- ### Configure IPython for Auto-reloading and Matplotlib Source: https://causalml.readthedocs.io/en/latest/examples/validation_with_tmle Configures the IPython environment to automatically reload modules before executing code and to display matplotlib plots inline. This is a common setup for interactive data science work. ```python %reload_ext autoreload %autoreload 2 %matplotlib inline ``` -------------------------------- ### Get Learner Class Mapping Source: https://causalml.readthedocs.io/en/latest/_sources/examples/meta_learners_with_synthetic_data_multiple_treatment.ipynb Retrieves the internal mapping of treatment group names to numerical class labels used by the learner. This is useful for understanding how different treatment groups are represented internally. ```python learner_x._classes ``` -------------------------------- ### Synthetic Data Generation - Single Simulation Source: https://causalml.readthedocs.io/en/latest/_sources/quickstart.rst Provides Python code for generating synthetic data for a single simulation using the `causalml.dataset` module. It includes functions for data generation, obtaining predictions, and visualizing results using scatter and distribution plots. ```python from causalml.dataset import * # Generate synthetic data for single simulation y, X, treatment, tau, b, e = synthetic_data(mode=1) y, X, treatment, tau, b, e = simulate_nuisance_and_easy_treatment() # Generate predictions for single simulation single_sim_preds = get_synthetic_preds(simulate_nuisance_and_easy_treatment, n=1000) # Generate multiple scatter plots to compare learner performance for a single simulation scatter_plot_single_sim(single_sim_preds) # Visualize distribution of learner predictions for a single simulation distr_plot_single_sim(single_sim_preds, kind='kde') ```