Balance Calculators

A balance calculator scores how well a population matches a target: the lower the distance, the better the balance. In this notebook we use BetaBalance, the mean absolute standardized mean difference (SMD) across features, to show the main ways of calling distance().

[1]:
from pybalance.utils.balance_calculators import *
from pybalance.utils import MatchingData
from pybalance.sim import load_paper_dataset

We use the dataset from the pybalance paper, which contains a pool population to match from and a target population to match to.

[2]:
m =load_paper_dataset()
m
[2]:
Headers Numeric:
['age', 'height', 'weight']

Headers Categoric:
['gender', 'haircolor', 'country', 'binary_0', 'binary_1', 'binary_2', 'binary_3']

Populations
['pool', 'target']
age height weight gender haircolor country population binary_0 binary_1 binary_2 binary_3 patient_id
0 64.854093 189.466850 88.835049 1.0 1 4 pool 0 1 0 1 135740
1 52.571993 158.134940 94.215107 1.0 1 1 pool 0 1 0 1 49288
2 25.828361 154.692482 94.226222 1.0 0 3 pool 0 0 1 0 256676
3 70.177571 160.536632 94.244356 1.0 0 2 pool 0 0 0 1 338287
4 73.779164 153.551419 86.161814 0.0 0 1 pool 0 0 1 1 72849
... ... ... ... ... ... ... ... ... ... ... ... ...
274995 62.547794 186.005015 50.975051 0.0 0 1 target 0 0 1 1 579081
274996 69.879934 142.371386 100.138389 1.0 1 4 target 0 1 1 0 569939
274997 56.921402 130.639589 108.745182 1.0 1 5 target 0 1 0 0 532419
274998 34.082754 174.764051 67.998396 0.0 2 2 target 0 0 0 1 566266
274999 60.981259 137.419436 89.897817 1.0 0 5 target 1 1 1 1 544231

275000 rows × 12 columns

counts() summarizes the size of each population.

[3]:
m.counts()
[3]:
N
population
pool 250000
target 25000

Create Balance Calculator

A calculator is built from a MatchingData and then used to score any number of populations or subsets.

[4]:
# Constructing a balance calculator fits its preprocessors (e.g. which bins to use
# when binning is involved) to the whole population data. This happens once, so
# all calls to distance() can be compared meaningfully.
beta = BetaBalance(m)
target, pool = split_target_pool(m)

Balance between pool and target

The simplest call scores the whole pool against the target.

[5]:
beta.distance(pool)
[5]:
tensor(0.2353)

The target defaults to the target population of the MatchingData the calculator was built from. It can also be passed explicitly.

[6]:
# Specifying target is optional
beta.distance(pool, target)
[6]:
tensor(0.2353)

Balance between subset of pool and target

We can also score a subset of the pool, e.g. a random sample of 100 patients. This is what a matcher does repeatedly while searching for a good subset.

[7]:
beta.distance(pool.sample(n=100))
[7]:
tensor(0.2396)

Subsets of the target can be scored too.

[8]:
# Can also take subsets of the target
beta.distance(pool.sample(n=100), target.sample(n=100))
[8]:
tensor(0.2224)

Balance between several subsets simultaneously

distance() can score many candidate subsets in a single call and returns one distance per subset, which is much faster than looping. Subsets are given as arrays of row positions in the pool.

[9]:
pool_subsets = np.array([
    np.random.choice(pool.reset_index().index.values, size=100, replace=False),
    np.random.choice(pool.reset_index().index.values, size=100, replace=False)
])
beta.distance(pool_subsets)
[9]:
tensor([0.2453, 0.2153])

The same works for pool and target subsets together: the \(i\)-th pool subset is compared to the \(i\)-th target subset.

