Skip to main content

Accelerated Weighting

Author: Carl Sanders

Email: carl.e.sanders@census.gov

This package implements routines for fast, easy, and sparse-data-aware weighting, using either Entropy Balancing Weighting (EBW) or Generalized REGression (GREG) approaches. The goal of this package was to scale weighting algorithms to allow them to work with large, complicated data sets. A particular focus is then on allowing sparse inputs, colinearity, and potential infeasibility without additional front-end data manipulation by the user.

Scaling up weighting problems is largely possible due to the sparsity of naturally-occuring data, e.g. models with group-specific moments. Utilizing sparsity of datasets, models with millions of observations and hundreds of thousands of constraints have successfully converged in minutes. In addition, extensions like bound constraints and handling colinear and inconsistent moments have been added to the standard approach.

Requirements:

  • Linux or Windows only (no MKL support on Mac)
  • Python 3.9+
  • Required packages (tested versions listed, should work on most others):
    • numpy (2.2, 1.26)
    • scipy (1.15.1, 1.13.1)
    • pypardiso (0.4.6)
    • sparse_dot_mkl (0.9.7)
    • numexpr (2.10.2)

Problem and Usage:

The primary function in this package is accelerated_weighting.weight, which takes a set of base weights and gives a new set of weights that match a set of externally-given moments.

The weighting problem solved here considers a set of $N$ sampled units, with initial unit weights $w_0$, an $N\times K$ matrix of observable characteristics at the unit level $X$, and a $K\times 1$ vector of known external unit-level mean "targets" $m$ that the reweighted moments should match. Distance between the new weights and old weights is calculated one of two ways: (a) the Entropy Balance method, using the Kullback-Leibler divergence, or (b) Generalized REGression (GREG), using a squared-loss distance function. For EB (the default case), call the criterion function $\phi$, and the problem can be written in terms of the ratio $r \equiv w_{1}/w_{0}$ between the new weights and the old weights:

$$\phi(r; w_0)=\sum w_{0,i} (\log(r_{i}) - r_{i} + 1).$$

The opimization problem can then be written

$$\min_{r\in \mathbb{R}^N} \phi(r; w_0)$$

$$\text{s.t. } (\text{Diag}({w_{i,0})}X)^T r = m \cdot \sum_{i=1}^N w_{i,0}, \hspace{3pt} r\geq 0.$$

The weight function takes three required keyword arguments: x_sample, the $N\times K$ array dense or sparse matrix (numpy.array or scipy.sparse.csc_array/csr_array) of unit-level observations; weights0, a numpy vector of the initial weights, best scaled to have mean 1; and mean_population_moments, a numpy vector of the exterally-known unit-level mean of each column of $X$. As written above, the algorithm matches the aggregate moments, so keeping the relative scaling of $X$, $m$, and $w_{i,0}$ consistent with the formulation above makes the algorithm more stable, even if not theoretically necessary.

The function returns an WeightingResults object, which has a property WeightingResults.new_weights, the new weights that match the moments (if possible) while being minimum distance from the initial weights.

The algorithm default to Entropy Balance Weighting; the method="greg" kwarg can be used to use GREG instead.

Passing in optional argments to weight can allow for setting bounds in the resulting ratios and dealing with infeasibility of the linear system; see the section "Bounded and Infeasible" below.

weight Example:

>>> import numpy as np
>>> import accelerated_weighting as aw
>>> import scipy.sparse as sp
>>> 
>>> sample_size = 5
>>> x = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]])
>>> mean_population_moments = np.array([.35, .30, .33])
>>> weights0 = np.ones(sample_size)
>>> x.T.dot(weights0) - sample_size * mean_population_moments  # Calculate miss in weighted aggregate moments.
array([-0.75,  0.5 ,  0.35])
>>>
>>> res_ebw = aw.weight(x_sample = x, weights0 = weights0, mean_population_moments = mean_population_moments)
>>> res_ebw.new_weights
array([1.75 , 0.75 , 0.75 , 0.825, 0.825])
>>> x.T.dot(res_ebw.new_weights) - sample_size * mean_population_moments # Aggregate weighted moments now matched exactly.
array([6.72795153e-14, 1.28785871e-14, 4.66293670e-15])
>>>
>>> x_sparse = sp.csr_array(x) # Can use sparse matrices for memory/computation savings
>>> res_sparse_ebw = ebw.entropy_balance(x_sample = x_sparse, weights0 = weights0, mean_population_moments = mean_population_moments)
>>> assert np.allclose(res_ebw.new_weights, res_sparse_ebw.new_weights)

