balance Quickstart: Analyzing and adjusting the bias on a simulated toy dataset¶
'balance' is a Python package that is maintained and released by the Core Data Science Tel-Aviv team in Meta. 'balance' performs and evaluates bias reduction by weighting for a broad set of experimental and observational use cases.
Although balance is written in Python, you don't need a deep Python understanding to use it. In fact, you can just use this notebook, load your data, change some variables and re-run the notebook and produce your own weights!
This quickstart demonstrates re-weighting specific simulated data, but if you have a different usecase or want more comprehensive documentation, you can check out the comprehensive balance tutorial.
Analysis¶
There are four main steps to analysis with balance:
- load data
- check diagnostics before adjustment
- perform adjustment + check diagnostics
- output results
Let's dive right in!
Example dataset¶
The following is a toy simulated dataset.
import warnings
warnings.filterwarnings("ignore")
from balance import load_data
INFO (2025-01-07 10:14:49,345) [__init__/<module> (line 54)]: Using balance version 0.10.0
target_df, sample_df = load_data()
print("target_df: \n", target_df.head())
print("sample_df: \n", sample_df.head())
target_df: id gender age_group income happiness 0 100000 Male 45+ 10.183951 61.706333 1 100001 Male 45+ 6.036858 79.123670 2 100002 Male 35-44 5.226629 44.206949 3 100003 NaN 45+ 5.752147 83.985716 4 100004 NaN 25-34 4.837484 49.339713 sample_df: id gender age_group income happiness 0 0 Male 25-34 6.428659 26.043029 1 1 Female 18-24 9.940280 66.885485 2 2 Male 18-24 2.673623 37.091922 3 3 NaN 18-24 10.550308 49.394050 4 4 NaN 18-24 2.689994 72.304208
target_df.head().round(2).to_dict()
# sample_df.shape
{'id': {0: '100000', 1: '100001', 2: '100002', 3: '100003', 4: '100004'}, 'gender': {0: 'Male', 1: 'Male', 2: 'Male', 3: nan, 4: nan}, 'age_group': {0: '45+', 1: '45+', 2: '35-44', 3: '45+', 4: '25-34'}, 'income': {0: 10.18, 1: 6.04, 2: 5.23, 3: 5.75, 4: 4.84}, 'happiness': {0: 61.71, 1: 79.12, 2: 44.21, 3: 83.99, 4: 49.34}}
In practice, one can use pandas loading function(such as read_csv()
) to import data into the DataFrame objects sample_df
and target_df
.
Load data into a Sample object¶
The first thing to do is to import the Sample
class from balance. All of the data we're going to be working with, sample or population, will be stored in objects of the Sample
class.
from balance import Sample
Using the Sample class, we can fill it with a "sample" we want to adjust, and also a "target" we want to adjust towards.
We turn the two input pandas DataFrame objects we created (or loaded) into a balance.Sample objects, by using the .from_frame()
sample = Sample.from_frame(sample_df, outcome_columns=["happiness"])
# Often times we don'y have the outcome for the target. In this case we've added it just to validate later that the weights indeed help us reduce the bias
target = Sample.from_frame(target_df, outcome_columns=["happiness"])
WARNING (2025-01-07 10:14:49,597) [util/guess_id_column (line 113)]: Guessed id column name id for the data
WARNING (2025-01-07 10:14:49,606) [sample_class/from_frame (line 261)]: No weights passed. Adding a 'weight' column and setting all values to 1
WARNING (2025-01-07 10:14:49,616) [util/guess_id_column (line 113)]: Guessed id column name id for the data
WARNING (2025-01-07 10:14:49,630) [sample_class/from_frame (line 261)]: No weights passed. Adding a 'weight' column and setting all values to 1
If we use the .df
property call, we can see the DataFrame stored in sample. We can see how we have a new weight column that was added (it will all have 1s) in the importing of the DataFrames into a balance.Sample
object.
sample.df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 1000 entries, 0 to 999 Data columns (total 6 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 1000 non-null object 1 gender 912 non-null object 2 age_group 1000 non-null object 3 income 1000 non-null float64 4 happiness 1000 non-null float64 5 weight 1000 non-null int64 dtypes: float64(2), int64(1), object(3) memory usage: 47.0+ KB
We can get a quick overview text of each Sample object, but just calling it.
Let's take a look at what this produces:
sample
(balance.sample_class.Sample) balance Sample object 1000 observations x 3 variables: gender,age_group,income id_column: id, weight_column: weight, outcome_columns: happiness
target
(balance.sample_class.Sample) balance Sample object 10000 observations x 3 variables: gender,age_group,income id_column: id, weight_column: weight, outcome_columns: happiness
Next, we combine the sample object with the target object. This is what will allow us to adjust the sample to the target.
sample_with_target = sample.set_target(target)
Looking on sample_with_target
now, it has the target atteched:
sample_with_target
(balance.sample_class.Sample) balance Sample object with target set 1000 observations x 3 variables: gender,age_group,income id_column: id, weight_column: weight, outcome_columns: happiness target: balance Sample object 10000 observations x 3 variables: gender,age_group,income id_column: id, weight_column: weight, outcome_columns: happiness 3 common variables: gender,age_group,income
Pre-Adjustment Diagnostics¶
We can use .covars()
and then followup with .mean()
and .plot()
(barplots and kde density plots) to get some basic diagnostics on what we got.
We can see how:
- The proportion of missing values in gender is similar in sample and target.
- We have younger people in the sample as compared to the target.
- We have more females than males in the sample, as compared to around 50-50 split for the (non NA) target.
- Income is more right skewed in the target as compared to the sample.
print(sample_with_target.covars().mean().T)
source self target _is_na_gender[T.True] 0.088000 0.089800 age_group[T.25-34] 0.300000 0.297400 age_group[T.35-44] 0.156000 0.299200 age_group[T.45+] 0.053000 0.206300 gender[Female] 0.268000 0.455100 gender[Male] 0.644000 0.455100 gender[_NA] 0.088000 0.089800 income 6.297302 12.737608
print(sample_with_target.covars().asmd().T)
source self age_group[T.25-34] 0.005688 age_group[T.35-44] 0.312711 age_group[T.45+] 0.378828 gender[Female] 0.375699 gender[Male] 0.379314 gender[_NA] 0.006296 income 0.494217 mean(asmd) 0.326799
print(sample_with_target.covars().asmd(aggregate_by_main_covar = True).T)
source self age_group 0.232409 gender 0.253769 income 0.494217 mean(asmd) 0.326799
sample_with_target.covars().plot()