[10]:
pool_subsets = [
    np.random.choice(pool.reset_index().index.values, size=100, replace=False),
    np.random.choice(pool.reset_index().index.values, size=100, replace=False)
]
target_subsets = [
    np.random.choice(target.reset_index().index.values, size=100, replace=False),
    np.random.choice(target.reset_index().index.values, size=100, replace=False)
]
beta.distance(pool_subsets, target_subsets)
pybalance/utils/balance_calculators.py:275: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at /Users/runner/work/pytorch/pytorch/torch/csrc/utils/tensor_new.cpp:255.)
  subset_populations = torch.tensor(
[10]:
tensor([0.2153, 0.2442])

The number of pool subsets and target subsets must match, otherwise distance() raises an error.

[11]:
# Must have same number of subsets! This will throw an error:
pool_subsets = [
    np.random.choice(pool.reset_index().index.values, size=100, replace=False),
    np.random.choice(pool.reset_index().index.values, size=100, replace=False)
]
target_subsets = [
    np.random.choice(target.reset_index().index.values, size=100, replace=False),
    np.random.choice(target.reset_index().index.values, size=100, replace=False),
    np.random.choice(target.reset_index().index.values, size=100, replace=False)
]
try:
    beta.distance(pool_subsets, target_subsets)
except ValueError as e:
    print(e)
Number of subset populations must be same for pool and target!

Feature weights

By default every feature contributes equally to the balance. Pass feature_weights to emphasize some features over others. Weights are specified per input feature (e.g. age, country), and each encoded column of that feature (e.g. the one-hot columns of country) inherits its weight. Features that are not listed get a weight of 1, and weights are normalized to sum to 1, so only their relative sizes matter.

[12]:
# Weight age 5x more than every other feature
beta_age = BetaBalance(m, feature_weights={'age': 5})

[13]:
# The same population is scored differently because age now counts for more
print(beta.distance(pool), beta_age.distance(pool))

tensor(0.2353) tensor(0.2606)
[14]:
# Normalized weight on each encoded feature
dict(zip(beta_age.preprocessor.output_headers['all'], beta_age.feature_weights.numpy().round(3)))

[14]:
{'gender_1.0': 0.053,
 'haircolor_1': 0.053,
 'haircolor_2': 0.053,
 'country_1': 0.053,
 'country_2': 0.053,
 'country_3': 0.053,
 'country_4': 0.053,
 'country_5': 0.053,
 'binary_0_1': 0.053,
 'binary_1_1': 0.053,
 'binary_2_1': 0.053,
 'binary_3_1': 0.053,
 'age': 0.263,
 'height': 0.053,
 'weight': 0.053}

Beta vs. gamma

BetaBalance compares populations feature by feature through their means. GammaBalance compares their whole distributions: it bins numeric features and measures the area between the two cumulative distribution functions. Two populations with the same mean but a very different spread look perfectly balanced to beta, but not to gamma.

To see this, we look at age only, by giving every other feature a weight of 0 (see the feature weights section above).

[15]:
age_only = {feature: 0 for feature in m.headers.all}
age_only['age'] = 1

beta_age_only = BetaBalance(m, feature_weights=age_only)
gamma_age_only = GammaBalance(m, feature_weights=age_only)

We compare the full pool, a random sample of the pool, and a deliberately bad subset made of the 1000 pool patients whose age is closest to the target’s mean age.

[16]:
narrow = pool.loc[(pool['age'] - target['age'].mean()).abs().nsmallest(1000).index]
random_sample = pool.sample(n=1000, random_state=0)

The narrow subset has essentially the same mean age as the target, but almost no spread.

[17]:
pd.DataFrame(
    {
        'mean age': [target['age'].mean(), narrow['age'].mean()],
        'std age': [target['age'].std(), narrow['age'].std()],
    },
    index=['target', 'narrow subset'],
)

[17]:
mean age std age
target 48.325155 14.387573
narrow subset 48.323495 0.056093

Beta rates the narrow subset as an almost perfect match, far better than the full pool or a random sample. Gamma sees that the distributions are very different and rates it as the worst of the three.

[18]:
pd.DataFrame(
    {
        'beta': [float(beta_age_only.distance(s)) for s in (pool, random_sample, narrow)],
        'gamma': [float(gamma_age_only.distance(s)) for s in (pool, random_sample, narrow)],
    },
    index=['pool', 'random sample', 'narrow subset'],
)

[18]:
beta gamma
pool 0.355794 0.247645
random sample 0.386569 0.260218
narrow subset 0.000115 0.578250

Which to use depends on the goal: beta is enough when matching means is the criterion, while gamma also protects against matching the mean at the expense of the shape of the distribution.