Bounded and Infeasible:

Passing the kwarg options={"bounds": (lbound, ubound)} for scalar lbound and ubound will solve the problem above with $\text{lbound} \leq r_i \leq \text{ubound }\forall i$. For no upper bound, pass None for ubound.

There is a tradeoff between bound constraints and feasibility of the linear system matching the moments. To make bounds generally useful, the bounded weight algorithm runs "elastic mode", a variant problem that has the following properties:

  1. If the bounded problem is feasible, weight(..., options={"bounds": ...}) returns the feasible solution.
  2. If the problem is infeasible, weight returns a point $r^\star$ that is feasible with respect to the bounds. This $r^\star$ minimizes the $L^1$ norm of the moment violations over the other feasible $r$ that satisfy $\phi(r) \leq \phi(r^\star)$; that is, the only way to make the moments match any better would be to increase the criterion. In practce, this matches as many moments exactly as possible, making it possible to identify which moments are impossible to simultaneously match.

The bounded problem is necessarily slower than the unbounded problem, but in theory should converge in every run. After running with bounds, the WeightingResults.constraint_violations property can be used to judge if the original problem was feasible or not. The feasibility of the unconstrained problem can be checked by passing {"bounds": (0, None)}.

Bounds and Elastic Mode Example:

<continued from above>
>>> res_bounded_ebw= aw.weight(x_sample = x, weights0 = weights0, mean_population_moments = mean_population_moments, options={"bounds": (0.5, 1.5)})
>>> res_bounded_ebw.new_weights
array([1.5 , 0.75 , 0.75 , 0.825, 0.825])
>>> res_bounded_ebw.constraint_violations # New bounds make problem infeasible, so return new weights that give "best fit" of moments.
array([-2.50000000e-01, -8.58102478e-11, -5.19522203e-11])

Disclaimers:

This work was performed as part of the National Experimental Wellbeing Statistics project at the U.S. Census Bureau. The views expressed are those of the authors and not those of the U.S. Census Bureau. The U.S. Census Bureau has reviewed this data product to ensure appropriate access, use, and disclosure avoidance protection of the confidential source data used to produce this product (Data Management System (DMS) number: P-6000725; Disclosure Review Board (DRB) approval number: CBDRB-FY25-SEHSD003-037).

Metadata

Release files for accelerated-weighting 0.7.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for accelerated-weighting 0.7.1
File Size Uploaded Provenance Actions
accelerated_weighting-0.7.1.tar.gz 103.1 kB Without provenance Details for accelerated_weighting-0.7.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for accelerated-weighting 0.7.1
File Interpreter ABI Platform Actions
accelerated_weighting-0.7.1-py3-none-any.whl Python 3 none any Details for accelerated_weighting-0.7.1-py3-none-any.whl

Total release size: 123.4 kB

Release files / accelerated_weighting-0.7.1.tar.gz

Download URL accelerated_weighting-0.7.1.tar.gz
Size 103.1 kB
Tags Source
SHA-256 checksum
How to use checksums
17648762bda65790d91d17b5ad107eba80088ced8d30d6274eb7252701b3e7e3
BLAKE2b-256 checksum
How to use checksums
be5308af26a59aed637ecb1a253221fa07b031f48dc52c7e1d99e33976c89d79
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.2

Release files / accelerated_weighting-0.7.1-py3-none-any.whl

Download URL accelerated_weighting-0.7.1-py3-none-any.whl
Size 20.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2af1f471938dbb4313ad0d218be0d57d6e2aead85bd1c634e20d05535e20bdf2
BLAKE2b-256 checksum
How to use checksums
0cdbd05d3575b54af6c573dd9351467939dccce66b627dc403a97bef3d9aa6cc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.2

Security for accelerated-weighting 0.7.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page