Metadata-Version: 2.5
Name: gapnet
Version: 0.1.1
Summary: An interpretable neural network that finds how feature effects differ between groups (Keras 3: TensorFlow, PyTorch or JAX).
Project-URL: Homepage, https://github.com/AnmolAdhikari/gapnet
Project-URL: Issues, https://github.com/AnmolAdhikari/gapnet/issues
Project-URL: Changelog, https://github.com/AnmolAdhikari/gapnet/blob/main/CHANGELOG.md
Author-email: Anmol Adhikari <anmoladhikari03@gmail.com>
License-Expression: MIT
License-File: LICENSE
Keywords: education,explainable-ai,fairness,heterogeneous-effects,inequality,interpretable-machine-learning,jax,keras,neural-additive-models,neural-network,pandas,pytorch,tensorflow,xai
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: keras>=3.4
Requires-Dist: numpy>=2.0
Requires-Dist: pandas>=2.2
Provides-Extra: dev
Requires-Dist: build; extra == 'dev'
Requires-Dist: matplotlib>=3.7; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: ruff; extra == 'dev'
Requires-Dist: twine; extra == 'dev'
Provides-Extra: jax
Requires-Dist: jax>=0.4.20; extra == 'jax'
Provides-Extra: plot
Requires-Dist: matplotlib>=3.7; extra == 'plot'
Provides-Extra: tensorflow
Requires-Dist: tensorflow>=2.16; extra == 'tensorflow'
Provides-Extra: torch
Requires-Dist: torch>=2.1; extra == 'torch'
Description-Content-Type: text/markdown

# gapnet

