multi-sigma 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: multi-sigma
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Multi Sigma, multiple imputation for preserving subgroup variance
|
|
5
|
+
Author: Ahmed E. Abdou
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/aeabdou/multi-sigma
|
|
8
|
+
Keywords: multiple imputation,missing data,subgroup variance
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: numpy>=2.0
|
|
17
|
+
Requires-Dist: pandas>=2.0
|
|
18
|
+
Requires-Dist: scikit-learn>=1.3
|
|
19
|
+
Requires-Dist: tensorflow>=2.16
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# Multi Sigma
|
|
23
|
+
|
|
24
|
+
Multi Sigma is a multiple imputation method for continuous variables. It fills the missing values of a column several times, and gives each record imputed values whose spread follows the noise predicted for that record. This keeps the variance of the completed data close to the true variance, overall and within subgroups.
|
|
25
|
+
|
|
26
|
+
The method fits two neural networks on the records where the column is observed. The mean network predicts the value of the column. The sigma network predicts the size of the noise around that prediction. An imputed value is the predicted mean plus a residual drawn from the observed records and scaled by a weight that comes from the predicted noise of the record. With a lower bound, such as zero for income or consumption, no imputed value falls below the bound.
|
|
27
|
+
|
|
28
|
+
## Installation
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
pip install multi-sigma
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
This also installs the libraries it needs. The function was tested with Python 3.13, NumPy 2.5, pandas 3.1, scikit-learn 1.9 and TensorFlow 2.21.
|
|
35
|
+
|
|
36
|
+
## Use
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from multi_sigma import multi_sigma
|
|
40
|
+
|
|
41
|
+
completed = multi_sigma(df, y="income")
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`completed` is a list of 20 completed data frames, one per imputation. Analyse each one and combine the results with Rubin's rules.
|
|
45
|
+
|
|
46
|
+
The data are passed the way they are passed to a model such as XGBoost, and `y` says what to impute.
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
multi_sigma(df, y="income") # one column of a data frame, by its name
|
|
50
|
+
multi_sigma(df, y=["income", "rent"]) # two or more columns, by a list of names
|
|
51
|
+
multi_sigma(df, y="all") # every continuous column that has missing values
|
|
52
|
+
multi_sigma(X, y) # X holds the predictors, y is the column to impute
|
|
53
|
+
multi_sigma(X, Y) # the same with two or more columns in Y
|
|
54
|
+
multi_sigma(arr, y=3) # one NumPy array with everything, the column at position 3
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
`df`, `X`, `y` and `Y` can be pandas objects or NumPy arrays. With names, the predictors are every other column of the data frame, or the columns listed in `x`. With `X` and `y` passed separately, the predictors are the columns of `X`.
|
|
58
|
+
|
|
59
|
+
A column to impute must be continuous, which means here that it holds numbers and has more than 10 different values. Predictors must hold numbers, so a text column has to be turned into 0/1 columns first.
|
|
60
|
+
|
|
61
|
+
## The method
|
|
62
|
+
|
|
63
|
+
Three settings choose the method.
|
|
64
|
+
|
|
65
|
+
| Setting | Default | Meaning |
|
|
66
|
+
|---|---|---|
|
|
67
|
+
| `bounded` | `True` | The column has a lower bound and no imputed value falls below it. With `False` imputed values can be negative. |
|
|
68
|
+
| `lower_bound` | `0` | The lower bound when `bounded` is `True`. |
|
|
69
|
+
| `normalization` | `"self"` | `"self"` gives the self-normalized weights and `"observed"` the observed-normalized weights. |
|
|
70
|
+
|
|
71
|
+
The default is MS-SN, bounded Multi Sigma with self-normalized weights. `normalization="observed"` gives MS-ON. When several columns are imputed, `bounded` and `lower_bound` can be a dictionary with a value for each column.
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
multi_sigma(df, y=["income", "savings"], bounded={"savings": False})
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Other settings are `reps`, the number of imputations (20 by default), and `seed` and `draw_seed`, which make the results repeatable.
|
|
78
|
+
|
|
79
|
+
## Missing values in the predictors
|
|
80
|
+
|
|
81
|
+
A record is used whatever predictors it is missing. A missing predictor cell gets the average of that predictor. When a predictor is missing in at least 100 records of the training data, it also gets a 1/0 column that marks where it was missing, so the networks learn not to rely on it there. A predictor is dropped when it has too few observed values to learn from, when it is missing from every record to impute, or when it is missing in many records to impute but in few records of the training data. The function warns about every dropped predictor. The full rules are in the description at the top of `multi_sigma.py`.
|
|
82
|
+
|
|
83
|
+
## What comes back
|
|
84
|
+
|
|
85
|
+
A list with one item per imputation. With names, each item is the completed data frame or array. With `X` and `y` passed separately, each item is the completed `y`. Missing values of the predictors are not filled. `completed.info` holds, for every imputed column, the number of records imputed, their predicted means and what was done with predictors that have missing values.
|
|
86
|
+
|
|
87
|
+
## How to cite
|
|
88
|
+
|
|
89
|
+
If you use Multi Sigma, please cite the paper.
|
|
90
|
+
|
|
91
|
+
Abdou, A. E. (2026). Multi Sigma: Multiple Imputation for Preserving Subgroup Variance. Working paper.
|
|
92
|
+
|
|
93
|
+
```bibtex
|
|
94
|
+
@unpublished{abdou2026multisigma,
|
|
95
|
+
author = {Abdou, Ahmed E.},
|
|
96
|
+
title = {Multi Sigma: Multiple Imputation for Preserving Subgroup Variance},
|
|
97
|
+
note = {Working paper},
|
|
98
|
+
year = {2026}
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
The **Cite this repository** button on the right of this page gives the same citation in other formats.
|
|
103
|
+
|
|
104
|
+
## License
|
|
105
|
+
|
|
106
|
+
MIT License. See `LICENSE`.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
multi_sigma.py,sha256=FXrtP7umYNltaPzJsJ3u9bT5uWURQM-kQyCYNa4vJbM,57747
|
|
2
|
+
multi_sigma-1.0.0.dist-info/licenses/LICENSE,sha256=2Br0KhDN6NvtM9KcrOrl3MLzPnY6NZ5nWtLXyEQ-gzQ,1064
|
|
3
|
+
multi_sigma-1.0.0.dist-info/METADATA,sha256=jMG3mTKQuqv8oeF-uhqb5XNY_SS9YSaBwgZNStLsVB8,5495
|
|
4
|
+
multi_sigma-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
multi_sigma-1.0.0.dist-info/top_level.txt,sha256=h-2996QH9MY-sCpmR_SBmBbn2B39X1E40TAqGG-G3zM,12
|
|
6
|
+
multi_sigma-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 aeabdou
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
multi_sigma
|
multi_sigma.py
ADDED
|
@@ -0,0 +1,1005 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Multi Sigma imputation.
|
|
3
|
+
|
|
4
|
+
How to call it. multi_sigma imputes the missing values of one or more continuous columns. The data are passed the
|
|
5
|
+
way they are passed to a model such as XGBoost, and y says what to impute.
|
|
6
|
+
multi_sigma(df, y="income") one column of a data frame, by its name
|
|
7
|
+
multi_sigma(df, y=["income", "rent"]) two or more columns, by a list of names
|
|
8
|
+
multi_sigma(df, y="all") every continuous column that has missing values
|
|
9
|
+
multi_sigma(X, y) X holds the predictors and y is the column itself, with its missing values
|
|
10
|
+
multi_sigma(X, Y) the same with two or more columns in Y
|
|
11
|
+
multi_sigma(arr, y=3) one NumPy array with everything, the column at position 3
|
|
12
|
+
df, X, y and Y are pandas objects or NumPy arrays. A NumPy array is read as a data frame whose column names are the
|
|
13
|
+
positions 0, 1, 2 and so on, so y and x are then positions. A list is always read as names or positions. A column
|
|
14
|
+
passed as data must be a pandas object or a NumPy array. To impute a column whose name is all, pass ["all"].
|
|
15
|
+
|
|
16
|
+
The columns to impute. For each column, the records where it is observed are the training data and the records where
|
|
17
|
+
it is missing are the prediction records. A column to impute must be continuous, which means here that it holds
|
|
18
|
+
numbers and has more than 10 different values. If it is not, the function stops with an error that names the column.
|
|
19
|
+
With y="all" this holds for every column that has missing values. A named column without a missing value is skipped
|
|
20
|
+
with a warning.
|
|
21
|
+
|
|
22
|
+
The predictors. With names, the predictors of a column are every other column of the data frame, or the columns
|
|
23
|
+
listed in x. With X and y passed separately, the predictors are the columns of X, or those of them listed in x. A
|
|
24
|
+
predictor must hold numbers. A text column gives an error that names it, and it has to be turned into 0/1 columns
|
|
25
|
+
first. A predictor may have missing values (see Missing values in the predictors).
|
|
26
|
+
|
|
27
|
+
Several columns. Each column is imputed on its own, by its own two networks. Another column to impute that is among
|
|
28
|
+
the predictors is used like any predictor, with its observed values and with its missing values handled as below.
|
|
29
|
+
Imputed values of one column are never used to impute another, so the order of the columns does not matter. For a
|
|
30
|
+
record that is missing two of the columns, each of the two values is drawn without looking at the other.
|
|
31
|
+
|
|
32
|
+
What comes back. A list with one item per imputation, reps of them (20 by default). Each item is the thing that had
|
|
33
|
+
the missing values, with them filled. With names it is the completed data frame, or the completed array. With X and y
|
|
34
|
+
it is the completed y. Missing values of the predictors are not filled. The list also has .info, which holds for
|
|
35
|
+
every imputed column what impute_column reports for it (see below), the number of records imputed and the predicted
|
|
36
|
+
mean of each of them from the full-data fit.
|
|
37
|
+
|
|
38
|
+
impute_column. Multi Sigma for one column, with the training data (base_df) and the prediction records (target_df)
|
|
39
|
+
passed as two data frames. It returns the imputed values of the prediction records, one column per imputation, and
|
|
40
|
+
their predicted means. multi_sigma calls it once for every column to impute. The tests of the paper have this form, a
|
|
41
|
+
training table and a held-out table, so they are rerun with impute_column. In the text below, the observed rows are
|
|
42
|
+
the training data, and the rows to impute, or target rows, are the prediction records.
|
|
43
|
+
|
|
44
|
+
The method. Three settings choose it.
|
|
45
|
+
bounded True by default. The outcome has a lower bound and no imputed value falls below it. False is for
|
|
46
|
+
an outcome without a lower bound, and imputed values can then be negative.
|
|
47
|
+
lower_bound The lower bound of the outcome when bounded is True, 0 by default. No observed outcome may be
|
|
48
|
+
below it. It is not used when bounded is False.
|
|
49
|
+
normalization "self", the default, gives the self-normalized weights and "observed" the observed-normalized
|
|
50
|
+
weights (see The weights).
|
|
51
|
+
The four methods they give
|
|
52
|
+
bounded=True, normalization="self" MS-SN, bounded Multi Sigma with self-normalized weights. The default.
|
|
53
|
+
bounded=True, normalization="observed" MS-ON, bounded Multi Sigma with observed-normalized weights.
|
|
54
|
+
bounded=False, normalization="self" Multi Sigma without a bound, with self-normalized weights.
|
|
55
|
+
bounded=False, normalization="observed" Multi Sigma without a bound, with observed-normalized weights.
|
|
56
|
+
In multi_sigma, bounded and lower_bound are one value for every column, or a dictionary with a value for each column,
|
|
57
|
+
because columns can have different bounds. A column that is not in the dictionary takes the default.
|
|
58
|
+
|
|
59
|
+
Missing values in the predictors. A record is used whatever predictors it is missing. Each predictor is standardized
|
|
60
|
+
with the average and the SD of its observed values in the training data, and a missing cell then gets 0, which is that
|
|
61
|
+
average. What else happens depends on how much the predictor is missing. Take income as the predictor. Not missing
|
|
62
|
+
much means missing in fewer than min_records records (100 by default), and missing a lot means missing in min_records
|
|
63
|
+
records or more. Dropped means that the run goes without income for all records, with a warning that gives the
|
|
64
|
+
reason. The cases are checked in this order and the first one that fits is taken.
|
|
65
|
+
Case 1. Income has fewer than min_records observed values in the training data, and the rest are missing. That is
|
|
66
|
+
too few for the networks to learn what income does, so income is dropped.
|
|
67
|
+
Case 2. This case is about the prediction, not the training. If income is missing from all of the prediction
|
|
68
|
+
records, it is dropped, because the model would never get to use it.
|
|
69
|
+
Case 3. Income is not missing much in the training data. The networks learn from the binary 1/0 column whether
|
|
70
|
+
income is missing or not. Here they did not see income missing much, so they cannot learn not to rely on
|
|
71
|
+
income when it is missing. This is okay if income is also not missing much in the prediction records
|
|
72
|
+
(case 5). But if income is missing a lot in the prediction records and not in the training data, income
|
|
73
|
+
is also dropped.
|
|
74
|
+
Case 4. Income is missing a lot in the training data. The networks saw income missing many times, so they can
|
|
75
|
+
learn from the binary 1/0 column not to rely on income when it is missing. Income is kept. Where it is
|
|
76
|
+
missing, the cell gets the average and the binary column is 1. Both networks get that column, so the sigma
|
|
77
|
+
network can also give a record without income a larger noise size. It does not matter how much income is
|
|
78
|
+
missing in the prediction records, as long as it is not missing from all of them, which is case 2.
|
|
79
|
+
Case 5. Income is not missing much in the training data, and not much in the prediction records either. Income
|
|
80
|
+
is kept, and where it is missing the cell gets the average. There is no binary column here, because the
|
|
81
|
+
networks would not see the 1 enough times to learn from it.
|
|
82
|
+
The predictors themselves are not imputed. impute_column reports in .attrs["predictors"] what was done with every
|
|
83
|
+
predictor that has missing values, with the number of training records and of prediction records where it is observed
|
|
84
|
+
and where it is missing. When no predictor has a missing value none of this happens, and the run is the same as
|
|
85
|
+
without this step.
|
|
86
|
+
|
|
87
|
+
The two networks. The mean network is the outcome model of the paper. It predicts the outcome. The sigma network is
|
|
88
|
+
the sigma model of the paper. It is trained on the squared residuals of the mean network and predicts the noise size
|
|
89
|
+
of each row. With a bound, the output of the mean network is the bound plus a softplus, so every predicted mean is
|
|
90
|
+
above the bound. Without a bound its output is linear, so a predicted mean can be negative.
|
|
91
|
+
|
|
92
|
+
The weights. The self-normalized weights divide the predicted sigma of a row to impute by the root of the average
|
|
93
|
+
squared predicted sigma of the rows to impute, so the squared weights of those rows average to one, and the total
|
|
94
|
+
noise variance of the plain draws is the variance of the residual pool. The observed-normalized weights take that
|
|
95
|
+
average over the rows of the residual pool instead, the rows whose residuals the draws take, with the predicted sigma
|
|
96
|
+
of the same sigma network,
|
|
97
|
+
w = sigma / sqrt(mean(sigma_pool ** 2)).
|
|
98
|
+
The squared weight of a row is then its predicted squared residual divided by the average predicted squared residual
|
|
99
|
+
of the pool rows, so it says how many times the variance of the pool the row gets. The squared weights of the rows to
|
|
100
|
+
impute average to the ratio of the two averages, not to one, and the weight of a row does not depend on the other
|
|
101
|
+
rows to impute. The imputations carry in .attrs mean_squared_weight, the mean over the fits of the average squared
|
|
102
|
+
weight of the target rows, before any weight is lowered.
|
|
103
|
+
|
|
104
|
+
The draws. Without a bound, a draw is the predicted mean of the row plus its weight times a residual drawn from the
|
|
105
|
+
centered residual pool (the plain draw). With a bound, the bounded draw step keeps every draw at or above the bound
|
|
106
|
+
while each row keeps its mean and its noise variance. For each row the lowest residuals are dropped from the pool
|
|
107
|
+
until no draw can fall below the bound, and the kept residuals are shifted and stretched back to mean zero and to the
|
|
108
|
+
SD of the full pool.
|
|
109
|
+
|
|
110
|
+
The check of the bounded draw step. A row whose weight is too large for the pool to keep its draws above the bound gets
|
|
111
|
+
the largest weight the pool can carry for it, and the other weights are scaled up so that the squared sum of the
|
|
112
|
+
weights does not change. The check fails when even the largest weights of all the rows together cannot carry that sum,
|
|
113
|
+
sum(max_weight**2) < sum(weights**2). This happens only with very few missing rows whose predicted means are close to
|
|
114
|
+
the bound. Every row of a completed dataset whose check fails takes a nearby draw. With a bound, the imputations
|
|
115
|
+
carry the counts of _counts in .attrs, fits_check_failed among them.
|
|
116
|
+
|
|
117
|
+
Nearby draws. The rows of the residual pool of a fit are observed rows (with bootstrap refits, the rows the bootstrap
|
|
118
|
+
sample left out). For a row to impute, they are put in order of how close their predicted means are to its predicted
|
|
119
|
+
mean, on both sides. The row uses the k nearest, k = n^(2/3) for a pool of n rows (the rate the kNNSampler paper gives
|
|
120
|
+
for neighbours matched on one number), and k_min when n^(2/3) is smaller, never more than n. One of the k is drawn at
|
|
121
|
+
random. The draw is the predicted mean of the row times the outcome of that neighbour divided by the predicted mean of
|
|
122
|
+
that neighbour, each measured from the bound,
|
|
123
|
+
lower_bound + (mu - lower_bound) * (y - lower_bound) / (pred - lower_bound).
|
|
124
|
+
Outcomes are at or above the bound and predicted means above it, so no draw goes below the bound and every row gets a
|
|
125
|
+
draw. The nearby draw of a row does not depend on the other rows or on the weights.
|
|
126
|
+
|
|
127
|
+
Model uncertainty. The networks are fitted on the observed rows, so their predictions carry estimation error.
|
|
128
|
+
Imputations that all reuse one fit leave that error out, and Rubin's rules then understate the variance of the
|
|
129
|
+
estimates. Each of the reps imputations therefore comes from its own fit. model_draws chooses how the fits are made.
|
|
130
|
+
|
|
131
|
+
"bootstrap" The default. Each fit refits both networks on a bootstrap sample of the observed rows, starting from
|
|
132
|
+
the weights of the full-data fit and training for refit_epochs passes (a warm start). The row
|
|
133
|
+
weights of that fit come from its sigma network. Its residual pool comes from the rows the bootstrap
|
|
134
|
+
sample left out, because residuals on the rows a network was just trained on are too small. The warm
|
|
135
|
+
start keeps the refits closer to the full-data fit than independent refits would be, so the model
|
|
136
|
+
term is somewhat understated.
|
|
137
|
+
"last_layer" One full-data fit, no refitting. The output layer of the mean network is a regression of the outcome
|
|
138
|
+
on the last hidden layer. Each fit draws the coefficients of that regression from a normal
|
|
139
|
+
approximation to their sampling distribution (heteroskedasticity-robust covariance) and keeps the
|
|
140
|
+
hidden layers, the sigma network and the residual pool of the full fit. This carries the uncertainty
|
|
141
|
+
of the output layer only, so it understates the model term.
|
|
142
|
+
"none" One full-data fit reused for every imputation.
|
|
143
|
+
|
|
144
|
+
The returned predicted mean is always that of the full-data fit.
|
|
145
|
+
|
|
146
|
+
Overflow in the refits. Adam keeps a running average v of each squared gradient entry, which Keras updates as
|
|
147
|
+
v += (g**2 - v) * (1 - beta_2). An entry g above 1.84e19 has a square beyond the largest float32 number, so v becomes
|
|
148
|
+
infinite, the next step subtracts infinity from infinity, and the weights become NaN. The sigma network is trained on
|
|
149
|
+
squared residuals, so on an outcome in the hundreds of thousands with predictors far out in the tails (UCI Credit, whose
|
|
150
|
+
predictors reach 77 standard deviations from their means) its gradient entries pass that limit. The full-data fit is
|
|
151
|
+
protected by early stopping, which goes back to its best weights. A refit has no such step, so the refits clip every
|
|
152
|
+
gradient entry at 1.84e19. An entry below the limit passes unchanged, so every step that did not overflow is exactly
|
|
153
|
+
the step it was before, and the full-data fit is not clipped at all. As a last safety net, a refit whose predictions are
|
|
154
|
+
still not all finite is trained again on a new bootstrap sample, drawn from a generator of its own so that every other
|
|
155
|
+
refit keeps its sample. The number of such refits is returned in .attrs["refits_redrawn"].
|
|
156
|
+
|
|
157
|
+
Seeds. seed fixes the networks, their training and the bootstrap samples. draw_seed fixes the random numbers of the
|
|
158
|
+
draws and is seed when it is not given. A benchmark that repeats the imputation over many train/test splits should give
|
|
159
|
+
each split its own draw_seed. The bounded draw step takes a residual by its position in the sorted pool, so with the
|
|
160
|
+
same random numbers in every split the same part of the pool (the largest residuals, say) is drawn in every split, and
|
|
161
|
+
the luck of the draws does not average out over the splits.
|
|
162
|
+
multi_sigma gives seed and draw_seed to impute_column as they are when one column is imputed. When several columns are
|
|
163
|
+
imputed, seed is the same for every column, and every column gets its own random numbers for the draws, made from
|
|
164
|
+
draw_seed and the name of the column. Two columns then never share those numbers, and the order of the list does not
|
|
165
|
+
matter.
|
|
166
|
+
|
|
167
|
+
The methods file of the paper. For the same seeds, impute_column gives the same draws as multi_sigma_methods.py. MS-SN
|
|
168
|
+
is its multi_sigma_cut_knn, MS-ON its multi_sigma_cut_knn_pool, and Multi Sigma without a bound with self-normalized
|
|
169
|
+
weights its multi_sigma_original.
|
|
170
|
+
"""
|
|
171
|
+
import warnings
|
|
172
|
+
import zlib
|
|
173
|
+
|
|
174
|
+
import numpy as np
|
|
175
|
+
import pandas as pd
|
|
176
|
+
import tensorflow as tf
|
|
177
|
+
from sklearn.preprocessing import StandardScaler
|
|
178
|
+
|
|
179
|
+
NORMALIZATIONS = ("self", "observed")
|
|
180
|
+
MODEL_DRAWS = ("bootstrap", "last_layer", "none")
|
|
181
|
+
K_MIN = 50 # the smallest number of neighbours of the nearby draws
|
|
182
|
+
MIN_RECORDS = 100 # the number of records between not missing much and missing a lot
|
|
183
|
+
MIN_DIFFERENT_VALUES = 10 # a continuous column has more different values than this
|
|
184
|
+
_GRAD_LIMIT = float(np.sqrt(np.finfo(np.float32).max)) # 1.84e19, the largest gradient entry whose square float32 holds
|
|
185
|
+
_MAX_REDRAWS = 20 # new bootstrap samples tried for one refit whose training broke down, see the module docstring
|
|
186
|
+
|
|
187
|
+
_TINY = np.finfo(np.float32).tiny
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
# =========================================================
|
|
191
|
+
# The data
|
|
192
|
+
# =========================================================
|
|
193
|
+
def _prepare(base_df, target_df, y_col, x_cols, min_records=MIN_RECORDS):
|
|
194
|
+
"""
|
|
195
|
+
Observed outcome and standardized predictors of the training data and of the prediction records. Also returns
|
|
196
|
+
what was done with every predictor that has missing values, with its counts (see Missing values in the predictors
|
|
197
|
+
in the module docstring). When no predictor has a missing value, this is the standardization alone.
|
|
198
|
+
"""
|
|
199
|
+
b = base_df[[y_col] + x_cols].dropna(subset=[y_col]) # the training data, the rows whose outcome is observed
|
|
200
|
+
y = b[y_col].to_numpy(float)
|
|
201
|
+
Xb = b[x_cols].to_numpy(float)
|
|
202
|
+
Xt = target_df[x_cols].to_numpy(float)
|
|
203
|
+
|
|
204
|
+
empty_b, empty_t = np.isnan(Xb), np.isnan(Xt)
|
|
205
|
+
keep = np.ones(len(x_cols), bool) # the predictors that are used
|
|
206
|
+
mark = np.zeros(len(x_cols), bool) # the predictors that get a binary 1/0 column
|
|
207
|
+
done = {}
|
|
208
|
+
for j in np.flatnonzero(empty_b.any(axis=0) | empty_t.any(axis=0)):
|
|
209
|
+
n = dict(training_observed=int((~empty_b[:, j]).sum()), training_missing=int(empty_b[:, j].sum()),
|
|
210
|
+
prediction_observed=int((~empty_t[:, j]).sum()), prediction_missing=int(empty_t[:, j].sum()))
|
|
211
|
+
if n["training_observed"] < min_records: # case 1
|
|
212
|
+
keep[j], action = False, "dropped, too few observed values in the training data"
|
|
213
|
+
elif n["prediction_observed"] == 0: # case 2
|
|
214
|
+
keep[j], action = False, "dropped, missing from all of the prediction records"
|
|
215
|
+
elif n["training_missing"] < min_records <= n["prediction_missing"]: # case 3
|
|
216
|
+
keep[j], action = False, "dropped, missing a lot in the prediction records and not in the training data"
|
|
217
|
+
elif n["training_missing"] >= min_records: # case 4
|
|
218
|
+
mark[j], action = True, "kept, average and 1/0 column"
|
|
219
|
+
else: # case 5
|
|
220
|
+
action = "kept, average"
|
|
221
|
+
done[x_cols[j]] = dict(action=action, **n)
|
|
222
|
+
|
|
223
|
+
scaler = StandardScaler()
|
|
224
|
+
if not done:
|
|
225
|
+
Xb = scaler.fit_transform(Xb)
|
|
226
|
+
Xt = scaler.transform(Xt)
|
|
227
|
+
return y, Xb, Xt, done
|
|
228
|
+
|
|
229
|
+
if not keep.any():
|
|
230
|
+
raise ValueError("Every predictor was dropped, so there is nothing to predict the outcome from.")
|
|
231
|
+
# The scaler takes the average and the SD of the observed values of the training data and leaves the missing
|
|
232
|
+
# cells missing
|
|
233
|
+
Xb = scaler.fit_transform(Xb[:, keep])
|
|
234
|
+
Xt = scaler.transform(Xt[:, keep])
|
|
235
|
+
Xb[np.isnan(Xb)] = 0.0 # a missing cell gets the average, which is 0 after the standardization
|
|
236
|
+
Xt[np.isnan(Xt)] = 0.0
|
|
237
|
+
Xb = np.column_stack([Xb, empty_b[:, mark].astype(float)]) # the binary 1/0 columns, 1 where the cell was missing
|
|
238
|
+
Xt = np.column_stack([Xt, empty_t[:, mark].astype(float)])
|
|
239
|
+
return y, Xb, Xt, done
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _above(mu, floor):
|
|
243
|
+
"""
|
|
244
|
+
Predicted means strictly above the bound, for the cut pool. A softplus output can round to
|
|
245
|
+
exactly zero in float32, so a mean that sits on the bound is moved to the smallest value
|
|
246
|
+
above it.
|
|
247
|
+
"""
|
|
248
|
+
lowest = floor + _TINY if floor == 0 else np.nextafter(floor, np.inf)
|
|
249
|
+
return np.maximum(np.asarray(mu, dtype=np.float64), lowest)
|
|
250
|
+
|
|
251
|
+
# =========================================================
|
|
252
|
+
# The networks, their fit and their warm started refits
|
|
253
|
+
# =========================================================
|
|
254
|
+
def _network(n_inputs, output_activation=None):
|
|
255
|
+
return tf.keras.Sequential([
|
|
256
|
+
tf.keras.layers.Input(shape=(n_inputs,)),
|
|
257
|
+
tf.keras.layers.Dense(128, activation="relu"),
|
|
258
|
+
tf.keras.layers.Dense(64, activation="relu"),
|
|
259
|
+
tf.keras.layers.Dense(32, activation="relu"),
|
|
260
|
+
tf.keras.layers.Dense(1, activation=output_activation),
|
|
261
|
+
])
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _fit(model, X, target, epochs, batch_size, patience, seed):
|
|
265
|
+
"""
|
|
266
|
+
Keras fit with validation_split=0.1 and EarlyStopping(patience, restore_best_weights=True),
|
|
267
|
+
step for step. The first 90% of the rows train in batches taken in the order Keras fit uses
|
|
268
|
+
after tf.keras.utils.set_random_seed(seed). After every pass the loss on the last 10% is
|
|
269
|
+
computed batch by batch and averaged as Keras does. Training stops when that loss has not
|
|
270
|
+
improved for `patience` passes, and the network gets the weights of its best pass. The steps
|
|
271
|
+
run through Keras's own training and test functions, without the per-pass work of fit (data
|
|
272
|
+
iterators, callbacks), which took most of the time on networks this small.
|
|
273
|
+
"""
|
|
274
|
+
model.compile(optimizer="adam", loss="mse")
|
|
275
|
+
X = np.asarray(X, dtype=np.float32)
|
|
276
|
+
target = np.asarray(target, dtype=np.float32)
|
|
277
|
+
n_train = int(np.floor(len(X) * (1.0 - 0.1)))
|
|
278
|
+
order = _row_order(seed, n_train)
|
|
279
|
+
X_val, t_val = X[n_train:], target[n_train:]
|
|
280
|
+
best, best_weights, wait = None, None, 0
|
|
281
|
+
for epoch in range(epochs):
|
|
282
|
+
for a in range(0, n_train, batch_size):
|
|
283
|
+
b = order[a:a + batch_size]
|
|
284
|
+
model.train_on_batch(X[b], target[b])
|
|
285
|
+
# validation loss as Keras evaluate computes it, batch losses averaged with the batch sizes as weights, in float32
|
|
286
|
+
total, count = np.float32(0), np.float32(0)
|
|
287
|
+
for a in range(0, len(X_val), batch_size):
|
|
288
|
+
loss = np.float32(model.test_on_batch(X_val[a:a + batch_size], t_val[a:a + batch_size]))
|
|
289
|
+
size = np.float32(len(X_val[a:a + batch_size]))
|
|
290
|
+
total, count = np.float32(total + np.float32(loss * size)), np.float32(count + size)
|
|
291
|
+
val_loss = float(np.float32(total / count))
|
|
292
|
+
wait += 1
|
|
293
|
+
if best is None or val_loss < best:
|
|
294
|
+
best, best_weights, wait = val_loss, model.get_weights(), 0
|
|
295
|
+
elif wait >= patience and epoch > 0:
|
|
296
|
+
break
|
|
297
|
+
model.set_weights(best_weights)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
_ORDERS = {}
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _row_order(seed, n):
|
|
304
|
+
"""
|
|
305
|
+
The order in which Keras fit goes through n rows once tf.keras.utils.set_random_seed(seed)
|
|
306
|
+
has been called. Keras fit with shuffle=True shuffles the rows once and feeds that same order
|
|
307
|
+
in every pass. The shuffle below is the one Keras runs.
|
|
308
|
+
"""
|
|
309
|
+
if (seed, n) not in _ORDERS:
|
|
310
|
+
@tf.autograph.experimental.do_not_convert
|
|
311
|
+
def shuffle(_):
|
|
312
|
+
return tf.random.shuffle(tf.range(n, dtype=tf.int64))
|
|
313
|
+
|
|
314
|
+
tf.random.set_seed(seed)
|
|
315
|
+
_ORDERS[(seed, n)] = next(iter(tf.data.Dataset.range(1).map(shuffle))).numpy()
|
|
316
|
+
return _ORDERS[(seed, n)]
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _fresh_adam(model):
|
|
320
|
+
"""The values of the variables of a new Adam optimizer for this model, as compile would create it."""
|
|
321
|
+
opt = tf.keras.optimizers.Adam()
|
|
322
|
+
opt.build(model.trainable_variables)
|
|
323
|
+
return [v.numpy() for v in opt.variables]
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _refit(model, start_weights, fresh_adam, X, target, epochs, batch_size, order):
|
|
327
|
+
"""
|
|
328
|
+
Warm start. Put the full-data weights back, start Adam again and train for a few passes on a
|
|
329
|
+
bootstrap sample, so the network moves from the full-data fit toward the fit of the sample
|
|
330
|
+
instead of being trained from scratch.
|
|
331
|
+
|
|
332
|
+
This does what compiling the model again and calling fit would do, step for step. Adam goes
|
|
333
|
+
back to the state of a new optimizer, and the batches are taken in the order Keras fit uses
|
|
334
|
+
after tf.keras.utils.set_random_seed (order). The steps run through the training function
|
|
335
|
+
Keras built for the full-data fit, so they are the same computation, without compiling and
|
|
336
|
+
building that function again for every refit, which took most of the time.
|
|
337
|
+
"""
|
|
338
|
+
model.set_weights(start_weights)
|
|
339
|
+
for v, v0 in zip(model.optimizer.variables, fresh_adam):
|
|
340
|
+
v.assign(v0)
|
|
341
|
+
X = np.asarray(X, dtype=np.float32)
|
|
342
|
+
target = np.asarray(target, dtype=np.float32)
|
|
343
|
+
for _ in range(epochs):
|
|
344
|
+
for a in range(0, len(order), batch_size):
|
|
345
|
+
b = order[a:a + batch_size]
|
|
346
|
+
model.train_on_batch(X[b], target[b])
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _predict(model, X, offset=0.0):
|
|
350
|
+
return model.predict(X, verbose=0).reshape(-1) + offset
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _hidden(model, X):
|
|
354
|
+
"""Output of the last hidden layer of a network for the rows X."""
|
|
355
|
+
dense = [layer for layer in model.layers if isinstance(layer, tf.keras.layers.Dense)]
|
|
356
|
+
h = tf.convert_to_tensor(np.asarray(X, dtype=np.float32))
|
|
357
|
+
for layer in dense[:-1]:
|
|
358
|
+
h = layer(h)
|
|
359
|
+
return np.asarray(h.numpy(), dtype=np.float64)
|
|
360
|
+
|
|
361
|
+
# =========================================================
|
|
362
|
+
# Stage 1 and Stage 2 on all observed rows
|
|
363
|
+
# =========================================================
|
|
364
|
+
def _fit_mean(Xb, y, seed, epochs, batch_size, patience, activation=None, floor=0.0):
|
|
365
|
+
"""
|
|
366
|
+
Stage 1. Mean model, a network trained with MSE to predict the outcome.
|
|
367
|
+
activation is the output activation of the network. None gives a linear output.
|
|
368
|
+
"softplus" trains the network on the outcome minus the bound and adds the bound back, so
|
|
369
|
+
every predicted mean is above the bound.
|
|
370
|
+
Returns the fitted network and the offset to add back to its output.
|
|
371
|
+
"""
|
|
372
|
+
tf.keras.utils.set_random_seed(seed)
|
|
373
|
+
mean_model = _network(Xb.shape[1], activation)
|
|
374
|
+
offset = floor if activation == "softplus" else 0.0
|
|
375
|
+
_fit(mean_model, Xb, y - offset, epochs, batch_size, patience, seed)
|
|
376
|
+
return mean_model, offset
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _fit_sigma(Xb, squared_resid, seed, epochs, batch_size, patience):
|
|
380
|
+
"""
|
|
381
|
+
Stage 2. Sigma model, a network with a softplus output trained on a squared residual.
|
|
382
|
+
Returns the fitted network.
|
|
383
|
+
"""
|
|
384
|
+
tf.keras.utils.set_random_seed(seed)
|
|
385
|
+
sigma_model = _network(Xb.shape[1], "softplus")
|
|
386
|
+
_fit(sigma_model, Xb, squared_resid, epochs, batch_size, patience, seed)
|
|
387
|
+
return sigma_model
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _fit_full(Xb, Xt, y, seed, mean_epochs, sigma_epochs, batch_size, patience, activation, floor):
|
|
391
|
+
"""
|
|
392
|
+
Stage 1 and Stage 2 on all observed rows. Returns the two fitted networks, the offset, the
|
|
393
|
+
residuals of the observed rows and the predicted means of the target rows.
|
|
394
|
+
"""
|
|
395
|
+
mean_model, offset = _fit_mean(Xb, y, seed, mean_epochs, batch_size, patience, activation, floor)
|
|
396
|
+
resid = y - _predict(mean_model, Xb, offset)
|
|
397
|
+
sigma_model = _fit_sigma(Xb, resid ** 2, seed, sigma_epochs, batch_size, patience)
|
|
398
|
+
mu_test = _predict(mean_model, Xt, offset)
|
|
399
|
+
return mean_model, sigma_model, offset, resid, mu_test
|
|
400
|
+
|
|
401
|
+
# =========================================================
|
|
402
|
+
# The weights
|
|
403
|
+
# =========================================================
|
|
404
|
+
def _sigma(sigma_model, X):
|
|
405
|
+
"""Predicted sigma of the rows X, the root of the predicted squared residual floored at 1e-8."""
|
|
406
|
+
return np.sqrt(np.maximum(_predict(sigma_model, X), 1e-8))
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _self_normalized(sigma_test_row):
|
|
410
|
+
"""
|
|
411
|
+
Self-normalized weights. Rows with a larger predicted sigma get more noise, rows with a
|
|
412
|
+
smaller one get less, and mean(weights**2) = 1 over the rows to impute keeps the total
|
|
413
|
+
noise variance equal to the variance of the residual pool.
|
|
414
|
+
"""
|
|
415
|
+
weights = sigma_test_row / np.mean(sigma_test_row)
|
|
416
|
+
return weights / np.sqrt(np.mean(weights ** 2))
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _observed_normalized(sigma_target, sigma_pool):
|
|
420
|
+
"""
|
|
421
|
+
Observed-normalized weights. The predicted sigma of every row to impute divided by the root of the average squared
|
|
422
|
+
predicted sigma of the rows of the residual pool, both from the same sigma network.
|
|
423
|
+
"""
|
|
424
|
+
sigma_target = np.asarray(sigma_target, dtype=np.float64)
|
|
425
|
+
sigma_pool = np.asarray(sigma_pool, dtype=np.float64)
|
|
426
|
+
return sigma_target / np.sqrt(np.mean(sigma_pool ** 2))
|
|
427
|
+
|
|
428
|
+
# =========================================================
|
|
429
|
+
# The fits
|
|
430
|
+
# =========================================================
|
|
431
|
+
def _fits(full, activation, Xb, Xt, y, seed, batch_size, model_draws, n_fits, refit_epochs, rng_model, redrawn=None):
|
|
432
|
+
"""
|
|
433
|
+
The fits. Yields, once per fit, the predicted means of the target rows, the centered residual pool, the predicted
|
|
434
|
+
sigma of the target rows and of the pool rows, and the predicted means and the outcomes of the pool rows, in the
|
|
435
|
+
order of the pool. rng_model draws the bootstrap samples or the output-layer coefficients. redrawn, a list,
|
|
436
|
+
receives the number of every refit that had to be trained again on a new bootstrap sample (see the module
|
|
437
|
+
docstring).
|
|
438
|
+
"""
|
|
439
|
+
mean_model, sigma_model, offset, resid, mu_test = full
|
|
440
|
+
|
|
441
|
+
if model_draws == "none":
|
|
442
|
+
# The residual pool is the residuals of the full-data fit, on every observed row
|
|
443
|
+
yield (mu_test, resid - resid.mean(), _sigma(sigma_model, Xt), _sigma(sigma_model, Xb),
|
|
444
|
+
_predict(mean_model, Xb, offset), y)
|
|
445
|
+
|
|
446
|
+
elif model_draws == "bootstrap":
|
|
447
|
+
mean_weights = mean_model.get_weights()
|
|
448
|
+
sigma_weights = sigma_model.get_weights()
|
|
449
|
+
mean_adam, sigma_adam = _fresh_adam(mean_model), _fresh_adam(sigma_model)
|
|
450
|
+
# The refits clip every gradient entry at _GRAD_LIMIT (see the module docstring). An entry below the limit
|
|
451
|
+
# passes unchanged, so a step without an overflow is exactly the step it was before.
|
|
452
|
+
for model in (mean_model, sigma_model):
|
|
453
|
+
model.optimizer.clipvalue = _GRAD_LIMIT
|
|
454
|
+
model.make_train_function(force=True)
|
|
455
|
+
n = len(y)
|
|
456
|
+
for t in range(n_fits):
|
|
457
|
+
idx = rng_model.choice(n, size=n, replace=True)
|
|
458
|
+
order = _row_order(seed + 1 + t, n) # the batch order of Keras fit after tf.keras.utils.set_random_seed(seed + 1 + t)
|
|
459
|
+
for attempt in range(_MAX_REDRAWS + 1):
|
|
460
|
+
if attempt > 0:
|
|
461
|
+
# The training of this refit broke down. Train it again on a new bootstrap sample, drawn
|
|
462
|
+
# from a generator of its own so that every other refit keeps its sample.
|
|
463
|
+
if redrawn is not None:
|
|
464
|
+
redrawn.append(t)
|
|
465
|
+
idx = np.random.default_rng([seed, 1, t, attempt]).choice(n, size=n, replace=True)
|
|
466
|
+
oob = np.setdiff1d(np.arange(n), idx) # the rows the sample left out, about 37% of them
|
|
467
|
+
_refit(mean_model, mean_weights, mean_adam, Xb[idx], y[idx] - offset, refit_epochs, batch_size, order)
|
|
468
|
+
resid_t = y[idx] - _predict(mean_model, Xb[idx], offset)
|
|
469
|
+
_refit(sigma_model, sigma_weights, sigma_adam, Xb[idx], resid_t ** 2, refit_epochs, batch_size, order)
|
|
470
|
+
# The residual pool comes from the out-of-bag rows. The in-bag residuals are too small, the
|
|
471
|
+
# refit has just been trained on those rows, and a pool built from them shrinks the draws.
|
|
472
|
+
rows = oob if len(oob) > 1 else idx
|
|
473
|
+
pred_pool = _predict(mean_model, Xb[rows], offset)
|
|
474
|
+
pool = y[rows] - pred_pool
|
|
475
|
+
mu_t, sigma_t = _predict(mean_model, Xt, offset), _sigma(sigma_model, Xt)
|
|
476
|
+
if np.isfinite(mu_t).all() and np.isfinite(pool).all() and np.isfinite(_self_normalized(sigma_t)).all():
|
|
477
|
+
break
|
|
478
|
+
else:
|
|
479
|
+
raise ValueError(f"The training of refit {t} broke down on {_MAX_REDRAWS + 1} bootstrap samples in a row.")
|
|
480
|
+
yield mu_t, pool - pool.mean(), sigma_t, _sigma(sigma_model, Xb[rows]), pred_pool, y[rows]
|
|
481
|
+
|
|
482
|
+
else:
|
|
483
|
+
# The output layer of the mean network is a regression of the outcome on the last hidden
|
|
484
|
+
# layer, with an intercept. Around the trained coefficients beta, a first-order expansion
|
|
485
|
+
# gives the sampling covariance (J'J)^-1 J' diag(e^2) J (J'J)^-1, where J is the design
|
|
486
|
+
# matrix of hidden features scaled by the slope of the output activation and e are the
|
|
487
|
+
# residuals of the observed rows. Each fit is a draw of beta from a normal with that
|
|
488
|
+
# covariance. Hidden layers, sigma network and residual pool stay those of the full fit.
|
|
489
|
+
H = np.column_stack([_hidden(mean_model, Xb), np.ones(len(y))])
|
|
490
|
+
Ht = np.column_stack([_hidden(mean_model, Xt), np.ones(len(Xt))])
|
|
491
|
+
W, b = [layer for layer in mean_model.layers if isinstance(layer, tf.keras.layers.Dense)][-1].get_weights()
|
|
492
|
+
beta = np.concatenate([W[:, 0], b]).astype(np.float64)
|
|
493
|
+
if activation == "softplus":
|
|
494
|
+
act = lambda z: np.logaddexp(0.0, z)
|
|
495
|
+
slope = 1.0 / (1.0 + np.exp(-(H @ beta)))
|
|
496
|
+
else:
|
|
497
|
+
act = lambda z: z
|
|
498
|
+
slope = np.ones(len(y))
|
|
499
|
+
J = slope[:, None] * H
|
|
500
|
+
A_inv = np.linalg.pinv(J.T @ J)
|
|
501
|
+
V = A_inv @ (J.T @ (resid[:, None] ** 2 * J)) @ A_inv
|
|
502
|
+
V = (V + V.T) / 2
|
|
503
|
+
betas = rng_model.multivariate_normal(beta, V, size=n_fits)
|
|
504
|
+
pool = resid - resid.mean()
|
|
505
|
+
sigma_t, sigma_pool = _sigma(sigma_model, Xt), _sigma(sigma_model, Xb)
|
|
506
|
+
pred_pool = _predict(mean_model, Xb, offset)
|
|
507
|
+
for t in range(n_fits):
|
|
508
|
+
yield act(Ht @ betas[t]) + offset, pool, sigma_t, sigma_pool, pred_pool, y
|
|
509
|
+
|
|
510
|
+
# =========================================================
|
|
511
|
+
# The plain draw
|
|
512
|
+
# =========================================================
|
|
513
|
+
def _plain_draws(mu, weights, pool, reps, rng):
|
|
514
|
+
"""The plain draw. Each draw is the row mean plus the row weight times a residual drawn from the centered pool."""
|
|
515
|
+
out = np.empty((len(mu), reps), float)
|
|
516
|
+
for r in range(reps):
|
|
517
|
+
out[:, r] = mu + rng.choice(pool, size=len(mu), replace=True) * weights
|
|
518
|
+
return out
|
|
519
|
+
|
|
520
|
+
# =========================================================
|
|
521
|
+
# The bounded draw step, in parts
|
|
522
|
+
# =========================================================
|
|
523
|
+
def _cut_pool(resid, max_drop=0.5):
|
|
524
|
+
"""
|
|
525
|
+
The part of the bounded draw step that depends only on the residual pool. Returns the sorted centered pool, its
|
|
526
|
+
size and SD, and for every valid cut the number of residuals it drops, the mean and SD of the residuals it keeps,
|
|
527
|
+
and the lowest kept residual after the shift and stretch.
|
|
528
|
+
"""
|
|
529
|
+
resid = np.asarray(resid, dtype=np.float64)
|
|
530
|
+
pool = np.sort(resid - resid.mean()) # residual pool, lowest first
|
|
531
|
+
n_pool = len(pool)
|
|
532
|
+
pool_sd = pool.std()
|
|
533
|
+
cp = {"pool": pool, "n_pool": n_pool, "pool_sd": pool_sd}
|
|
534
|
+
if pool_sd == 0.0:
|
|
535
|
+
return cp # a constant pool carries no noise
|
|
536
|
+
|
|
537
|
+
# Mean and population variance of the residuals kept by cut k (the pool without its k lowest values), for
|
|
538
|
+
# every k, accumulated from the top of the pool with Welford's recurrence so that no large sums are
|
|
539
|
+
# subtracted from each other.
|
|
540
|
+
kept_mean = np.empty(n_pool)
|
|
541
|
+
kept_var = np.empty(n_pool)
|
|
542
|
+
m, s2, count = 0.0, 0.0, 0
|
|
543
|
+
for k in range(n_pool - 1, -1, -1):
|
|
544
|
+
x = pool[k]
|
|
545
|
+
count += 1
|
|
546
|
+
delta = x - m
|
|
547
|
+
m += delta / count
|
|
548
|
+
s2 += delta * (x - m)
|
|
549
|
+
kept_mean[k] = m
|
|
550
|
+
kept_var[k] = s2 / count
|
|
551
|
+
|
|
552
|
+
# Candidate cuts. Cut k drops the k lowest residuals, up to max_drop of the pool. A cut whose kept residuals
|
|
553
|
+
# are all equal has zero variance and cannot be rescaled, so it is not valid.
|
|
554
|
+
n_cuts = int(max_drop * n_pool) + 1
|
|
555
|
+
cuts = np.arange(n_cuts)
|
|
556
|
+
valid = cuts[(pool[:n_cuts] < pool[-1]) & (kept_var[:n_cuts] > 0.0)] # original cut indices
|
|
557
|
+
cp["valid"] = valid
|
|
558
|
+
cp["kept_mean"] = kept_mean[valid]
|
|
559
|
+
cp["kept_sd"] = np.sqrt(kept_var[valid])
|
|
560
|
+
cp["lowest_kept"] = (pool[valid] - cp["kept_mean"]) * pool_sd / cp["kept_sd"]
|
|
561
|
+
cp["top"] = np.maximum.accumulate(cp["lowest_kept"])
|
|
562
|
+
return cp
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def _cut_weights(cp, mu, weights, floor):
|
|
566
|
+
"""
|
|
567
|
+
The weights of the bounded draw step for one completed dataset. A row whose weight is above the largest weight
|
|
568
|
+
the pool can carry for it gets that largest weight, and the other weights are scaled up so that the squared sum
|
|
569
|
+
of the weights does not change. The check fails when even the largest weights of all the rows together cannot
|
|
570
|
+
carry that sum. The weights are then not used, because every row takes a nearby draw. mu and weights are float64.
|
|
571
|
+
|
|
572
|
+
Returns the weights, the rows whose weight was lowered, and whether the check failed.
|
|
573
|
+
"""
|
|
574
|
+
n = len(mu)
|
|
575
|
+
if cp["pool_sd"] == 0.0:
|
|
576
|
+
return weights, np.zeros(n, bool), False
|
|
577
|
+
|
|
578
|
+
room = mu - floor # distance from the row mean down to the floor
|
|
579
|
+
max_weight = room / -cp["lowest_kept"].max() * (1 - 1e-12)
|
|
580
|
+
target = np.sum(weights ** 2)
|
|
581
|
+
capacity = np.sum(max_weight ** 2)
|
|
582
|
+
if capacity < target * (1 - 1e-9):
|
|
583
|
+
return weights, np.zeros(n, bool), True
|
|
584
|
+
|
|
585
|
+
original = weights
|
|
586
|
+
lowered = np.zeros(n, bool)
|
|
587
|
+
while ((weights > max_weight) & ~lowered).any():
|
|
588
|
+
lowered |= weights > max_weight
|
|
589
|
+
if lowered.all():
|
|
590
|
+
weights = max_weight.copy() # every weight at its limit, the limits carry the target together
|
|
591
|
+
break
|
|
592
|
+
scale = np.sqrt((target - np.sum(max_weight[lowered] ** 2)) / np.sum(original[~lowered] ** 2))
|
|
593
|
+
weights = np.where(lowered, max_weight, original * scale)
|
|
594
|
+
|
|
595
|
+
if (weights > max_weight * (1 + 1e-9)).any():
|
|
596
|
+
raise RuntimeError("A weight exceeds the largest weight its row can carry.")
|
|
597
|
+
if abs(np.sum(weights ** 2) - target) > 1e-9 * target:
|
|
598
|
+
raise RuntimeError("The squared sum of the weights does not match the target.")
|
|
599
|
+
return weights, lowered, False
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def _cut_draws(cp, mu, weights, u, floor):
|
|
603
|
+
"""
|
|
604
|
+
One cut pool draw for one completed dataset, with its uniform numbers u given. Each row
|
|
605
|
+
takes the smallest valid cut that keeps its lowest draw at or above the floor. Returns the draws and the share
|
|
606
|
+
of the pool each row drops.
|
|
607
|
+
"""
|
|
608
|
+
if cp["pool_sd"] == 0.0:
|
|
609
|
+
return mu.copy(), np.zeros(len(mu))
|
|
610
|
+
room = mu - floor
|
|
611
|
+
pos = np.searchsorted(cp["top"], -room / weights)
|
|
612
|
+
cut = cp["valid"][pos] # original cut index, the number of residuals dropped
|
|
613
|
+
shift = cp["kept_mean"][pos]
|
|
614
|
+
stretch = cp["pool_sd"] / cp["kept_sd"][pos]
|
|
615
|
+
donor = cut + np.floor(u * (cp["n_pool"] - cut)).astype(int)
|
|
616
|
+
return mu + weights * (cp["pool"][donor] - shift) * stretch, cut / cp["n_pool"]
|
|
617
|
+
|
|
618
|
+
# =========================================================
|
|
619
|
+
# Nearby draws
|
|
620
|
+
# =========================================================
|
|
621
|
+
def _near_k(n_pool, k_min=K_MIN):
|
|
622
|
+
"""Number of neighbours of the nearby draws, n^(2/3) of the pool and at least k_min, never more than the pool."""
|
|
623
|
+
return int(min(n_pool, max(np.ceil(n_pool ** (2 / 3)), k_min)))
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def _nearby_draws(mu, y_pool, pred_pool, u, floor, k, chunk=256):
|
|
627
|
+
"""
|
|
628
|
+
Nearby draws (see the module docstring) for the rows with predicted means mu (above the floor) and uniform
|
|
629
|
+
numbers u. y_pool and pred_pool are the outcomes and the predicted means of the pool rows, in the same order. A
|
|
630
|
+
predicted mean of a pool row that sits on the bound is moved just above it, as for the rows to impute (_above),
|
|
631
|
+
so the division is always defined. Each row draws one of its k nearest pool rows, the one at place floor(u * k)
|
|
632
|
+
counted from the nearest. Returns the draws.
|
|
633
|
+
"""
|
|
634
|
+
mu = np.asarray(mu, dtype=np.float64)
|
|
635
|
+
y_pool = np.asarray(y_pool, dtype=np.float64)
|
|
636
|
+
pred_pool = _above(pred_pool, floor)
|
|
637
|
+
out = np.empty(len(mu))
|
|
638
|
+
for a in range(0, len(mu), chunk):
|
|
639
|
+
b = min(a + chunk, len(mu))
|
|
640
|
+
order = np.argsort(np.abs(pred_pool[None, :] - mu[a:b, None]), axis=1, kind="stable")[:, :k] # nearest first
|
|
641
|
+
j = order[np.arange(b - a), np.floor(u[a:b] * k).astype(int)] # the drawn neighbour
|
|
642
|
+
out[a:b] = floor + (mu[a:b] - floor) * (y_pool[j] - floor) / (pred_pool[j] - floor)
|
|
643
|
+
return out
|
|
644
|
+
|
|
645
|
+
# =========================================================
|
|
646
|
+
# The bounded draw step of one fit and its counts
|
|
647
|
+
# =========================================================
|
|
648
|
+
def _bounded_draws(mu, weights, pool, pred_pool, y_pool, reps, rng, floor, k_min=K_MIN):
|
|
649
|
+
"""
|
|
650
|
+
Draw step of bounded Multi Sigma for one fit. For each row to impute the lowest residuals are dropped from the
|
|
651
|
+
pool until no draw can fall below the floor, and the kept residuals are shifted and stretched back to mean zero
|
|
652
|
+
and to the SD of the full pool, so the row keeps its mean mu and the noise variance weights**2 * var(pool) of the
|
|
653
|
+
plain draw. Only cuts whose kept residuals have a positive SD are valid, and a cut drops at most half the pool. A
|
|
654
|
+
row that sits too close to the floor for any valid cut to carry its weight gets the largest weight the pool can
|
|
655
|
+
carry for it, and the other weights are scaled up so that sum(weights**2) does not change. If the residual pool
|
|
656
|
+
has zero variance every draw is the predicted mean. When the check fails (see the module docstring) every row
|
|
657
|
+
takes a nearby draw, with the same uniform numbers. pool is the centered residual pool, and pred_pool and y_pool
|
|
658
|
+
the predicted means and the outcomes of its rows, in the same order. pred_pool and y_pool are used only by the
|
|
659
|
+
nearby draws.
|
|
660
|
+
|
|
661
|
+
Returns a dict with the draws, the share of the pool dropped for each row, the rows whose weight was lowered,
|
|
662
|
+
whether the check failed and the number of neighbours k.
|
|
663
|
+
"""
|
|
664
|
+
mu = np.asarray(mu, dtype=np.float64)
|
|
665
|
+
weights = np.asarray(weights, dtype=np.float64)
|
|
666
|
+
resid = np.asarray(pool, dtype=np.float64)
|
|
667
|
+
floor = float(floor)
|
|
668
|
+
n = len(mu)
|
|
669
|
+
if not np.isfinite(mu).all() or not np.isfinite(weights).all() or not np.isfinite(resid).all():
|
|
670
|
+
raise ValueError("The predicted means, the weights and the residual pool must all be finite.")
|
|
671
|
+
if (mu <= floor).any():
|
|
672
|
+
raise ValueError("Every predicted mean must be above the floor.")
|
|
673
|
+
|
|
674
|
+
cp = _cut_pool(resid)
|
|
675
|
+
w, lowered, failed = _cut_weights(cp, mu, weights, floor)
|
|
676
|
+
k = _near_k(len(resid), k_min)
|
|
677
|
+
out = np.empty((n, reps))
|
|
678
|
+
share = np.zeros(n)
|
|
679
|
+
if cp["pool_sd"] == 0.0:
|
|
680
|
+
out[:] = mu[:, None] # a constant pool carries no noise, every draw is the predicted mean
|
|
681
|
+
else:
|
|
682
|
+
for r in range(reps):
|
|
683
|
+
u = rng.random(n)
|
|
684
|
+
if failed:
|
|
685
|
+
out[:, r] = _nearby_draws(mu, y_pool, pred_pool, u, floor, k)
|
|
686
|
+
else:
|
|
687
|
+
out[:, r], share = _cut_draws(cp, mu, w, u, floor)
|
|
688
|
+
return dict(draws=out, share=share, lowered=lowered, failed=failed, k=k)
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
def _counts(results):
|
|
692
|
+
"""
|
|
693
|
+
The counts of the bounded draw step over the fits, for .attrs of the imputations.
|
|
694
|
+
|
|
695
|
+
fits_check_failed fits whose check failed (with bootstrap refits, one fit per imputation)
|
|
696
|
+
mean_share_of_pool_dropped the share of the pool each row drops, averaged over the rows and over the fits
|
|
697
|
+
whose check passed
|
|
698
|
+
rows_with_lowered_weight the average number of rows whose weight was lowered, over the fits
|
|
699
|
+
whose check passed
|
|
700
|
+
values_drawn_nearby values drawn nearby, rows times imputations
|
|
701
|
+
values_not_imputed of those, values that are missing or not finite
|
|
702
|
+
"""
|
|
703
|
+
passed = [d for d in results if not d["failed"]]
|
|
704
|
+
failed = [d for d in results if d["failed"]]
|
|
705
|
+
return {"fits_check_failed": len(failed),
|
|
706
|
+
"mean_share_of_pool_dropped": float(np.mean([d["share"].mean() for d in passed])) if passed else float("nan"),
|
|
707
|
+
"rows_with_lowered_weight": float(np.mean([d["lowered"].sum() for d in passed])) if passed else float("nan"),
|
|
708
|
+
"values_drawn_nearby": int(sum(d["draws"].size for d in failed)),
|
|
709
|
+
"values_not_imputed": int(sum((~np.isfinite(d["draws"])).sum() for d in failed))}
|
|
710
|
+
|
|
711
|
+
# =========================================================
|
|
712
|
+
# Multi Sigma for one column
|
|
713
|
+
# =========================================================
|
|
714
|
+
def _frame(blocks, target_df):
|
|
715
|
+
"""The imputations side by side, one column each."""
|
|
716
|
+
out = np.hstack(blocks)
|
|
717
|
+
return pd.DataFrame(out, index=target_df.index, columns=[f"imp_{i+1}" for i in range(out.shape[1])])
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
def impute_column(
|
|
721
|
+
base_df,
|
|
722
|
+
target_df,
|
|
723
|
+
y_col,
|
|
724
|
+
x_cols,
|
|
725
|
+
bounded=True,
|
|
726
|
+
lower_bound=0.0,
|
|
727
|
+
normalization="self",
|
|
728
|
+
reps=20,
|
|
729
|
+
seed=0,
|
|
730
|
+
mean_epochs=1000,
|
|
731
|
+
sigma_epochs=1000,
|
|
732
|
+
batch_size=256,
|
|
733
|
+
patience=20,
|
|
734
|
+
model_draws="bootstrap",
|
|
735
|
+
refit_epochs=5,
|
|
736
|
+
draw_seed=None,
|
|
737
|
+
k_min=K_MIN,
|
|
738
|
+
min_records=MIN_RECORDS,
|
|
739
|
+
):
|
|
740
|
+
"""
|
|
741
|
+
Multi Sigma imputation of one column. The outcome y_col is imputed for the prediction records (the rows of
|
|
742
|
+
target_df) from the training data (the rows of base_df where y_col is observed) and the predictors x_cols.
|
|
743
|
+
multi_sigma calls this once for every column to impute.
|
|
744
|
+
|
|
745
|
+
bounded, lower_bound and normalization choose the method (see the module docstring). The default is MS-SN with
|
|
746
|
+
the bound at zero.
|
|
747
|
+
|
|
748
|
+
reps is the number of imputations. Each comes from its own fit, made as model_draws says, with refit_epochs
|
|
749
|
+
passes for a bootstrap refit. mean_epochs, sigma_epochs, batch_size and patience are the training settings of the
|
|
750
|
+
two networks on the observed rows. seed fixes the networks and the bootstrap samples, and draw_seed the random
|
|
751
|
+
numbers of the draws (seed when it is not given). k_min is the smallest number of neighbours of the nearby draws.
|
|
752
|
+
|
|
753
|
+
The predictors may have missing values, in the training data and in the prediction records (see Missing values
|
|
754
|
+
in the predictors in the module docstring). min_records is the number of records that separates not missing much
|
|
755
|
+
from missing a lot in the five cases there.
|
|
756
|
+
|
|
757
|
+
Returns the imputations of the prediction records, one column per imputation, and their predicted means from the
|
|
758
|
+
full-data fit. The imputations carry in .attrs the number of refits trained again on a new bootstrap sample
|
|
759
|
+
(refits_redrawn) and mean_squared_weight, with a bound the counts of _counts, and, when a predictor has missing
|
|
760
|
+
values, what was done with each such predictor (predictors).
|
|
761
|
+
"""
|
|
762
|
+
if normalization not in NORMALIZATIONS:
|
|
763
|
+
raise ValueError(f"normalization must be one of {NORMALIZATIONS}.")
|
|
764
|
+
if model_draws not in MODEL_DRAWS:
|
|
765
|
+
raise ValueError(f"model_draws must be one of {MODEL_DRAWS}.")
|
|
766
|
+
if reps < 1:
|
|
767
|
+
raise ValueError("reps must be positive.")
|
|
768
|
+
if min_records < 1:
|
|
769
|
+
raise ValueError("min_records must be positive.")
|
|
770
|
+
# "none" reuses one fit for every imputation, the others fit once per imputation
|
|
771
|
+
n_fits, per_fit = (1, reps) if model_draws == "none" else (reps, 1)
|
|
772
|
+
|
|
773
|
+
y, Xb, Xt, predictors = _prepare(base_df, target_df, y_col, x_cols, min_records)
|
|
774
|
+
dropped = [f"{name} ({d['action'][len('dropped, '):]})" for name, d in predictors.items()
|
|
775
|
+
if d["action"].startswith("dropped")]
|
|
776
|
+
if dropped:
|
|
777
|
+
warnings.warn(f"Predictors dropped in the imputation of {y_col}, each with its reason. "
|
|
778
|
+
+ ", ".join(dropped) + ".")
|
|
779
|
+
floor = float(lower_bound)
|
|
780
|
+
if bounded and (y < floor).any():
|
|
781
|
+
raise ValueError(
|
|
782
|
+
f"{int((y < floor).sum())} observed values of {y_col} are below the lower bound {floor:g}. Set lower_bound "
|
|
783
|
+
f"to the lowest value {y_col} can take, or set bounded=False if it has no lower bound. In multi_sigma, "
|
|
784
|
+
"bounded and lower_bound can be a dictionary with a value for each column.")
|
|
785
|
+
# With a bound the mean network gives the bound plus a softplus. Without one its output is linear.
|
|
786
|
+
activation = "softplus" if bounded else None
|
|
787
|
+
|
|
788
|
+
full = _fit_full(Xb, Xt, y, seed, mean_epochs, sigma_epochs, batch_size, patience, activation, floor)
|
|
789
|
+
rng_model = np.random.default_rng([seed, 1]) # bootstrap samples or coefficient draws
|
|
790
|
+
rng = np.random.default_rng(seed if draw_seed is None else draw_seed)
|
|
791
|
+
draws, squared, redrawn = [], [], []
|
|
792
|
+
for mu_t, pool, sigma_t, sigma_pool, pred_pool, y_pool in _fits(full, activation, Xb, Xt, y, seed, batch_size,
|
|
793
|
+
model_draws, n_fits, refit_epochs, rng_model,
|
|
794
|
+
redrawn):
|
|
795
|
+
if normalization == "self":
|
|
796
|
+
w = _self_normalized(sigma_t)
|
|
797
|
+
else:
|
|
798
|
+
w = _observed_normalized(sigma_t, sigma_pool)
|
|
799
|
+
if bounded:
|
|
800
|
+
draws.append(_bounded_draws(_above(mu_t, floor), w, pool, pred_pool, y_pool, per_fit, rng, floor, k_min))
|
|
801
|
+
else:
|
|
802
|
+
draws.append(_plain_draws(mu_t, w, pool, per_fit, rng))
|
|
803
|
+
squared.append(float(np.mean(np.asarray(w, dtype=np.float64) ** 2)))
|
|
804
|
+
|
|
805
|
+
if bounded:
|
|
806
|
+
imps = _frame([d["draws"] for d in draws], target_df)
|
|
807
|
+
imps.attrs.update(_counts(draws))
|
|
808
|
+
else:
|
|
809
|
+
imps = _frame(draws, target_df)
|
|
810
|
+
imps.attrs["refits_redrawn"] = len(redrawn)
|
|
811
|
+
imps.attrs["mean_squared_weight"] = float(np.mean(squared))
|
|
812
|
+
if predictors:
|
|
813
|
+
imps.attrs["predictors"] = predictors
|
|
814
|
+
return imps, full[4]
|
|
815
|
+
|
|
816
|
+
# =========================================================
|
|
817
|
+
# Multi Sigma, the function to call
|
|
818
|
+
# =========================================================
|
|
819
|
+
class Completed(list):
|
|
820
|
+
"""The completed data, one item per imputation. info holds, for every imputed column, what was reported for it."""
|
|
821
|
+
info = None
|
|
822
|
+
|
|
823
|
+
|
|
824
|
+
def _table(data, what):
|
|
825
|
+
"""A data frame from a data frame or from a NumPy array, whose columns are then named by their positions."""
|
|
826
|
+
if isinstance(data, np.ndarray) and data.ndim == 2:
|
|
827
|
+
data = pd.DataFrame(data)
|
|
828
|
+
if not isinstance(data, pd.DataFrame):
|
|
829
|
+
raise TypeError(f"{what} must be a pandas data frame or a NumPy array with rows and columns.")
|
|
830
|
+
if not data.columns.is_unique:
|
|
831
|
+
raise ValueError(f"The column names of {what} must all be different.")
|
|
832
|
+
return data
|
|
833
|
+
|
|
834
|
+
|
|
835
|
+
def _columns_of_y(y, n_rows):
|
|
836
|
+
"""
|
|
837
|
+
The column or columns passed as y, as a data frame. A column without a name is called y, and the columns of an
|
|
838
|
+
array are called y0, y1 and so on.
|
|
839
|
+
"""
|
|
840
|
+
if isinstance(y, pd.Series):
|
|
841
|
+
Y = y.to_frame("y" if y.name is None else y.name)
|
|
842
|
+
elif isinstance(y, np.ndarray) and y.ndim == 1:
|
|
843
|
+
Y = pd.DataFrame({"y": y})
|
|
844
|
+
elif isinstance(y, np.ndarray) and y.ndim == 2:
|
|
845
|
+
Y = pd.DataFrame(y, columns=[f"y{k}" for k in range(y.shape[1])])
|
|
846
|
+
else:
|
|
847
|
+
Y = _table(y, "y")
|
|
848
|
+
if len(Y) != n_rows:
|
|
849
|
+
raise ValueError("y must have one row for every row of the data.")
|
|
850
|
+
return Y
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
def _names(value):
|
|
854
|
+
"""A name or a list of names, as a list."""
|
|
855
|
+
return list(value) if isinstance(value, (list, tuple, pd.Index)) else [value]
|
|
856
|
+
|
|
857
|
+
|
|
858
|
+
def _listed(names):
|
|
859
|
+
return ", ".join(str(n) for n in names)
|
|
860
|
+
|
|
861
|
+
|
|
862
|
+
def _not_continuous(column):
|
|
863
|
+
"""Why a column is not continuous, or None when it is (numbers with more than MIN_DIFFERENT_VALUES different values)."""
|
|
864
|
+
if not pd.api.types.is_numeric_dtype(column):
|
|
865
|
+
return "it does not hold numbers"
|
|
866
|
+
different = int(column.nunique()) # missing values are not counted
|
|
867
|
+
if different <= MIN_DIFFERENT_VALUES:
|
|
868
|
+
return f"it has only {different} different values"
|
|
869
|
+
return None
|
|
870
|
+
|
|
871
|
+
|
|
872
|
+
def _of(setting, column, default):
|
|
873
|
+
"""The value of a setting for one column. A setting is one value for every column or a dictionary by column."""
|
|
874
|
+
return setting.get(column, default) if isinstance(setting, dict) else setting
|
|
875
|
+
|
|
876
|
+
|
|
877
|
+
def multi_sigma(
|
|
878
|
+
data,
|
|
879
|
+
y,
|
|
880
|
+
x=None,
|
|
881
|
+
bounded=True,
|
|
882
|
+
lower_bound=0.0,
|
|
883
|
+
normalization="self",
|
|
884
|
+
reps=20,
|
|
885
|
+
seed=0,
|
|
886
|
+
mean_epochs=1000,
|
|
887
|
+
sigma_epochs=1000,
|
|
888
|
+
batch_size=256,
|
|
889
|
+
patience=20,
|
|
890
|
+
model_draws="bootstrap",
|
|
891
|
+
refit_epochs=5,
|
|
892
|
+
draw_seed=None,
|
|
893
|
+
k_min=K_MIN,
|
|
894
|
+
min_records=MIN_RECORDS,
|
|
895
|
+
):
|
|
896
|
+
"""
|
|
897
|
+
Multi Sigma imputation of the missing values of one or more continuous columns (see How to call it in the module
|
|
898
|
+
docstring).
|
|
899
|
+
|
|
900
|
+
data is a data frame or a NumPy array. y says what to impute. A name imputes that column of data, a list of names
|
|
901
|
+
imputes each of them, and "all" imputes every continuous column of data that has missing values. y can also be
|
|
902
|
+
the column itself (a pandas Series or a NumPy array) or several columns (a data frame or an array), and data then
|
|
903
|
+
holds only the predictors. x lists the predictors. Without it, every other column of data is a predictor.
|
|
904
|
+
|
|
905
|
+
bounded, lower_bound and normalization choose the method. bounded and lower_bound are one value for every column
|
|
906
|
+
or a dictionary with a value for each column. The other settings are those of impute_column and are the same for
|
|
907
|
+
every column.
|
|
908
|
+
|
|
909
|
+
Returns a list with one item per imputation, each the data (or the y that was passed) with the missing values of
|
|
910
|
+
the imputed columns filled. Its .info holds, for every imputed column, what impute_column reports, the number of
|
|
911
|
+
records imputed (records_imputed) and their predicted means (predicted_mean).
|
|
912
|
+
"""
|
|
913
|
+
table = _table(data, "the data")
|
|
914
|
+
y_is_data = isinstance(y, (pd.Series, pd.DataFrame, np.ndarray))
|
|
915
|
+
if y_is_data:
|
|
916
|
+
# y is the column itself, or several columns. The data hold only the predictors.
|
|
917
|
+
Y = _columns_of_y(y, len(table))
|
|
918
|
+
columns = list(Y.columns)
|
|
919
|
+
same = [c for c in columns if c in table.columns]
|
|
920
|
+
if same:
|
|
921
|
+
raise ValueError(f"y and the data both have a column called {_listed(same)}. When y is passed as data, "
|
|
922
|
+
"the data hold only the predictors.")
|
|
923
|
+
work = table.copy()
|
|
924
|
+
for c in columns:
|
|
925
|
+
work[c] = Y[c].to_numpy()
|
|
926
|
+
else:
|
|
927
|
+
# y names the columns of the data to impute
|
|
928
|
+
work = table
|
|
929
|
+
if isinstance(y, str) and y == "all":
|
|
930
|
+
columns = [c for c in table.columns if table[c].isna().any()]
|
|
931
|
+
if not columns:
|
|
932
|
+
raise ValueError("No column of the data has a missing value, so there is nothing to impute.")
|
|
933
|
+
else:
|
|
934
|
+
columns = _names(y)
|
|
935
|
+
unknown = [c for c in columns if c not in table.columns]
|
|
936
|
+
if unknown:
|
|
937
|
+
raise ValueError(f"y names what is not a column of the data, {_listed(unknown)}. A column passed as data "
|
|
938
|
+
"must be a pandas object or a NumPy array.")
|
|
939
|
+
if len(set(columns)) != len(columns):
|
|
940
|
+
raise ValueError("y names a column twice.")
|
|
941
|
+
candidates = list(table.columns) if x is None else _names(x) # the predictors, before the column itself is taken out
|
|
942
|
+
unknown = [c for c in candidates if c not in table.columns]
|
|
943
|
+
if unknown:
|
|
944
|
+
raise ValueError(f"x names what is not a column of the data, {_listed(unknown)}.")
|
|
945
|
+
for name, setting in (("bounded", bounded), ("lower_bound", lower_bound)):
|
|
946
|
+
if isinstance(setting, dict) and [c for c in setting if c not in columns]:
|
|
947
|
+
raise ValueError(f"{name} has a value for {_listed([c for c in setting if c not in columns])}, which is not imputed.")
|
|
948
|
+
|
|
949
|
+
# A named column without a missing value is skipped. Every column that is imputed must be continuous.
|
|
950
|
+
todo = [c for c in columns if work[c].isna().any()]
|
|
951
|
+
for c in columns:
|
|
952
|
+
if c not in todo:
|
|
953
|
+
warnings.warn(f"The column {c} has no missing value, so nothing is imputed in it.")
|
|
954
|
+
reasons = {c: _not_continuous(work[c]) for c in todo}
|
|
955
|
+
reasons = [f"{c} ({why})" for c, why in reasons.items() if why]
|
|
956
|
+
if reasons:
|
|
957
|
+
raise ValueError(
|
|
958
|
+
f"A column to impute must be continuous, which means that it holds numbers and has more than "
|
|
959
|
+
f"{MIN_DIFFERENT_VALUES} different values. Not continuous, {', '.join(reasons)}."
|
|
960
|
+
+ (' With y="all" every column that has missing values is imputed. To leave a column out, name the '
|
|
961
|
+
'columns to impute in y.' if isinstance(y, str) and y == "all" else ""))
|
|
962
|
+
text = [p for p in candidates if not pd.api.types.is_numeric_dtype(work[p])]
|
|
963
|
+
if todo and text:
|
|
964
|
+
raise ValueError(f"A predictor must hold numbers. These do not, {_listed(text)}. Turn each into 0/1 columns "
|
|
965
|
+
"first, or leave it out by listing the predictors in x.")
|
|
966
|
+
if todo:
|
|
967
|
+
work = work[list(dict.fromkeys(todo + candidates))].astype("float64")
|
|
968
|
+
|
|
969
|
+
info, filled = {}, {}
|
|
970
|
+
for c in todo:
|
|
971
|
+
missing = work[c].isna().to_numpy() # the prediction records of this column
|
|
972
|
+
predictors = [p for p in candidates if p != c]
|
|
973
|
+
if not predictors:
|
|
974
|
+
raise ValueError(f"The column {c} has no predictor.")
|
|
975
|
+
if len(columns) == 1:
|
|
976
|
+
column_draw_seed = draw_seed
|
|
977
|
+
else:
|
|
978
|
+
# every column gets its own random numbers for the draws, made from draw_seed and the name of the column
|
|
979
|
+
given = seed if draw_seed is None else draw_seed
|
|
980
|
+
column_draw_seed = [*np.atleast_1d(given).tolist(), zlib.crc32(str(c).encode("utf8"))]
|
|
981
|
+
imps, mu = impute_column(work, work.loc[missing], c, predictors, bounded=_of(bounded, c, True),
|
|
982
|
+
lower_bound=_of(lower_bound, c, 0.0), normalization=normalization, reps=reps,
|
|
983
|
+
seed=seed, mean_epochs=mean_epochs, sigma_epochs=sigma_epochs, batch_size=batch_size,
|
|
984
|
+
patience=patience, model_draws=model_draws, refit_epochs=refit_epochs,
|
|
985
|
+
draw_seed=column_draw_seed, k_min=k_min, min_records=min_records)
|
|
986
|
+
filled[c] = (np.flatnonzero(missing), imps.to_numpy())
|
|
987
|
+
info[c] = dict(imps.attrs, records_imputed=int(missing.sum()),
|
|
988
|
+
predicted_mean=pd.Series(np.asarray(mu), index=work.index[missing], name=c))
|
|
989
|
+
|
|
990
|
+
out = Completed()
|
|
991
|
+
for r in range(reps):
|
|
992
|
+
done = (Y if y_is_data else table).copy()
|
|
993
|
+
for c, (rows, values) in filled.items():
|
|
994
|
+
column = work[c].to_numpy(copy=True)
|
|
995
|
+
column[rows] = values[:, r]
|
|
996
|
+
done[c] = column
|
|
997
|
+
if isinstance(y, pd.Series):
|
|
998
|
+
done = done.iloc[:, 0].rename(y.name)
|
|
999
|
+
elif isinstance(y, np.ndarray):
|
|
1000
|
+
done = done.to_numpy()[:, 0] if y.ndim == 1 else done.to_numpy()
|
|
1001
|
+
elif not y_is_data and isinstance(data, np.ndarray):
|
|
1002
|
+
done = done.to_numpy()
|
|
1003
|
+
out.append(done)
|
|
1004
|
+
out.info = info
|
|
1005
|
+
return out
|