### Install Bambi from GitHub Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/getting_started.ipynb Install the bleeding-edge version of Bambi directly from its GitHub repository. ```cmd pip install git+https://github.com/bambinos/bambi.git ``` -------------------------------- ### Install Development Environment with Pixi Source: https://github.com/bambinos/bambi/blob/main/CONTRIBUTING.md Install the 'dev' environment using Pixi, which includes all necessary dependencies for development. This should only be done once. ```bash pixi install -e dev ``` -------------------------------- ### Inspect Bambi Model Setup Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/t-test.ipynb Display the Bambi model object to inspect its setup, including the formula and automatically selected prior distributions. ```python model_2 ``` -------------------------------- ### Build Full Documentation Site Source: https://github.com/bambinos/bambi/blob/main/CONTRIBUTING.md Builds the complete documentation site, outputting to 'docs/_site/'. This command renders all example notebooks from scratch. ```bash quartodoc build --config docs/_quarto.yml quarto render docs/ ``` -------------------------------- ### Install Bambi using pip Source: https://github.com/bambinos/bambi/blob/main/README.md Install Bambi from PyPI. For the latest development version, install from GitHub. ```bash pip install bambi ``` ```bash pip install git+https://github.com/bambinos/bambi.git ``` -------------------------------- ### Install Bambi using pip Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/getting_started.ipynb Install the Bambi package using pip. This is the standard method for installing Python packages. ```cmd pip install bambi ``` -------------------------------- ### Quickstart Model Fitting and Visualization Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/getting_started.ipynb Fit a mixed-effects model and visualize the results using ArviZ. Assumes data is loaded into a pandas DataFrame. ```python import bambi as bmb # Assume we already have our data loaded as a pandas DataFrame model = bmb.Model("rt ~ condition + (condition|subject) + (1|stimulus)", data) results = model.fit(draws=5000, chains=2) az.plot_trace(results) az.summary(results) ``` -------------------------------- ### Basic Python Setup for Bambi Source: https://github.com/bambinos/bambi/blob/main/README.md Import necessary libraries for using Bambi, including ArviZ, Bambi, NumPy, and pandas. ```python import arviz as az import bambi as bmb import numpy as np import pandas as pd ``` -------------------------------- ### Import Libraries and Set Up Environment Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/shooter_crossed_random_ANOVA.ipynb Imports necessary libraries for data analysis and visualization, and sets a random seed for reproducibility. This setup is standard for Bayesian modeling workflows. ```python import arviz as az import bambi as bmb import matplotlib.pyplot as plt import numpy as np import pandas as pd az.style.use("arviz-darkgrid") SEED = 1234 ``` -------------------------------- ### OrthogonalPolynomialTransformer Example Call Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/orthogonal_polynomial_reg.ipynb An example demonstrating how to instantiate and use the `OrthogonalPolynomialTransformer` with a degree of 3. The output excludes the constant term. ```python X = np.array([1, 2, 3, 4, 5]) poly3 = OrthogonalPolynomialTransformer(degree=3).fit(X) poly3.transform(X) ``` -------------------------------- ### Example Usage of OrthogonalPolynomialTransformer Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/orthogonal_polynomial_reg.ipynb Demonstrates how to instantiate, fit, and transform data using the OrthogonalPolynomialTransformer. ```APIDOC ## Example ```python X = np.array([1, 2, 3, 4, 5]) poly3 = OrthogonalPolynomialTransformer(degree=3).fit(X) transformed_data = poly3.transform(X) print(transformed_data) ``` ### Result ``` array([[-0.63245553, 0.53452248, -0.31622777], [-0.31622777, -0.26726124, 0.63245553], [ 0. , -0.53452248, -0. ], [ 0.31622777, -0.26726124, -0.63245553], [ 0.63245553, 0.53452248, 0.31622777]]) ``` ``` -------------------------------- ### Inspect Bambi model setup and priors Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/t-test.ipynb Prints the model summary, including the formula, family, link function, number of observations, and prior distributions for parameters. ```python model_1 ``` -------------------------------- ### Set Up Pre-commit Hooks Source: https://github.com/bambinos/bambi/blob/main/CONTRIBUTING.md Configure pre-commit hooks to automatically check code formatting and style before commits. This is part of the development environment setup. ```bash pixi run -e dev pre-commit-setup ``` -------------------------------- ### Load and Import Libraries Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/wald_gamma_glm.ipynb Imports necessary libraries (ArviZ, Bambi, Matplotlib) and sets the ArviZ style for visualizations. This is a common setup for statistical modeling and plotting. ```python import arviz as az import bambi as bmb import matplotlib.pyplot as plt az.style.use("arviz-darkgrid") ``` -------------------------------- ### Import Libraries Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/ESCS_multiple_regression.ipynb Imports necessary libraries for data manipulation, modeling, and plotting. Ensure these are installed before running. ```python import arviz.preview as az import bambi as bmb import matplotlib.pyplot as plt import numpy as np import pandas as pd import statsmodels.api as sm import xarray as xr ``` -------------------------------- ### Load and Display Pandas Version Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/ESCS_multiple_regression.ipynb Loads the pandas library and displays its version. Ensure pandas is installed for data manipulation. ```python import pandas as pd print(f"pandas: {pd.__version__}") ``` -------------------------------- ### Activate Development Shell Source: https://github.com/bambinos/bambi/blob/main/CONTRIBUTING.md Activate the 'dev' Pixi environment to use the installed development tools and dependencies. Use 'exit' to deactivate the shell. ```bash pixi shell -e dev ``` -------------------------------- ### Import Libraries for ArviZ, Bambi, Matplotlib, NumPy, Pandas, SciPy Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/alternative_links_binary.ipynb Imports necessary libraries for data manipulation, statistical modeling, and plotting. Ensure these are installed before running. ```python import arviz as az import bambi as bmb import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy.special import expit as invlogit from scipy.stats import norm az.style.use("arviz-darkgrid") ``` -------------------------------- ### Import Libraries and Set Style Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/sleepstudy.ipynb Imports the required libraries for data analysis and visualization, and sets the ArviZ style for plots. This is a standard setup for analyses using Bambi and ArviZ. ```python import arviz.preview as az import bambi as bmb import matplotlib.pyplot as plt import numpy as np SEED = 1211 az.style.use("arviz-variat") ``` -------------------------------- ### Load Batting Data with Bambi Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/beta_regression.ipynb Loads the 'batting' dataset using Bambi's data loading utility. Ensure Bambi is installed and the dataset is accessible. ```python batting = bmb.load_data("batting") ``` -------------------------------- ### Fit Bambi Model with Default Priors Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/prior_sensitivity.ipynb Fit a Bambi model using default, weakly informative priors. This is a starting point for prior sensitivity analysis when initial priors show conflict. ```python model_bf_01 = bmb.Model(f"siri ~ {' + '.join(covars)}", data=body_fat) dt_bf_01 = model_bf_01.fit(random_seed=SEED) model_bf_01.compute_log_likelihood(dt_bf_01) model_bf_01.compute_log_prior(dt_bf_01) ``` -------------------------------- ### Fit Bambi Model with PyMC Sampler Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/getting_started.ipynb Fit a Bambi model and obtain parameter estimates using the PyMC sampler. The `fit()` method starts sampling immediately. It returns an `InferenceData` instance containing posterior samples. ```python model = bmb.Model("value ~ condition + age + gender + (1|uid)", data, dropna=True) results = model.fit() ``` -------------------------------- ### Import Libraries and Set Up Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/distributional_models.ipynb Imports necessary libraries like ArviZ, Bambi, Matplotlib, NumPy, and Pandas. It also configures warnings and ArviZ's plotting style. ```python import warnings import arviz as az import bambi as bmb import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib.lines import Line2D warnings.simplefilter(action='ignore', category=FutureWarning) # ArviZ az.style.use("arviz-doc") ``` -------------------------------- ### Set ArviZ style Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/getting_started.ipynb Apply a specific visual style for ArviZ plots. Ensure ArviZ is installed. ```python az.style.use("arviz-variat") ``` -------------------------------- ### Clone Repository and Set Up Remotes Source: https://github.com/bambinos/bambi/blob/main/CONTRIBUTING.md Clone your fork of the Bambi repository and add the base repository as an upstream remote for syncing changes. ```bash git clone git@github.com:/bambi.git cd bambi git remote add upstream git@github.com:bambinos/bambi.git ``` -------------------------------- ### Get Logistic Regression Predictions Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/logistic_regression.ipynb Obtain model predictions for binary outcomes. This is a prerequisite for generating separation plots. ```python clinton_model.predict(clinton_fitted, kind="response") ``` -------------------------------- ### Import necessary libraries Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/getting_started.ipynb Import ArviZ, Bambi, and pandas for statistical modeling and data manipulation. ```python import arviz.preview as az import bambi as bmb import pandas as pd ``` -------------------------------- ### Create Matplotlib Figure and Axes Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/hierarchical_binomial_bambi.ipynb Initializes a Matplotlib figure and axes object for plotting. This is a common setup for creating visualizations. ```python #| code-fold: true _, ax = plt.subplots(figsize = (8, 8)) ``` -------------------------------- ### Import Bambi Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/per_parameter_noncentered.ipynb Import the Bambi library to begin modeling. ```python import bambi as bmb ``` -------------------------------- ### Preview General Documentation Content Source: https://github.com/bambinos/bambi/blob/main/CONTRIBUTING.md Previews general documentation content (notebooks, .qmd pages) without API reference changes. Provides live reload for general content. ```bash quartodoc build --config docs/_quarto.yml quarto preview docs/ ``` -------------------------------- ### Preview API Reference Changes Source: https://github.com/bambinos/bambi/blob/main/CONTRIBUTING.md Enables live reload for API reference content changes by watching for modifications in package source and regenerating API .qmd files, then serving the site. ```bash # Terminal 1 — watches for changes in the package source and regenerates API .qmd files quartodoc build --watch --config docs/_quarto.yml # Terminal 2 — serves the site with live reload, picks up the regenerated files quarto preview docs/ ``` -------------------------------- ### PyMC Model Definition Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/multi-level_regression.ipynb Defines a multi-level regression model in PyMC. This setup is suitable for hierarchical data structures where observations are grouped. ```python import pymc as pm import pytensor.tensor as pt with pm.Model() as model: # Hyperpriors for the group-level standard deviations sigma_pig = pm.HalfCauchy("sigma", beta=10, shape=2) # Hyperpriors for the group-level intercepts and slopes intercept_pig = pm.Normal("Intercept", mu=0, sigma=10, shape=2) time_pig = pm.Normal("Time", mu=0, sigma=10, shape=2) # Group-level means for the parameters mu_intercept = pm.Deterministic("mu_Intercept", intercept_pig[0] + time_pig[0] * Time) mu_sigma = pm.Deterministic("mu_sigma", sigma_pig[0]) # Random effects for each pig intercept = pm.Normal("Intercept", mu=mu_intercept, sigma=mu_sigma, shape=N) time = pm.Normal("Time", mu=time_pig[1] + time_pig[0] * Time, sigma=sigma_pig[1], shape=N) # Expected value of outcome mu = pm.Deterministic("mu", intercept + time * Time) # Likelihood (sampling distribution) of the outcome sigma = pm.HalfCauchy("sigma", beta=10) y_hat = pm.Normal("y_hat", mu=mu, sigma=sigma, observed=Weight) # Sample from the posterior distribution idata = pm.sample(1000, tune=1000, chains=4, cores=4, target_accept=0.95) ``` -------------------------------- ### Create and Inspect a Bambi Model Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/getting_started.ipynb Initialize a Bambi model with a formula and data, then inspect its structure and default priors. ```python # Read in a tab-delimited file containing our data data = pd.read_table("data/my_data.txt", sep="\t") # Initialize the model model = bmb.Model("y ~ x + z", data) # Inspect model object model ``` -------------------------------- ### Model Fitting Progress Output Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/survival_continuous_time_notebook.ipynb This output indicates the initialization of the NUTS sampler and the parameters being sampled, showing the progress of the model fitting process. ```text Initializing NUTS using jitter+adapt_diag... Multiprocess sampling (4 chains in 4 jobs) NUTS: [alpha, Intercept, treatment, age] ``` -------------------------------- ### Load and Prepare Fish Dataset Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/zero_inflated_regression.ipynb Loads the fish dataset from a URL and performs initial data cleaning and preparation. This includes selecting relevant columns, converting categorical variables, and removing outliers. ```python fish_data = pd.read_csv("https://stats.idre.ucla.edu/stat/data/fish.csv") cols = ["count", "livebait", "camper", "persons", "child"] fish_data = fish_data[cols] fish_data["livebait"] = pd.Categorical(fish_data["livebait"]) fish_data["camper"] = pd.Categorical(fish_data["camper"]) fish_data = fish_data[fish_data["count"] < 60] # remove outliers ``` -------------------------------- ### Plot Predictions per Group Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/mister_p.ipynb Visualizes predicted outcomes across different groups using Bambi's plot_predictions function. Requires matplotlib for figure setup. ```python mosaic = """ AABB CCCC """ fig = plt.figure(figsize=(20, 7)) axs = fig.subplot_mosaic(mosaic) fig.suptitle("Plot Prediction per Class", fontsize=20) p1 = bmb.interpret.plot_predictions(base_model, result, "eth") p2 = bmb.interpret.plot_predictions(base_model, result, "edu") p3 = bmb.interpret.plot_predictions(base_model, result, "state") p1.on(axs["A"]) p2.on(axs["B"]) p3.on(axs["C"]) p3.plot().show() ``` -------------------------------- ### Initialize and Fit Bambi Model Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/Strack_RRR_re_analysis.ipynb Initializes a Bambi model with a specified formula, dataset, and prior settings. The model is then fitted using MCMC sampling. This snippet demonstrates setting custom priors for group-specific variances. ```python # Initialize the model, passing in the dataset we want to use. model = bmb.Model("value ~ condition + (1|uid)", long, dropna=True) ``` ```python # Set a custom prior on group specific factor variances—just for illustration group_specific_sd = bmb.Prior("HalfNormal", sigma=10) group_specific_prior = bmb.Prior("Normal", mu=0, sigma=group_specific_sd) model.set_priors(group_specific=group_specific_prior) ``` ```python # Fit the model, drawing 1,000 MCMC draws per chain results = model.fit(draws=1000) ``` -------------------------------- ### PyMC Sampling Progress Output Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/count_roaches.ipynb Displays the initialization and progress of the NUTS sampler during PyMC model sampling. ```text Initializing NUTS using jitter+adapt_diag... Multiprocess sampling (4 chains in 4 jobs) NUTS: [Intercept, beta_roach1, beta_treatment, beta_senior] ``` -------------------------------- ### Obtain Model Predictions Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/logistic_regression.ipynb Uses the `Model.predict()` method to get predictions from a fitted Bambi model for new data. By default, it provides a posterior distribution for the mean probability. ```python clinton_model.predict(clinton_fitted, data=new_data) ``` -------------------------------- ### Binomial Model with Logit Link Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/alternative_links_binary.ipynb This code initializes a binomial model using the default logit link. The model is then fitted to the data. ```python model_logit = bmb.Model(formula, data, family="binomial") idata_logit = model_logit.fit(draws=2000) ``` -------------------------------- ### Get Prediction Summary and Draws Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/plot_predictions.ipynb Obtain the computed prediction results directly using the `predictions` function. It returns a summary DataFrame and ArviZ InferenceData with posterior draws. ```python result = bmb.interpret.predictions(model, idata, "hp", target="mpg") result.summary.head(10) ``` -------------------------------- ### Fit a Linear Regression Model in Bambi Source: https://github.com/bambinos/bambi/blob/main/README.md Demonstrates fitting a simple fixed-effects linear regression model. Loads data, initializes the model, prints its description, fits the model, and summarizes/plots the results using ArviZ. ```python # Read in a dataset from the package content data = bmb.load_data("sleepstudy") # See first rows data.head() # Initialize the fixed effects only model model = bmb.Model('Reaction ~ Days', data) # Get model description print(model) # Fit the model using 1000 on each chain results = model.fit(draws=1000) # Key summary and diagnostic info on the model parameters az.summary(results) # Use ArviZ to plot the results az.plot_trace(results) ``` ```text Reaction Days Subject 0 249.5600 0 308 1 258.7047 1 308 2 250.8006 2 308 3 321.4398 3 308 4 356.8519 4 308 ``` ```text Formula: Reaction ~ Days Family: gaussian Link: mu = identity Observations: 180 Priors: target = mu Common-level effects Intercept ~ Normal(mu: 298.5079, sigma: 261.0092) Days ~ Normal(mu: 0.0, sigma: 48.8915) Auxiliary parameters sigma ~ HalfStudentT(nu: 4.0, sigma: 56.1721) ``` ```text mean sd hdi_3% hdi_97% mcse_mean mcse_sd ess_bulk ess_tail r_hat Intercept 251.552 6.658 238.513 263.417 0.083 0.059 6491.0 2933.0 1.0 Days 10.437 1.243 8.179 12.793 0.015 0.011 6674.0 3242.0 1.0 Reaction_sigma 47.949 2.550 43.363 52.704 0.035 0.025 5614.0 2974.0 1.0 ``` -------------------------------- ### Build and Graph Bambi Model Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/getting_started.ipynb Construct a Bambi model with a specified formula, data, and family, then build and visualize the model graph. ```python model = bmb.Model("admit ~ scale(gre) + gpa + rank", data, family=family) model.build() model.graph() ``` -------------------------------- ### Create Patient DataFrame Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/mister_p.ipynb Initializes a pandas DataFrame with patient data including name, risk strata, treatment, and outcome. This setup is crucial for subsequent causal inference analyses. ```python df = pd.DataFrame( { "name": [ "Rheia", "Kronos", "Demeter", "Hades", "Hestia", "Poseidon", "Hera", "Zeus", "Artemis", "Apollo", "Leto", "Ares", "Athena", "Hephaestus", "Aphrodite", "Cyclope", "Persephone", "Hermes", "Hebe", "Dionysus", ], "Risk_Strata": [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], "Treatment": [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1], "Outcome": [0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], } ) df["Treatment_x_Risk_Strata"] = df.Treatment * df.Risk_Strata df ``` -------------------------------- ### Import Libraries for Polynomial Regression Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/polynomial_regression.ipynb Imports necessary libraries including warnings, ArviZ, Bambi, Matplotlib, NumPy, and Pandas. Sets a random seed and applies ArviZ styling. Suppresses warnings for cleaner output. ```python import warnings import arviz as az import bambi as bmb import matplotlib.pyplot as plt import numpy as np import pandas as pd SEED = 1234 az.style.use("arviz-darkgrid") warnings.filterwarnings("ignore") # Temporary fix to make outputs cleaner ``` -------------------------------- ### Reproduce Alligator Dataset Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/categorical_regression.ipynb This code block reproduces the dataset used in the example, including alligator lengths, food choices, and sex. It then converts the 'choice' column to an ordered categorical type. ```python length = [ 1.3, 1.32, 1.32, 1.4, 1.42, 1.42, 1.47, 1.47, 1.5, 1.52, 1.63, 1.65, 1.65, 1.65, 1.65, 1.68, 1.7, 1.73, 1.78, 1.78, 1.8, 1.85, 1.93, 1.93, 1.98, 2.03, 2.03, 2.31, 2.36, 2.46, 3.25, 3.28, 3.33, 3.56, 3.58, 3.66, 3.68, 3.71, 3.89, 1.24, 1.3, 1.45, 1.45, 1.55, 1.6, 1.6, 1.65, 1.78, 1.78, 1.8, 1.88, 2.16, 2.26, 2.31, 2.36, 2.39, 2.41, 2.44, 2.56, 2.67, 2.72, 2.79, 2.84 ] choice = [ "I", "F", "F", "F", "I", "F", "I", "F", "I", "I", "I", "O", "O", "I", "F", "F", "I", "O", "F", "O", "F", "F", "I", "F", "I", "F", "F", "F", "F", "F", "O", "O", "F", "F", "F", "F", "O", "F", "F", "I", "I", "I", "O", "I", "I", "I", "F", "I", "O", "I", "I", "F", "F", "F", "F", "F", "F", "F", "O", "F", "I", "F", "F" ] sex = ["Male"] * 32 + ["Female"] * 31 data = pd.DataFrame({"choice": choice, "length": length, "sex": sex}) data["choice"] = pd.Categorical( data["choice"].map({"I": "Invertebrates", "F": "Fish", "O": "Other"}), ["Other", "Invertebrates", "Fish"], ordered=True ) data.head(3) ``` -------------------------------- ### Get Design Matrix Shape Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/splines_cherry_blossoms.ipynb Retrieve the shape of the model's design matrix. This helps in understanding the number of observations and predictors, including terms like intercepts and basis functions. ```python model.components["mu"].design.common.design_matrix.shape ``` -------------------------------- ### Fit Zero-Inflated Model Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/zero_inflated_regression.ipynb Fit a zero-inflated negative binomial regression model using the `bambi` library. This model is appropriate for count data with excess zeros. Ensure `bambi` is installed and imported. ```python import bambi as bmb model = bmb.Model("like ~ livebait + camper + persons + child", data=df, family="zeroinflated-negbin") results = model.fit() ``` -------------------------------- ### Import Libraries for Negative Binomial Analysis Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/negative_binomial.ipynb Imports necessary libraries including ArviZ, Bambi, Matplotlib, NumPy, Pandas, and SciPy's negative binomial distribution function. It also sets up ArviZ styling and suppresses future warnings. ```python import warnings import arviz as az import bambi as bmb import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy.stats import nbinom az.style.use("arviz-darkgrid") warnings.simplefilter(action='ignore', category=FutureWarning) ``` -------------------------------- ### Summarize Prior Sensitivity Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/prior_sensitivity.ipynb Generate a summary table of prior sensitivity using `az.psense_summary`. This helps identify variables with potential prior-data conflict. ```python az.psense_summary(dt_bf_01, var_names=["~mu"], round_to=2) ``` -------------------------------- ### Define and Fit Weibull AFT Model Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/survival_continuous_time_notebook.ipynb Sets up the formula for a Weibull AFT model and calls the fitting function with retention data. This example demonstrates a typical use case for the `fit_retention_model` function. ```python formula_base = ( "censored(month, censoring) ~ C(gender) + C(level) + C(field) + sentiment + intention" ) idata_weibull, model_weibull = fit_retention_model(retention_df, formula_base, likelihood="weibull") ``` -------------------------------- ### Import necessary libraries for survival analysis Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/survival_continuous_time_notebook.ipynb Imports essential libraries including ArviZ, Bambi, Matplotlib, NumPy, Pandas, PyMC, PyTensor, SciPy, and warnings for setting up survival modeling and analysis. ```python import arviz as az import bambi as bmb import matplotlib.pyplot as plt import numpy as np import pandas as pd import pymc as pm import pytensor import pytensor.tensor as pt from scipy.special import gamma as gamma_func from scipy.stats import weibull_min import warnings warnings.filterwarnings("ignore", category=FutureWarning) ``` -------------------------------- ### Define and Fit Models with Different Parameterizations Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/per_parameter_noncentered.ipynb Define a distributional formula and fit two models: one with both 'mu' and 'sigma' components non-centered, and another with both centered. This setup is used to compare sampler behavior. ```python import arviz as az # Distributional formula: a regression for *both* mu (the response) and sigma. # Each component then has its own group-specific intercept by Subject. dist_formula = bmb.Formula( "Reaction ~ Days + (Days | Subject)", "sigma ~ 1 + (1 | Subject)", ) FIT_KW = dict(chains=4, random_seed=1234, progressbar=False) # Non-centered for both components. m_nc_fit = bmb.Model(dist_formula, data, noncentered={"mu": True, "sigma": True}) idata_nc = m_nc_fit.fit(**FIT_KW) # Centered for both components. m_c_fit = bmb.Model(dist_formula, data, noncentered={"mu": False, "sigma": False}) idata_c = m_c_fit.fit(**FIT_KW) ``` -------------------------------- ### Import Libraries for Beta Regression Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/beta_regression.ipynb Imports necessary libraries including ArviZ, Bambi, Matplotlib, NumPy, Pandas, and SciPy for statistical modeling and plotting. ```python import arviz as az import bambi as bmb import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy import stats from scipy.special import expit az.style.use("arviz-darkgrid") ``` -------------------------------- ### Predicting Expected Outcome in Untreated Group Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/mister_p.ipynb Calculates and prints the mean of the posterior predictive outcomes for the untreated group using a stratified regression model. Requires prior setup of the regression model and data. ```python new_df = df[["Risk_Strata"]].assign(Treatment=0).assign(Treatment_x_Risk_Strata=0) new_preds = reg_strata.predict(results_strata, kind="pps", data=new_df, inplace=False) print("Expected Outcome in the Untreated") new_preds["posterior_predictive"]["Outcome"].mean().item() ``` -------------------------------- ### Define Hierarchical Binomial Model with Bambi Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/hierarchical_binomial_bambi.ipynb Defines a hierarchical binomial model using Bambi with specified priors for the intercept and playerID effects. This setup is useful for modeling binary outcomes with group-level variations. ```python priors = { "Intercept": bmb.Prior("Normal", mu=0, sigma=1), "1|playerID": bmb.Prior("Normal", mu=0, sigma=bmb.Prior("HalfNormal", sigma=1)) } model_hierarchical = bmb.Model("p(H, AB) ~ 1 + (1|playerID)", df, family="binomial", priors=priors) ``` -------------------------------- ### Compare Bayesian Models with ArviZ Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/model_comparison.ipynb Compares Bayesian models using ArviZ's compare function. Pass a dictionary of InferenceData objects to get a comparison dataframe ordered by a chosen criterion (defaulting to LOO). ```python models_dict = { "model1": fitted1, "model2": fitted2, "model3": fitted3 } df_compare = az.compare(models_dict) df_compare ``` -------------------------------- ### Define Partial Pooling Priors Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/radon_example.ipynb Specifies hierarchical priors for a partial pooling model, including priors for the intercept, county-level effects, and the standard deviation of county effects. This setup is used when observations within groups are related. ```python partial_pooling_priors = { "Intercept": bmb.Prior("Normal", mu=0, sigma=10), "1|county": bmb.Prior("Normal", mu=0, sigma=bmb.Prior("Exponential", lam=1)), "sigma": bmb.Prior("Exponential", lam=1), } partial_pooling_model = bmb.Model( formula="log_radon ~ 1 + (1|county)", data=df, priors=partial_pooling_priors, noncentered=False ) partial_pooling_model ``` -------------------------------- ### Prepare for Cubic Orthogonal Polynomials Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/orthogonal_polynomial_reg.ipynb Sets up data for a cubic regression by generating a cubic response variable and applying a third-degree orthogonal polynomial transformation. ```python import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np from sklearn.preprocessing import OrthogonalPolynomialTransformer x3 = x**3 x2 = x**2 # Creating a cubic function with an up and down pattern y_cubic = 2.5* x3 - 15*x2 + 55 * x transformer = OrthogonalPolynomialTransformer(degree=3) x_orthogonalized = transformer.fit_transform(x) x_orth = x_orthogonalized[:, 0] x2_orth = x_orthogonalized[:, 1] x3_orth = x_orthogonalized[:, 2] fig, axs = plt.subplots(2, 3, figsize=(12, 8), sharey='row', layout="constrained") ``` -------------------------------- ### Load Data and Define Negative Binomial Model Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/plot_predictions.ipynb Loads data from a URL, maps categorical variables, and defines a Negative Binomial model with interactions using Bambi. This setup is for analyzing count data with specific predictor relationships. ```python # Load data, define and fit Bambi model data = pd.read_stata("https://stats.idre.ucla.edu/stat/stata/dae/nb_data.dta") data["prog"] = data["prog"].map({1: "General", 2: "Academic", 3: "Vocational"}) model_interaction = bmb.Model( "daysabs ~ 0 + prog + scale(math) + prog:scale(math)", data, family="negativebinomial" ) idata_interaction = model_interaction.fit( draws=1000, target_accept=0.95, random_seed=1234, chains=4 ) ``` -------------------------------- ### Load and Prepare Data Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/plot_slopes.ipynb Load the Wells dataset and perform feature engineering by creating new variables for distance and education, scaled for model fitting. ```python data = pd.read_csv("https://vincentarelbundock.github.io/Rdatasets/csv/carData/Wells.csv") data["switch"] = pd.Categorical(data["switch"]) data["dist100"] = data["distance"] / 100 data["educ4"] = data["education"] / 4 data.head() ``` -------------------------------- ### Constructing a Bernoulli Family Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/getting_started.ipynb Demonstrates how to construct the built-in Bernoulli family dynamically. Requires scipy.special. ```python from scipy import special ``` -------------------------------- ### Define Bambi Multi-level Model Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/multi-level_regression.ipynb Define a multi-level regression model using Bambi's formula syntax, which simplifies model specification by mimicking R's formula interface. This example includes random intercepts and slopes for 'Time' per 'Pig'. ```python df["Time"] = df["Time"].astype(float) bmb_model = bmb.Model("Weight ~ Time + (Time|Pig)", df) bmb_model # Inspect the model ``` -------------------------------- ### Build and Graph Bambi Model Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/how_bambi_works.ipynb Builds the model, which prepares the necessary components for fitting, and then generates a graphical representation of the model structure. This is useful for visualizing the model's components and their relationships. ```python model.build() model.graph() ``` -------------------------------- ### Display package versions and system information Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/alternative_samplers.ipynb Loads the watermark extension and displays information about Python, its version, and key packages like numpy, pandas, and bambi. ```python %load_ext watermark %watermark -n -u -v -iv -w ``` -------------------------------- ### Visualize Model Priors Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/logistic_regression.ipynb Visualize the prior distributions chosen by Bambi for the model parameters. This helps in understanding the default weakly informative priors. ```python clinton_model.plot_priors(); ``` -------------------------------- ### Run Pre-commit Hooks Source: https://github.com/bambinos/bambi/blob/main/CONTRIBUTING.md Executes all pre-commit hooks for the development environment to ensure code style and quality. ```shell pixi run -e dev pre-commit run --all ``` -------------------------------- ### Import Libraries for Bambi and Data Analysis Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/orthogonal_polynomial_reg.ipynb Imports necessary libraries including warnings, ArviZ, Bambi, formulae, Matplotlib, NumPy, Pandas, SciPy, and Seaborn. Sets a random seed and ArviZ style, and filters warnings. ```python import warnings import arviz as az import bambi as bmb import formulae import matplotlib.pyplot as plt import numpy as np import pandas as pd import scipy import seaborn as sns import seaborn.objects as so from typing import Optional SEED = 1234 az.style.use("arviz-darkgrid") warnings.filterwarnings("ignore") # Temporary fix to make outputs cleaner ``` -------------------------------- ### Build and Visualize Model Graph Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/distributional_models.ipynb Build the Bambi model and generate a graphviz graph to visualize its structure. This is useful for understanding the model's components. ```python model_varying.build() model_varying.graph() ``` -------------------------------- ### Display Package Versions and Environment Information Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/mister_p.ipynb Loads the watermark extension and displays Python version, last updated date, and versions of key packages like arviz, bambi, numpy, nutpie, pymc, and pytensor. Useful for reproducibility. ```python %load_ext watermark %watermark -n -u -v -w -p arviz,bambi,numpy,nutpie,pymc,pytensor ``` -------------------------------- ### Run Pylint Source: https://github.com/bambinos/bambi/blob/main/CONTRIBUTING.md Runs Pylint on the Bambi package to check for code quality and style issues. ```shell pixi run -e dev pylint bambi ``` -------------------------------- ### Verify Parameterizations and Compare Diagnostics Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/per_parameter_noncentered.ipynb Check if the correct parameterizations were applied by examining model variables and compare the number of divergences and posterior summaries for population coefficients between the non-centered and centered fits. ```python # Sanity-check that each fit actually picked up the parameterization we asked for. nc_offsets = sorted(v for v in m_nc_fit.backend.model.named_vars if v.endswith("_offset")) c_offsets = sorted(v for v in m_c_fit.backend.model.named_vars if v.endswith("_offset")) print("non-centered offsets:", nc_offsets) print("centered offsets:", c_offsets) div_nc = int(idata_nc.sample_stats["diverging"].sum().item()) div_c = int(idata_c.sample_stats["diverging"].sum().item()) print(f"\ndivergences: non-centered={div_nc}, centered={div_c}") print("\n--- Population coefficients (mu component) ---") print("non-centered:") print(az.summary(idata_nc, var_names=["Intercept", "Days"], kind="stats", round_to=2)) print("\ncentered:") print(az.summary(idata_c, var_names=["Intercept", "Days"], kind="stats", round_to=2)) ``` -------------------------------- ### Define and Build Naive Model Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/fixed_random.ipynb Sets up priors and constructs a naive Bayesian model using Bambi, ignoring group-level confounding. The model is then built and its graph visualized. Requires pandas and Bambi. ```python priors = { "Intercept": bmb.Prior("Normal", mu=0, sigma=1), "x": bmb.Prior("Normal", mu=0, sigma=1), "z": bmb.Prior("Normal", mu=0, sigma=1), } df = pd.DataFrame( { "x": x_obs, "y": y_obs, "z": z_obs[g], # map group-level z to observation level "group": g, # group indicator per observation } ) naive_model = bmb.Model( "y ~ x + z", data=df, family="bernoulli", priors=priors, auto_scale=False, ) naive_model.build() naive_model.graph() ``` -------------------------------- ### Perform Numerical Prior Sensitivity Analysis Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/prior_sensitivity.ipynb Uses ArviZ's `psense_summary` to compute the Cumulative Jensen-Shannon divergence between the prior and posterior for model parameters. This helps identify potential prior-data conflicts. ```python az.psense_summary(dt_bf_00, var_names=["~mu"], round_to=2) ``` -------------------------------- ### Binomial Model with Probit Link Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/alternative_links_binary.ipynb This code initializes a binomial model specifying the probit link function. The model is then fitted to the data. ```python model_probit = bmb.Model(formula, data, family="binomial", link="probit") idata_probit = model_probit.fit(draws=2000) ``` -------------------------------- ### Build the Bambi model Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/t-test.ipynb Builds the Bambi model, automatically selecting prior distributions for the parameters based on the specified formula and data. ```python model_1.build() ``` -------------------------------- ### Prepare Cat Adoption Data Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/survival_model.ipynb Prepares the cat adoption dataset by creating a 'adopt' column to indicate censoring status and encoding 'color' into a numerical 'color_id'. This step is crucial for setting up the survival model. ```python cats = cats_df.copy() cats["adopt"] = np.where(cats["out_event"] == "Adoption", "right", "none") cats["color_id"] = np.where(cats["color"] == "Black", 1, 0) cats = cats[["days_to_event", "adopt", "color_id"]] ``` -------------------------------- ### Load and Prepare Body Fat Data Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/prior_sensitivity.ipynb Loads the body fat dataset from a CSV file and centers the predictor variables. This is a prerequisite for model fitting. ```python body_fat = pd.read_csv("data/body_fat.csv") covars = body_fat.columns.difference(["siri"]) body_fat[covars] = body_fat[covars] - body_fat[covars].mean() ``` -------------------------------- ### Simulate Beta Distribution with Predictor Effect Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/beta_regression.ipynb Simulates data from a Beta distribution where the alpha parameter is influenced by a predictor (e.g., amount of dirt). This demonstrates setting up a Beta regression with predictors. ```python effect_per_micron = 5.0 # Clean Coin alpha = 1_000 beta = 1_000 p = np.random.beta(alpha, beta, size=10_000) # Add two std to tails side (heads more likely) p_heads = np.random.beta(alpha + 50 * effect_per_micron, beta, size=10_000) ``` -------------------------------- ### Model Fitting and Sampling Output Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/survival_continuous_time_notebook.ipynb Displays the output from the MCMC sampling process, including NUTS initialization and sampling progress. This indicates the model is being fitted to the data. ```text Initializing NUTS using jitter+adapt_diag... Multiprocess sampling (4 chains in 4 jobs) NUTS: [alpha1, alpha2, Intercept, age_c, sex, treatment, mu2_Intercept, mu2_age_c, mu2_sex, mu2_treatment] ``` ```text /home/tomas/Desktop/oss/bambinos/bambi/.pixi/envs/dev/lib/python3.13/site-packages/pymc/step_methods/hmc/quadpotential.py:316: RuntimeWarning: overflow encountered in dot return 0.5 * np.dot(x, v_out) ``` ```text Sampling 4 chains for 1_000 tune and 2_000 draw iterations (4_000 + 8_000 draws total) took 7 seconds. ``` ```text Result: Output() ``` -------------------------------- ### Binomial Model with CLogLog Link Source: https://github.com/bambinos/bambi/blob/main/docs/notebooks/alternative_links_binary.ipynb This code initializes a binomial model specifying the complementary log-log (cloglog) link function. The model is then fitted to the data. ```python model_cloglog = bmb.Model(formula, data, family="binomial", link="cloglog") idata_cloglog = model_cloglog.fit(draws=2000) ```