[![PyPI](https://img.shields.io/pypi/v/gapnet.svg)](https://pypi.org/project/gapnet/)
[![CI](https://github.com/AnmolAdhikari/gapnet/actions/workflows/ci.yml/badge.svg)](https://github.com/AnmolAdhikari/gapnet/actions/workflows/ci.yml)
[![Python](https://img.shields.io/pypi/pyversions/gapnet.svg)](https://pypi.org/project/gapnet/)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

**An interpretable neural network that tells you whether something affects one group more than another, and by how much.**

A normal neural network can predict who will fail an exam, but it can't tell you *why*, let alone
whether the reasons are different in different places. `gapnet` is built to answer exactly that:

> *"Low income hurts pass rates everywhere, but 1.6x more in Mountain districts. Distance to school
> matters in the Hills and hardly at all in the Valley. Parents' education matters the same everywhere."*

It is as accurate as a black-box network, every effect can be read and plotted directly (no SHAP
guesswork), and every gap comes with a confidence interval and a significance test. It is built on
**Keras 3**, so the same code runs on **TensorFlow, PyTorch or JAX**.

```bash
pip install "gapnet[jax,plot]"          # or gapnet[tensorflow] / gapnet[torch]
```

## Quick start

```python
from gapnet import GapNet, make_example

df = make_example()                      # simulated school data with known gaps
model = GapNet(group="region").fit(df, target="passed")
print(model.summary())
```

Real output:

```text
GapNet: 4 features x 4 groups of 'region' (binary, 10-model ensemble, effects in log-odds)
[GAP] baseline: otherwise identical people in 'Mountain' score lower (gap -0.85, 95% CI -1.08 to -0.62)
[GAP] distance_km: effect is 2.2x stronger in 'Hill' (-0.72 vs -0.33 overall; gap -0.39, 95% CI -0.57 to -0.21)
[GAP] income: effect is 1.6x stronger in 'Mountain' (+1.28 vs +0.78 overall; gap +0.49, 95% CI +0.24 to +0.75)
[GAP] distance_km: effect is weak or absent in 'Valley' (+0.16 vs -0.33 overall; gap +0.49, 95% CI +0.24 to +0.75)
[GAP] baseline: otherwise identical people in 'Hill' score higher (gap +0.17, 95% CI +0.08 to +0.27)
[SAME] no evidence of a gap for: parent_edu, female
```

The data was simulated so that the truth is known: income matters twice as much in Mountain,
distance matters only in Mountain and Hill, parents' education is the same everywhere and gender has
no effect. `gapnet` found these gaps from the data alone and reported no false ones.

```python
model.plot("income")         # one curve per group, with 90% bands
model.gaps()                 # table: effect, overall, gap, 95% CI, Holm-adjusted p-value
model.effects("distance_km") # the curves as a DataFrame
model.predict_proba(new_df)  # it is still a normal predictive model
```

![Effect curves by region](https://raw.githubusercontent.com/AnmolAdhikari/gapnet/main/docs/effects.png)

## How it works

For a person in group *g*:

```
prediction = bias + b_g + Σ_j [ f_j(x_j) + δ_j(x_j, g) ]
```

* **f_j**: a small neural network per feature, the **shared effect** for everyone.
* **δ_j**: a small **gap network** per feature that takes the feature and a learned embedding of the
  group, and learns how that group's effect curve differs.
* **Shrinkage**: a penalty pulls gaps towards zero unless the data clearly supports them, much as
  multilevel (random-effects) models do, so small groups don't produce imaginary gaps.
* **Uncertainty**: a bootstrap ensemble (10 models by default, each with early stopping on its
  out-of-bag rows) gives every effect and gap a 95% interval.
* **Testing**: each gap gets a Student-t test across the ensemble, with Holm correction over all
  features and groups. A reversal is only reported when the group's own effect passes the same bar.

Because the model is additive, each feature's effect for each group is an exact curve you can plot,
not an after-the-fact approximation.

## Does it actually work?

**It finds the gaps that are there, and only those.** On the simulated data above (6,000 rows,
4 regions), at two different random seeds, it found the planted income gap in Mountain and the distance
gaps between Hill, Terai and Valley, and every gap it flagged was a real one. Smaller planted gaps
(distance in Mountain, where data at typical distances is sparse) were not always significant: with
shrinkage, `gapnet` errs on the side of saying "not enough evidence".

**It doesn't invent gaps that aren't there.** On data with *no* group differences (`make_example(gaps=False)`)
it reported **0 false gaps across 5 datasets** (4 x 6,000 rows, 1 x 1,500 rows). This is checked in
the test suite.

**It's as accurate as a black box.** Test-set AUC on the example data (70/30 split):

| Model | AUC | Explains group gaps? |
|---|---|---|
| Logistic regression | 0.745 | No |
| MLP, 2 x 64 (scikit-learn, black box) | 0.755 | No |
| **GapNet** | **0.753** | **Yes, with CIs and tests** |

## What `gaps()` reports

| column | meaning |
|---|---|
| `effect` | change in the outcome when the feature moves from its 25th to 75th percentile (numeric) or from the reference level to this level (categorical), in this group. Log-odds for binary targets, outcome units for regression |
| `overall` | the size-weighted average effect across groups |
| `gap`, `gap_lower`, `gap_upper` | `effect - overall` with a 95% interval |
| `p`, `p_adj`, `significant` | Student-t test across the ensemble, Holm-adjusted |
| `ratio` | `effect / overall` when they share a sign ("2x stronger") |
| `(baseline)` rows | otherwise identical people (all features at their median / reference level) in different groups |

## Works on any data with groups

Nothing is specific to schools or Nepal. A few examples:

* **Health**: does smoking raise risk more for women than for men?
* **Business**: does a price change hit sales harder in one region?
* **HR and fairness**: does experience affect salary differently by department or gender?
* **Agriculture**: does rainfall matter more for some districts or crops?
* **Policy**: where should a programme go, given where a factor matters most?

Numeric, boolean and categorical features are handled automatically (categoricals are one-hot encoded
against their first level; missing numeric values are filled with the median and you are warned).
Targets can be binary (any two values) or numeric.

## Choosing a backend

`gapnet` uses whichever backend Keras is set to. Set it before importing:

```python
import os
os.environ["KERAS_BACKEND"] = "jax"      # or "tensorflow" / "torch"
```

## Options

```python
GapNet(group, task="auto", n_models=10, hidden=(32, 32), gap_hidden=16, embed_dim=4,
       gap_penalty=0.03, epochs=300, batch_size=256, learning_rate=3e-3, patience=20,
       random_state=0, verbose=0)
```

* `gap_penalty`: higher means a gap needs more evidence before it shows up.
* `n_models`: more models give tighter, more reliable intervals; below 5 the tests have little power.

## Limitations (v0.1)

* One grouping column at a time (intersections like region x gender: combine them into one column).
* Effects are additive across features; interactions *between* features are not modelled yet.
* Curves are least certain at the extremes of a feature's range, where there is little data. Read the
  bands, not just the lines.
* Binary and regression targets only (no multi-class yet).

## Related work

`gapnet` builds on Neural Additive Models (Agarwal et al., 2021), varying-coefficient models
(Hastie & Tibshirani, 1993) and multilevel models. Its contribution is a single neural model that learns
*group-specific* effect curves with shrinkage and reports the gaps with uncertainty and multiple-testing
control.

## Also by the author

* [simpsonscan](https://github.com/AnmolAdhikari/simpsonscan): find Simpson's paradoxes in your data
* [chartaudit](https://github.com/AnmolAdhikari/chartaudit): catch misleading charts (lie factor, data-ink, Anscombe)
* [pandas-mergeguard](https://github.com/AnmolAdhikari/mergeguard): predict and audit pandas merges before they break

## Citation

If you use gapnet in research, please cite:

```
Adhikari, A. (2026). gapnet: an interpretable neural network for group-specific effects (v0.1.1).
https://github.com/AnmolAdhikari/gapnet
```

MIT licensed. Contributions welcome.
