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, collinearity, 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-occurring 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 collinear 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.5–0.4.7)
    • 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_{i,0} (r_{i} \log(r_{i}) - r_{i} + 1).$$

The optimization 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$ 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 externally-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 a 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 defaults to Entropy Balance Weighting; the method="greg" kwarg can be used to use GREG instead.

Passing in optional arguments 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 = aw.weight(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 in "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, each divided by the root mean square of its column of $X$ under the initial weights, 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 practice, 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 options={"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.8.0

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.8.0
File Size Uploaded Provenance Actions
accelerated_weighting-0.8.0.tar.gz 228.4 kB Without provenance Details for accelerated_weighting-0.8.0.tar.gz

Built distribution (wheel)

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

Total release size: 250.7 kB

Release files / accelerated_weighting-0.8.0.tar.gz

Download URL accelerated_weighting-0.8.0.tar.gz
Size 228.4 kB
Tags Source
SHA-256 checksum
How to use checksums
438ef59c510d063ef378c148782936c3a475dea6f76f1d97315654c7f4d22328
BLAKE2b-256 checksum
How to use checksums
4d5f1cbc377045b1590049d85a7c6fe7c6949ab2dc275e4dc453a5e760c0b6d5
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.8.0-py3-none-any.whl

Download URL accelerated_weighting-0.8.0-py3-none-any.whl
Size 22.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3adf9f4df6a0a2409e24a70ba1c0c514b436a25620f472796496a44efbc7642f
BLAKE2b-256 checksum
How to use checksums
2a59ec27672fc3b3164eba5906adcb537e717852802dfd4cc48fdcbafe56a3b2
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.8.0

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