sgci 0.2.0__tar.gz
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.
- sgci-0.2.0/LICENSE +15 -0
- sgci-0.2.0/MANIFEST.in +5 -0
- sgci-0.2.0/NOTICE +7 -0
- sgci-0.2.0/PKG-INFO +122 -0
- sgci-0.2.0/README.md +97 -0
- sgci-0.2.0/docs/PAPER_API.md +25 -0
- sgci-0.2.0/docs/QUICKSTART_CN.md +84 -0
- sgci-0.2.0/examples/activity.py +30 -0
- sgci-0.2.0/examples/activity_decisions.py +27 -0
- sgci-0.2.0/examples/custom_sensors.py +35 -0
- sgci-0.2.0/examples/forecast.py +26 -0
- sgci-0.2.0/pyproject.toml +40 -0
- sgci-0.2.0/setup.cfg +4 -0
- sgci-0.2.0/src/sgci/__init__.py +20 -0
- sgci-0.2.0/src/sgci/__main__.py +4 -0
- sgci-0.2.0/src/sgci/_files.py +20 -0
- sgci-0.2.0/src/sgci/_version.py +1 -0
- sgci-0.2.0/src/sgci/activity.py +187 -0
- sgci-0.2.0/src/sgci/activity_workflow.py +247 -0
- sgci-0.2.0/src/sgci/classification.py +172 -0
- sgci-0.2.0/src/sgci/cli.py +222 -0
- sgci-0.2.0/src/sgci/comparison.py +231 -0
- sgci-0.2.0/src/sgci/diagnostics.py +87 -0
- sgci-0.2.0/src/sgci/dynamics.py +102 -0
- sgci-0.2.0/src/sgci/forecasting/__init__.py +10 -0
- sgci-0.2.0/src/sgci/forecasting/data.py +181 -0
- sgci-0.2.0/src/sgci/forecasting/scoring.py +143 -0
- sgci-0.2.0/src/sgci/forecasting/training.py +101 -0
- sgci-0.2.0/src/sgci/graph.py +49 -0
- sgci-0.2.0/src/sgci/invariance.py +125 -0
- sgci-0.2.0/src/sgci/response.py +158 -0
- sgci-0.2.0/src/sgci/selection.py +111 -0
- sgci-0.2.0/src/sgci/sensor.py +102 -0
- sgci-0.2.0/src/sgci.egg-info/PKG-INFO +122 -0
- sgci-0.2.0/src/sgci.egg-info/SOURCES.txt +47 -0
- sgci-0.2.0/src/sgci.egg-info/dependency_links.txt +1 -0
- sgci-0.2.0/src/sgci.egg-info/entry_points.txt +2 -0
- sgci-0.2.0/src/sgci.egg-info/requires.txt +7 -0
- sgci-0.2.0/src/sgci.egg-info/top_level.txt +1 -0
- sgci-0.2.0/tests/test_activity.py +42 -0
- sgci-0.2.0/tests/test_activity_workflow.py +117 -0
- sgci-0.2.0/tests/test_cli.py +23 -0
- sgci-0.2.0/tests/test_comparison.py +110 -0
- sgci-0.2.0/tests/test_custom_forecast.py +88 -0
- sgci-0.2.0/tests/test_field_cli.py +126 -0
- sgci-0.2.0/tests/test_forecasting.py +61 -0
- sgci-0.2.0/tests/test_response_ranking.py +22 -0
- sgci-0.2.0/tests/test_science.py +152 -0
- sgci-0.2.0/tests/test_sensor.py +49 -0
sgci-0.2.0/LICENSE
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ziran Peng et al.
|
|
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.
|
sgci-0.2.0/MANIFEST.in
ADDED
sgci-0.2.0/NOTICE
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
SGCI — Structure-Guided Counterfactual Invariance for Sequential Pattern Recognition
|
|
2
|
+
Copyright (c) 2026 Ziran Peng et al. Distributed under the enclosed MIT License.
|
|
3
|
+
The lagged graph and coordinate transition derive from the authors' archived
|
|
4
|
+
implementation (Zenodo 21696299, Git tag v0.0.2). The matched HAR encoder
|
|
5
|
+
and the one-step forecast protocol are adapted from the authors' research code.
|
|
6
|
+
The sgci Python distribution has its own version and public interface.
|
|
7
|
+
No raw datasets, trained checkpoints or experiment outputs are included.
|
sgci-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sgci
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Structure-guided counterfactual invariance for sequential classification and forecasting
|
|
5
|
+
Author: Ziran Peng, Siyuan Xia, Huiqin Xiao
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/anonymous-rl-lab/SGCI
|
|
8
|
+
Project-URL: Historical software archive, https://doi.org/10.5281/zenodo.21696299
|
|
9
|
+
Keywords: time series,counterfactual invariance,forecasting,PyTorch,pattern recognition
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
License-File: NOTICE
|
|
18
|
+
Requires-Dist: torch>=2.1
|
|
19
|
+
Requires-Dist: numpy>=1.24
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
22
|
+
Requires-Dist: build>=1; extra == "dev"
|
|
23
|
+
Requires-Dist: twine>=5; extra == "dev"
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# SGCI
|
|
27
|
+
|
|
28
|
+
**Structure-Guided Counterfactual Invariance for Sequential Pattern Recognition**
|
|
29
|
+
Ziran Peng, Siyuan Xia and Huiqin Xiao. Corresponding authors are Ziran Peng and Huiqin Xiao. Contact Ziran Peng at pengziran@hut.edu.cn.
|
|
30
|
+
|
|
31
|
+
SGCI helps you test whether a sequence model depends on particular inputs and whether learning which inputs to protect improves held-out decisions. After warm-up, the fixed learned policy protects each target's highest-ranked input directions. On eligible directions, training penalizes disagreement between responses to two independently drawn replacements. A fixed random policy protects the same number of directions per target and provides a matched control.
|
|
32
|
+
|
|
33
|
+
## Install and try it
|
|
34
|
+
|
|
35
|
+
Run these commands at the root of the unpacked release ZIP. If you downloaded only the wheel, use its local path in the install command. SGCI 0.2.0 requires Python 3.10 or later, NumPy 1.24 or later and PyTorch 2.1 or later. The command can reuse compatible dependencies in the active Python environment.
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
python -m pip install ./dist/sgci-0.2.0-py3-none-any.whl
|
|
39
|
+
python -m sgci --version
|
|
40
|
+
python -m sgci demo
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
The demo runs a single CPU fit on generated data and prints intact and permuted test MSE. To try a complete paired comparison without supplying any data, run these bundled examples in the same environment. The source distribution can also be installed directly with `python -m pip install ./dist/sgci-0.2.0.tar.gz`.
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
python examples/custom_sensors.py
|
|
47
|
+
python examples/activity_decisions.py
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Choose a workflow
|
|
51
|
+
|
|
52
|
+
| Your question | Command | What to read or reuse |
|
|
53
|
+
|---|---|---|
|
|
54
|
+
| What comes next for my sensors? | `fit-forecast`, then `predict forecast` | A reusable model with channel scaling and a NumPy array of next-step target estimates in original units |
|
|
55
|
+
| Does learned selection lower the error? | `compare-forecast` | Paired intact and shifted MSE changes overall, by seed, by test sequence and optionally by participant |
|
|
56
|
+
| Which activity occurred in a completed window? | `classify`, then `predict activity` | A reusable classifier and one original class label per window |
|
|
57
|
+
| Which decisions did learned selection fix or break? | `compare-activity` for new fits, or `errors` for existing predictions | Counts and zero-based test-row indices of corrected and introduced errors |
|
|
58
|
+
| Which measured inputs change the model's response? | `scan` | Gate and replacement-response ranks for every source of each requested target |
|
|
59
|
+
| Which directions may be probed during training? | `mask` | Eligible source indices per target from a warm-up gate matrix |
|
|
60
|
+
|
|
61
|
+
### Forecast your own observed channels
|
|
62
|
+
|
|
63
|
+
For deployment, supply one finite numeric training array in original units with shape `[sequences, time steps, channels]`. For evaluation, add an independent test array with the same channels. Each sequence must have at least two observations. Keep units and channel order consistent. Split recordings or participants before creating overlapping windows if they are intended to be held out. Use at least two test sequences for a permutation comparison. Training uses adjacent observations within each sequence and estimates its channel scales from the training split.
|
|
64
|
+
|
|
65
|
+
To deploy a one-step predictor, train directly on your measured sequences and select the output channels. Omitting `--targets` returns every measured channel. This route uses only the training file.
|
|
66
|
+
|
|
67
|
+
```sh
|
|
68
|
+
python -m sgci fit-forecast train.npy --targets 0 --model sensor.pt
|
|
69
|
+
python -m sgci predict forecast sensor.pt current.npy --predictions next.npy
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
To evaluate input dependence, choose which observed channels to perturb. In the following example there are four measured channels. The model learns transitions for all four. Channel 0 is the next-step outcome, and channels 2 and 3 move together between test sequences in the offline stress test. Channel 1 remains in place. Targets and shifted inputs must be nonempty, disjoint sets of zero-based channel indices. All filenames in the following commands refer to your own arrays.
|
|
73
|
+
|
|
74
|
+
```sh
|
|
75
|
+
python -m sgci forecast train.npy test.npy --dataset custom --targets 0 --shift 2,3
|
|
76
|
+
python -m sgci compare-forecast train.npy test.npy --dataset custom --targets 0 --shift 2,3 --seeds 0,1,2 --groups test_people.npy --report forecast.json
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
`current.npy` contains one or more observed states with shape `[..., C]`. The output keeps those leading dimensions and orders its last axis as specified in `--targets`. Scoring uses standardized target units. In `forecast.json`, a positive `reduction_mse` means lower error for the fixed learned policy (comparator MSE minus learned MSE). Percentage reductions are calculated within each seed and averaged. A zero comparator MSE makes the corresponding aggregate percentage unavailable. `permutation_penalty` measures the change from intact to shifted MSE. By default each sequence has equal weight. Providing one participant ID per test sequence weights participant means equally. Use `case_summary.by_sequence.shifted` for counts and the most improved or worsened row. The paired comparison fits two models per seed with matched training budgets and shared evaluation permutations. Cross-sequence replacement stresses input dependence offline; the deployed predictor only consumes the current measurement.
|
|
80
|
+
|
|
81
|
+
### Classify windows and inspect changed decisions
|
|
82
|
+
|
|
83
|
+
Use raw windows shaped `[N, T, C]` and a vector of `N` integer IDs or nonempty Unicode string labels. The training split must include at least two classes. The classifier fits its scaler and label vocabulary on training windows and predicts a single class for each completed window. Use the same label type and channel order at evaluation. CLI input files must be ordinary NumPy arrays readable with `allow_pickle=False`.
|
|
84
|
+
|
|
85
|
+
```sh
|
|
86
|
+
python -m sgci classify train_windows.npy train_labels.npy --model activity.pt
|
|
87
|
+
python -m sgci predict activity activity.pt test_windows.npy --predictions labels.npy
|
|
88
|
+
python -m sgci compare-activity train_windows.npy train_labels.npy test_windows.npy test_labels.npy --groups test_people.npy --report decisions.json
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`corrected` counts windows the reference got wrong and the learned policy got right. `introduced` counts the reverse. The net accuracy change in percentage points is `100 × (corrected − introduced) / N`. Both models can be wrong on the same window. The report keeps these rows as `both_wrong` and records their indices. For classification, `--groups` adds a breakdown by participant. Overall accuracy still weights each window equally. Group IDs describe a split you have already made.
|
|
92
|
+
|
|
93
|
+
If you already have two prediction files aligned to the same test rows, you can examine errors without fitting again.
|
|
94
|
+
|
|
95
|
+
```sh
|
|
96
|
+
python -m sgci errors test_labels.npy reference_labels.npy learned_labels.npy --report errors.json
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### Trace an input's influence
|
|
100
|
+
|
|
101
|
+
Use two raw matrices shaped `[rows, C]` with the saved sensor model. Take contexts from the held-out set and replacement values from training. Use the original channel units and ordering.
|
|
102
|
+
|
|
103
|
+
```sh
|
|
104
|
+
python -m sgci scan sensor.pt contexts.npy donors.npy --targets 0 --names target,context,aux1,aux2 --report directions.json
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Within each target, response rank 1 denotes the largest measured output variance when that source is replaced at unit gate. A positive `rank_gap` means the response ranked more strongly than the gate. This diagnoses sensitivity of the fitted mechanism to the chosen donor distribution. A predictive improvement needs a held-out comparison. Physical causality would require additional evidence.
|
|
108
|
+
|
|
109
|
+
## Reuse the implementation and check the paper protocols
|
|
110
|
+
|
|
111
|
+
| Need | Python entry points |
|
|
112
|
+
|---|---|
|
|
113
|
+
| Train on your own sensors and reuse the model | `fit_sensor_forecaster`, `SensorForecaster.load`, `predict_next`; for held-out stress tests use `prepare_custom_forecast_data`, `fit_forecaster` and `score_forecast` |
|
|
114
|
+
| Compare paired fits or existing forecast scores | `compare_forecasts`, `summarize_forecast_pairs` |
|
|
115
|
+
| Reuse classified labels and class probabilities | `fit_activity`, `ActivityPredictor.load`, `predict`, `predict_proba`. Probability column j corresponds to `predictor.classes[j]`. |
|
|
116
|
+
| Integrate with a PyTorch transition | `StructuredDynamics`, `ProbePolicy.fixed`, `invariance_penalty`, `measure_direction`, `rank_directions` |
|
|
117
|
+
|
|
118
|
+
For a custom training loop, capture `ProbePolicy.fixed(transition.edge_probabilities())` once at the end of warm-up. The matrix is indexed by source row and target column. Reuse the policy while continuing to fit transition parameters. The runnable scripts in `examples/` show the higher-level interfaces. The Chinese guide and manuscript-to-API map are in `docs/QUICKSTART_CN.md` and `docs/PAPER_API.md` in the source distribution.
|
|
119
|
+
|
|
120
|
+
The v40 Table 7 paths use `prepare_forecast_data(..., dataset="natops")` for 24 raw channels or `dataset="hapt"` for six. They construct the paper's three trailing auxiliary channels. HAPT aggregation uses held-out participant IDs. CPU replay of 70 archived forecast checkpoints reproduced the 275 result rows. The paired shifted-MSE reduction against fixed random selection was 21.55% on NATOPS and 51.38% on HAPT under those protocols. The paper's HAR selectivity measurement concerns changes in response variance at similar classification accuracy. Results on custom sensors or a different activity vocabulary need their own evaluation. The source distribution includes tests; from its unpacked root run `python -m pip install ".[dev]"` and `python -m pytest -q`.
|
|
121
|
+
|
|
122
|
+
The manuscript's numerical evidence archive supplies the original splits and checkpoints. The historical research code is archived on [Zenodo](https://doi.org/10.5281/zenodo.21696299) and [GitHub](https://github.com/anonymous-rl-lab/SGCI). License: MIT.
|
sgci-0.2.0/README.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# SGCI
|
|
2
|
+
|
|
3
|
+
**Structure-Guided Counterfactual Invariance for Sequential Pattern Recognition**
|
|
4
|
+
Ziran Peng, Siyuan Xia and Huiqin Xiao. Corresponding authors are Ziran Peng and Huiqin Xiao. Contact Ziran Peng at pengziran@hut.edu.cn.
|
|
5
|
+
|
|
6
|
+
SGCI helps you test whether a sequence model depends on particular inputs and whether learning which inputs to protect improves held-out decisions. After warm-up, the fixed learned policy protects each target's highest-ranked input directions. On eligible directions, training penalizes disagreement between responses to two independently drawn replacements. A fixed random policy protects the same number of directions per target and provides a matched control.
|
|
7
|
+
|
|
8
|
+
## Install and try it
|
|
9
|
+
|
|
10
|
+
Run these commands at the root of the unpacked release ZIP. If you downloaded only the wheel, use its local path in the install command. SGCI 0.2.0 requires Python 3.10 or later, NumPy 1.24 or later and PyTorch 2.1 or later. The command can reuse compatible dependencies in the active Python environment.
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
python -m pip install ./dist/sgci-0.2.0-py3-none-any.whl
|
|
14
|
+
python -m sgci --version
|
|
15
|
+
python -m sgci demo
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
The demo runs a single CPU fit on generated data and prints intact and permuted test MSE. To try a complete paired comparison without supplying any data, run these bundled examples in the same environment. The source distribution can also be installed directly with `python -m pip install ./dist/sgci-0.2.0.tar.gz`.
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
python examples/custom_sensors.py
|
|
22
|
+
python examples/activity_decisions.py
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Choose a workflow
|
|
26
|
+
|
|
27
|
+
| Your question | Command | What to read or reuse |
|
|
28
|
+
|---|---|---|
|
|
29
|
+
| What comes next for my sensors? | `fit-forecast`, then `predict forecast` | A reusable model with channel scaling and a NumPy array of next-step target estimates in original units |
|
|
30
|
+
| Does learned selection lower the error? | `compare-forecast` | Paired intact and shifted MSE changes overall, by seed, by test sequence and optionally by participant |
|
|
31
|
+
| Which activity occurred in a completed window? | `classify`, then `predict activity` | A reusable classifier and one original class label per window |
|
|
32
|
+
| Which decisions did learned selection fix or break? | `compare-activity` for new fits, or `errors` for existing predictions | Counts and zero-based test-row indices of corrected and introduced errors |
|
|
33
|
+
| Which measured inputs change the model's response? | `scan` | Gate and replacement-response ranks for every source of each requested target |
|
|
34
|
+
| Which directions may be probed during training? | `mask` | Eligible source indices per target from a warm-up gate matrix |
|
|
35
|
+
|
|
36
|
+
### Forecast your own observed channels
|
|
37
|
+
|
|
38
|
+
For deployment, supply one finite numeric training array in original units with shape `[sequences, time steps, channels]`. For evaluation, add an independent test array with the same channels. Each sequence must have at least two observations. Keep units and channel order consistent. Split recordings or participants before creating overlapping windows if they are intended to be held out. Use at least two test sequences for a permutation comparison. Training uses adjacent observations within each sequence and estimates its channel scales from the training split.
|
|
39
|
+
|
|
40
|
+
To deploy a one-step predictor, train directly on your measured sequences and select the output channels. Omitting `--targets` returns every measured channel. This route uses only the training file.
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
python -m sgci fit-forecast train.npy --targets 0 --model sensor.pt
|
|
44
|
+
python -m sgci predict forecast sensor.pt current.npy --predictions next.npy
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
To evaluate input dependence, choose which observed channels to perturb. In the following example there are four measured channels. The model learns transitions for all four. Channel 0 is the next-step outcome, and channels 2 and 3 move together between test sequences in the offline stress test. Channel 1 remains in place. Targets and shifted inputs must be nonempty, disjoint sets of zero-based channel indices. All filenames in the following commands refer to your own arrays.
|
|
48
|
+
|
|
49
|
+
```sh
|
|
50
|
+
python -m sgci forecast train.npy test.npy --dataset custom --targets 0 --shift 2,3
|
|
51
|
+
python -m sgci compare-forecast train.npy test.npy --dataset custom --targets 0 --shift 2,3 --seeds 0,1,2 --groups test_people.npy --report forecast.json
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`current.npy` contains one or more observed states with shape `[..., C]`. The output keeps those leading dimensions and orders its last axis as specified in `--targets`. Scoring uses standardized target units. In `forecast.json`, a positive `reduction_mse` means lower error for the fixed learned policy (comparator MSE minus learned MSE). Percentage reductions are calculated within each seed and averaged. A zero comparator MSE makes the corresponding aggregate percentage unavailable. `permutation_penalty` measures the change from intact to shifted MSE. By default each sequence has equal weight. Providing one participant ID per test sequence weights participant means equally. Use `case_summary.by_sequence.shifted` for counts and the most improved or worsened row. The paired comparison fits two models per seed with matched training budgets and shared evaluation permutations. Cross-sequence replacement stresses input dependence offline; the deployed predictor only consumes the current measurement.
|
|
55
|
+
|
|
56
|
+
### Classify windows and inspect changed decisions
|
|
57
|
+
|
|
58
|
+
Use raw windows shaped `[N, T, C]` and a vector of `N` integer IDs or nonempty Unicode string labels. The training split must include at least two classes. The classifier fits its scaler and label vocabulary on training windows and predicts a single class for each completed window. Use the same label type and channel order at evaluation. CLI input files must be ordinary NumPy arrays readable with `allow_pickle=False`.
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
python -m sgci classify train_windows.npy train_labels.npy --model activity.pt
|
|
62
|
+
python -m sgci predict activity activity.pt test_windows.npy --predictions labels.npy
|
|
63
|
+
python -m sgci compare-activity train_windows.npy train_labels.npy test_windows.npy test_labels.npy --groups test_people.npy --report decisions.json
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`corrected` counts windows the reference got wrong and the learned policy got right. `introduced` counts the reverse. The net accuracy change in percentage points is `100 × (corrected − introduced) / N`. Both models can be wrong on the same window. The report keeps these rows as `both_wrong` and records their indices. For classification, `--groups` adds a breakdown by participant. Overall accuracy still weights each window equally. Group IDs describe a split you have already made.
|
|
67
|
+
|
|
68
|
+
If you already have two prediction files aligned to the same test rows, you can examine errors without fitting again.
|
|
69
|
+
|
|
70
|
+
```sh
|
|
71
|
+
python -m sgci errors test_labels.npy reference_labels.npy learned_labels.npy --report errors.json
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Trace an input's influence
|
|
75
|
+
|
|
76
|
+
Use two raw matrices shaped `[rows, C]` with the saved sensor model. Take contexts from the held-out set and replacement values from training. Use the original channel units and ordering.
|
|
77
|
+
|
|
78
|
+
```sh
|
|
79
|
+
python -m sgci scan sensor.pt contexts.npy donors.npy --targets 0 --names target,context,aux1,aux2 --report directions.json
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Within each target, response rank 1 denotes the largest measured output variance when that source is replaced at unit gate. A positive `rank_gap` means the response ranked more strongly than the gate. This diagnoses sensitivity of the fitted mechanism to the chosen donor distribution. A predictive improvement needs a held-out comparison. Physical causality would require additional evidence.
|
|
83
|
+
|
|
84
|
+
## Reuse the implementation and check the paper protocols
|
|
85
|
+
|
|
86
|
+
| Need | Python entry points |
|
|
87
|
+
|---|---|
|
|
88
|
+
| Train on your own sensors and reuse the model | `fit_sensor_forecaster`, `SensorForecaster.load`, `predict_next`; for held-out stress tests use `prepare_custom_forecast_data`, `fit_forecaster` and `score_forecast` |
|
|
89
|
+
| Compare paired fits or existing forecast scores | `compare_forecasts`, `summarize_forecast_pairs` |
|
|
90
|
+
| Reuse classified labels and class probabilities | `fit_activity`, `ActivityPredictor.load`, `predict`, `predict_proba`. Probability column j corresponds to `predictor.classes[j]`. |
|
|
91
|
+
| Integrate with a PyTorch transition | `StructuredDynamics`, `ProbePolicy.fixed`, `invariance_penalty`, `measure_direction`, `rank_directions` |
|
|
92
|
+
|
|
93
|
+
For a custom training loop, capture `ProbePolicy.fixed(transition.edge_probabilities())` once at the end of warm-up. The matrix is indexed by source row and target column. Reuse the policy while continuing to fit transition parameters. The runnable scripts in `examples/` show the higher-level interfaces. The Chinese guide and manuscript-to-API map are in `docs/QUICKSTART_CN.md` and `docs/PAPER_API.md` in the source distribution.
|
|
94
|
+
|
|
95
|
+
The v40 Table 7 paths use `prepare_forecast_data(..., dataset="natops")` for 24 raw channels or `dataset="hapt"` for six. They construct the paper's three trailing auxiliary channels. HAPT aggregation uses held-out participant IDs. CPU replay of 70 archived forecast checkpoints reproduced the 275 result rows. The paired shifted-MSE reduction against fixed random selection was 21.55% on NATOPS and 51.38% on HAPT under those protocols. The paper's HAR selectivity measurement concerns changes in response variance at similar classification accuracy. Results on custom sensors or a different activity vocabulary need their own evaluation. The source distribution includes tests; from its unpacked root run `python -m pip install ".[dev]"` and `python -m pytest -q`.
|
|
96
|
+
|
|
97
|
+
The manuscript's numerical evidence archive supplies the original splits and checkpoints. The historical research code is archived on [Zenodo](https://doi.org/10.5281/zenodo.21696299) and [GitHub](https://github.com/anonymous-rl-lab/SGCI). License: MIT.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Paper-to-API map
|
|
2
|
+
|
|
3
|
+
| Manuscript result or protocol | Module and entry point | Quantity or behavior |
|
|
4
|
+
|---|---|---|
|
|
5
|
+
| §§2–3, lagged transition | `sgci.dynamics.StructuredDynamics` | One scalar nonlinear mechanism per target, weighted inputs, allowed self-lags; archived parameter names for checkpoint loading. |
|
|
6
|
+
| §3, eligibility at warm-up | `sgci.selection.ProbePolicy` | Fixed learned, dynamic learned, fixed random, reversed-half and all-direction controls. Stable sorting resolves equal gates by source index. |
|
|
7
|
+
| §3, loss | `sgci.invariance.invariance_penalty` | Two independent donor permutations, source gate set to one, detached live weights. Use `protocol="har"` for the matched HAR sampling order and `protocol="forecast"` for the forecast order. |
|
|
8
|
+
| §3.3, Lemma 1 | `sgci.response.paired_response_variance`, `sample_response_variance` | Half the squared norm of paired differences estimates total variance; sample variance uses divisor draws minus one. |
|
|
9
|
+
| §4, scalar bound | `sgci.response.sharp_mean_sensitivity` | Population standard deviation under a discrete reference law. For vector outputs use total response variance for the measured mechanism. |
|
|
10
|
+
| §§6–7, HAR selectivity | `sgci.response.measure_direction` | Supply matched contexts, gate matrix and donor indices to compare the same directed input. Aggregate as sum(weight × variance) / sum(weight). |
|
|
11
|
+
| §§6–7, completed-window classifier | `sgci.classification.activity_loss`, `fit_activity_classifier` | Task cross-entropy, smooth L1 latent dynamics, EMA target, sparsity, HAR probe cap and independent RNG streams. |
|
|
12
|
+
| Table 7, one-step forecasting | `sgci.forecasting` | Within-sequence transitions, training statistics, trailing proxy construction, fixed/random/dynamic controls and intact/permuted errors. |
|
|
13
|
+
| Table 7, aggregation | `score_forecast(..., groups=person_ids)` | HAPT weights participants equally; report method differences within each seed before averaging percentage reductions. |
|
|
14
|
+
|
|
15
|
+
## Questions supported by the application interfaces
|
|
16
|
+
|
|
17
|
+
| Practical question | Public entry point | Interpretation |
|
|
18
|
+
|---|---|---|
|
|
19
|
+
| What will the measured target read at the next step? | `fit_sensor_forecaster(train, target_channels=...)`, `SensorForecaster.predict_next` | Train on adjacent measurements within each sequence. Output values retain the original sensor units and target ordering. |
|
|
20
|
+
| Is learned selection helpful for these inputs? | `prepare_custom_forecast_data`, `compare_forecasts` | Compare matched fits with the same held-out trajectories and donor permutations. Inspect both the intact error and incremental permutation penalty. |
|
|
21
|
+
| Which held-out sequences and participants improved? | `summarize_forecast_pairs` | Combines the scores of already fitted pairs. Reports participant and row-level differences. Positive MSE reduction favors fixed learned selection. |
|
|
22
|
+
| Did a change in selection fix classification errors? | `compare_activity`, `compare_activity_predictions` | Train two matched classifiers or use two existing decision vectors. For each original window index, track correct-to-wrong and wrong-to-correct changes. SI J.1 uses the same archived readout in both arms. |
|
|
23
|
+
| Which input replacements change a fitted transition? | `rank_directions` | Compare a fitted gate rank and a standardized unit-gate replacement response rank for inputs to the same target. A common gate matrix and donor sample can be used for a model-to-model comparison. |
|
|
24
|
+
|
|
25
|
+
The paper's source-specific data loaders, archived weights, fixed splits, provenance manifests and plot/table generators live in the numerical and repository archives. This installable package exposes the reusable algorithms.
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# SGCI 0.2.0 中文使用指南
|
|
2
|
+
|
|
3
|
+
如果你有一组连续传感器记录,可以用 SGCI 完成三件事:预测下一时刻的读数,判断一个完整窗口里的活动,或检查模型依赖哪些输入。要判断“学到的规律是否有用”,可以让学习策略与随机策略在同一批测试记录、相同训练预算下竞争,查看预测误差的变化以及被纠正的具体样本。
|
|
4
|
+
|
|
5
|
+
## 安装和跑通首个例子
|
|
6
|
+
|
|
7
|
+
使用 Python 3.10 或以上,依赖 NumPy 1.24 或以上、PyTorch 2.1 或以上。在解压后的发行包根目录运行以下命令。若单独下载了 wheel,请将安装命令中的路径换成该文件的实际位置。pip 可以复用当前环境中满足版本要求的依赖。
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
python -m pip install ./dist/sgci-0.2.0-py3-none-any.whl
|
|
11
|
+
python -m sgci --version
|
|
12
|
+
python -m sgci demo
|
|
13
|
+
python examples/custom_sensors.py
|
|
14
|
+
python examples/activity_decisions.py
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
`demo` 在 CPU 上用生成数据训练一个小模型,打印原始输入和置换输入下的均方误差。两个示例分别走通自有通道的预测与成对评估、带原始活动标签的分类与错例比较。它们都自带演示数据。需要从源码安装时,可运行 `python -m pip install ./dist/sgci-0.2.0.tar.gz`。
|
|
18
|
+
|
|
19
|
+
## 按问题选入口
|
|
20
|
+
|
|
21
|
+
| 想解决的问题 | 命令 | 拿到的结果 |
|
|
22
|
+
|---|---|---|
|
|
23
|
+
| 下一时刻的指定传感器读数是多少? | `fit-forecast` → `predict forecast` | 模型文件和原始物理单位下的预测数组 |
|
|
24
|
+
| 学习策略是否比同预算随机策略更稳? | `compare-forecast` | 原始输入和置换输入下的误差差值,细化到种子、受试者和序列 |
|
|
25
|
+
| 这个已结束的窗口是什么活动? | `classify` → `predict activity` | 模型文件和每个窗口的原始类别标签 |
|
|
26
|
+
| 学习策略改对了哪些,新增了哪些错判? | `compare-activity`;已有预测时用 `errors` | 各类决策计数、测试行号、准确率变化 |
|
|
27
|
+
| 模型对哪个输入的替换最敏感? | `scan` | 每个源通道对所选目标的响应方差、响应排名、门值排名 |
|
|
28
|
+
| 热身后哪些方向允许替换? | `mask` | 每个目标对应的可替换源通道索引 |
|
|
29
|
+
|
|
30
|
+
### 用自己的传感器训练并预测
|
|
31
|
+
|
|
32
|
+
把每段记录存为 `[N,T,C]` 数组,分别表示序列数、时间步数和观测通道数。训练与推断必须使用相同的通道顺序、单位,训练时每段至少有两个时间步。使用有限实数的 `.npy` 数组。先按研究目标划分受试者、记录或时间段,再从各自的划分中取窗口,避免相邻或重叠片段跨集。
|
|
33
|
+
|
|
34
|
+
以下文件名代表你准备好的本地数组。只想训练并部署一步预测器时,只需训练文件。下面的例子指定预测第 0 个通道;省略 `--targets` 会输出全部通道。训练时模型拟合所有通道、仅使用同一序列内的相邻观测,标准化参数也仅从训练数据估计。
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
python -m sgci fit-forecast train.npy --targets 0 --model sensor.pt
|
|
38
|
+
python -m sgci predict forecast sensor.pt current.npy --predictions next.npy
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
`current.npy` 存放当前时刻的所有观测,形状为 `[...,C]`。输出保留前面的维度,最后一维是指定目标的原始单位预测值,排列顺序与 `--targets` 一致。Python 对应入口是 `fit_sensor_forecaster` 和 `SensorForecaster.load(...).predict_next(...)`。
|
|
42
|
+
|
|
43
|
+
### 检查学习策略有没有带来预测收益
|
|
44
|
+
|
|
45
|
+
另备独立的 `test.npy`,至少含两条序列。假定共有四个通道,第 0 个是要计分的目标,第 2、3 个可能提供了不稳定的线索。离线测试把第 2、3 个输入通道的整段轨迹一起换给另一条测试序列,保留通道间同步关系。目标真值和其余输入仍与原序列对齐。此模式使用实测通道,目标和置换索引从零开始,两组各自非空且互不重叠。
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
python -m sgci forecast train.npy test.npy --dataset custom --targets 0 --shift 2,3
|
|
49
|
+
python -m sgci compare-forecast train.npy test.npy --dataset custom --targets 0 --shift 2,3 --seeds 0,1,2 --groups test_people.npy --report forecast.json
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
第一条命令评估一种策略。第二条每个种子训练一对模型,采用相同初始种子、相同更新次数和相同测试置换。默认对照 `fixed_random` 保护与学习策略相同数量的方向。阅读 JSON 时,先看 `overall.intact` 和 `overall.shifted`。两者的 `reduction_mse` 都等于对照误差减去学习策略误差,正值表示学习策略更好。单位是目标标准化后的均方误差。百分比先按种子计算再平均,如某个种子的对照误差为零,汇总百分比为 `null`。`permutation_penalty` 是置换相对原始输入带来的额外误差。`case_summary.by_sequence.shifted` 直接给出改善、变差、持平的片段数,以及变化最大的样本行号。随后查看 `by_seed`、`by_sequence` 和 `by_group`,定位汇总变化来自哪些样本。可省略 `--groups` 以使用序列等权;提供与测试行逐一对应的受试者 ID 时,先在受试者内取平均,再对受试者等权平均。
|
|
53
|
+
|
|
54
|
+
### 判断活动和定位错判
|
|
55
|
+
|
|
56
|
+
训练输入为 `[窗口数,时间步数,通道数]`,标签为一维数组,每个窗口一个标签。标签可用整数或非空 Unicode 字符串,全组使用同一类型。训练集至少有两类且须覆盖待评估类别。预测时输入完整窗口,输出训练时使用的原始标签。在 Python 中,`predictor.predict_proba(windows)` 的第 j 列对应 `predictor.classes[j]`。命令行读取普通 NumPy 数组,保存字符串时请使用 Unicode 字符串数组。
|
|
57
|
+
|
|
58
|
+
```sh
|
|
59
|
+
python -m sgci classify train_windows.npy train_labels.npy --model activity.pt
|
|
60
|
+
python -m sgci predict activity activity.pt test_windows.npy --predictions labels.npy
|
|
61
|
+
python -m sgci compare-activity train_windows.npy train_labels.npy test_windows.npy test_labels.npy --groups test_people.npy --report decisions.json
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
`corrected` 是随机对照判错而学习策略判对的窗口数,`introduced` 则是原来判对而学习策略判错的窗口数。两者之差除以总窗口数再乘 100,就是以百分点计的净收益 `delta_accuracy_pp`。JSON 的 `indices` 给出从零开始的测试行号,可逐条回查。活动分类的 `--groups` 增加受试者分项,整体准确率始终按窗口等权。若已有对照预测和学习策略预测,按同一测试顺序直接运行:
|
|
65
|
+
|
|
66
|
+
```sh
|
|
67
|
+
python -m sgci errors test_labels.npy reference_labels.npy learned_labels.npy --report errors.json
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### 判断模型对哪些替换敏感
|
|
71
|
+
|
|
72
|
+
从测试集取上下文,从训练集取替换值,分别存成原始单位的 `[行数,C]` 矩阵。以下命令针对预测目标 0,为四个源通道生成报告:
|
|
73
|
+
|
|
74
|
+
```sh
|
|
75
|
+
python -m sgci scan sensor.pt contexts.npy donors.npy --targets 0 --names target,context,aux1,aux2 --report directions.json
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
对于同一目标,`response_rank=1` 表示在被测源的门值设为 1 后,替换该源引起的输出方差最大。`rank_gap` 等于门值排名减去响应排名,正值说明实测响应排得更靠前。这个量描述拟合模型在给定替换分布下的敏感性。要证明任务收益,应查看独立测试集上的预测或分类对照。要解释为物理因果关系,还需要额外证据。
|
|
79
|
+
|
|
80
|
+
## 与论文核对
|
|
81
|
+
|
|
82
|
+
源码中的 `docs/PAPER_API.md` 索引 v40 的算法、损失与实验协议。论文 Table 7 使用 `prepare_forecast_data` 处理 NATOPS 的 24 个原始通道或 HAPT 的 6 个原始通道,并按论文方法构造三个历史辅助输入。HAPT 按受试者等权汇总。CPU 回放 70 个既有预测检查点复现了 275 行结果。按论文协议,学习策略相对固定随机策略的置换误差降幅在 NATOPS、HAPT 上分别为 21.55%、51.38%。HAR 的主要结果衡量结构选择对响应方差的影响,对比模型的分类准确率相近。这些数值属于各自的任务和数据协议。自有数据上的收益应使用自己的独立测试集评估。
|
|
83
|
+
|
|
84
|
+
如要把正则项接入现有 PyTorch 训练循环,可用 `StructuredDynamics`、`ProbePolicy.fixed` 与 `invariance_penalty`。热身结束时记录一次固定策略,随后复用,同时继续更新转移模型的参数。矩阵行代表源、列代表目标;可用 `measure_direction` 针对单个方向测量响应。
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Use a complete activity window to classify; measure one latent response separately."""
|
|
2
|
+
import torch
|
|
3
|
+
from sgci.classification import ActivityClassifier, fit_activity_classifier
|
|
4
|
+
from sgci.response import measure_direction
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def main():
|
|
8
|
+
torch.set_num_threads(1)
|
|
9
|
+
rng = torch.Generator().manual_seed(7)
|
|
10
|
+
windows = torch.randn(16, 10, 3, generator=rng)
|
|
11
|
+
labels = (windows[:, :, 0].mean(1) > 0).long()
|
|
12
|
+
torch.manual_seed(9)
|
|
13
|
+
small = ActivityClassifier(input_dim=3, latent_dim=4, output_dim=2, inception_filters=2,
|
|
14
|
+
inception_blocks=1, dynamics_hidden_dim=8, head_hidden_dim=8)
|
|
15
|
+
fit = fit_activity_classifier(windows[:12], labels[:12], model=small, epochs=5, batch_size=4)
|
|
16
|
+
with torch.no_grad():
|
|
17
|
+
logits, _ = fit.model(windows[12:])
|
|
18
|
+
_, latent = fit.model(windows[:12])
|
|
19
|
+
z = torch.nn.functional.layer_norm(latent, (fit.model.latent_dim,))[:, :-1].reshape(-1, 4)
|
|
20
|
+
target = 0
|
|
21
|
+
source = int(fit.policy.candidate_sources(fit.warmup_gates)[target, 0])
|
|
22
|
+
donor_indices = torch.randint(len(z), (8, 6), generator=rng)
|
|
23
|
+
measure = measure_direction(fit.model.dynamics, z[:6], z, source=source, target=target,
|
|
24
|
+
donor_indices=donor_indices)
|
|
25
|
+
print("Predicted classes:", logits.argmax(1).tolist())
|
|
26
|
+
print("Direction:", (source, target), "response variance:", float(measure.response_variance))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
if __name__ == "__main__":
|
|
30
|
+
main()
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Train, reload and compare completed-window predictions with original string labels."""
|
|
2
|
+
import tempfile
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import numpy as np
|
|
5
|
+
import torch
|
|
6
|
+
from sgci import ActivityPredictor, compare_activity_predictions, fit_activity
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def main():
|
|
10
|
+
torch.set_num_threads(1)
|
|
11
|
+
rng = np.random.default_rng(5)
|
|
12
|
+
windows = rng.normal(size=(48, 16, 3)).astype("float32")
|
|
13
|
+
labels = np.where(windows[:, :, 1].mean(1) >= 0, "walking", "standing")
|
|
14
|
+
options = dict(epochs=4, batch_size=8, seed=0, model_options={
|
|
15
|
+
"latent_dim":4,"dynamics_hidden_dim":8,"inception_filters":2,"inception_blocks":1,"head_hidden_dim":8})
|
|
16
|
+
learned = fit_activity(windows[:32], labels[:32], policy="fixed_learned", **options)
|
|
17
|
+
random = fit_activity(windows[:32], labels[:32], policy="fixed_random", **options)
|
|
18
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
19
|
+
path = Path(directory)/"activity.pt"
|
|
20
|
+
learned.save(path)
|
|
21
|
+
pred = ActivityPredictor.load(path).predict(windows[32:])
|
|
22
|
+
report = compare_activity_predictions(labels[32:], random.predict(windows[32:]), pred)
|
|
23
|
+
print(report["counts"], report["delta_accuracy_pp"], report["indices"]["introduced"])
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
if __name__ == "__main__":
|
|
27
|
+
main()
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""An end-to-end comparison, prediction and direction probe on four observed channels."""
|
|
2
|
+
import tempfile
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import torch
|
|
7
|
+
|
|
8
|
+
from sgci import (compare_forecasts, fit_forecaster, prepare_custom_forecast_data,
|
|
9
|
+
rank_directions, SensorForecaster)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main():
|
|
13
|
+
torch.set_num_threads(1)
|
|
14
|
+
rng = np.random.default_rng(42)
|
|
15
|
+
# Two independent splits of four consistently ordered sensor channels.
|
|
16
|
+
train = rng.normal(size=(24, 16, 4)).cumsum(axis=1).astype("float32")
|
|
17
|
+
test = rng.normal(size=(8, 16, 4)).cumsum(axis=1).astype("float32")
|
|
18
|
+
data = prepare_custom_forecast_data(train, test, target_channels=[0], shift_channels=[2, 3])
|
|
19
|
+
options = dict(epochs=3, batch_size=32, hidden_dim=8)
|
|
20
|
+
result = compare_forecasts(data, seeds=[0, 1], **options)
|
|
21
|
+
print("Paired held-out shifted MSE:", result["overall"]["shifted"])
|
|
22
|
+
trained = fit_forecaster(data.train, seed=0, **options)
|
|
23
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
24
|
+
path = Path(directory) / "forecaster.pt"
|
|
25
|
+
SensorForecaster.from_fit(trained, data).save(path)
|
|
26
|
+
predicted = SensorForecaster.load(path).predict_next(test[:, -1, :])
|
|
27
|
+
print("Next target value for each sequence, in sensor units:", predicted[:, 0])
|
|
28
|
+
responses = rank_directions(trained.model, data.test[:, :-1].reshape(-1, 4),
|
|
29
|
+
data.train[:, :-1].reshape(-1, 4), targets=[0],
|
|
30
|
+
names=["target", "context", "aux1", "aux2"], max_contexts=32)
|
|
31
|
+
print("Strongest standardized response:", responses["directions"][0])
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
if __name__ == "__main__":
|
|
35
|
+
main()
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Train and compare two probe policies on synthetic, HAPT-shaped sequences.
|
|
2
|
+
|
|
3
|
+
Run with python examples/forecast.py after installing the distribution.
|
|
4
|
+
These short illustrative fits do not reproduce the paper's accuracy estimates.
|
|
5
|
+
"""
|
|
6
|
+
import numpy as np
|
|
7
|
+
import torch
|
|
8
|
+
|
|
9
|
+
from sgci.forecasting import evaluation_permutations, fit_forecaster, prepare_forecast_data, score_forecast
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main():
|
|
13
|
+
torch.set_num_threads(1)
|
|
14
|
+
rng = np.random.default_rng(21)
|
|
15
|
+
train = rng.normal(size=(10, 16, 6)).astype("float32").cumsum(axis=1)
|
|
16
|
+
test = rng.normal(size=(6, 16, 6)).astype("float32").cumsum(axis=1)
|
|
17
|
+
data = prepare_forecast_data(train, test, dataset="hapt")
|
|
18
|
+
donor = evaluation_permutations(len(test), seed=0)
|
|
19
|
+
for policy in ("fixed_learned", "fixed_random"):
|
|
20
|
+
fit = fit_forecaster(data.train, policy=policy, seed=0, epochs=3, hidden_dim=16, batch_size=32)
|
|
21
|
+
metrics = score_forecast(fit.model, data.test, permutations=donor)
|
|
22
|
+
print(f"{policy:14s} intact MSE {metrics.intact_mse:.5f}, shifted MSE {metrics.shifted_mse:.5f}")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
if __name__ == "__main__":
|
|
26
|
+
main()
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "sgci"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Structure-guided counterfactual invariance for sequential classification and forecasting"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE", "NOTICE"]
|
|
13
|
+
authors = [{name = "Ziran Peng"}, {name = "Siyuan Xia"}, {name = "Huiqin Xiao"}]
|
|
14
|
+
keywords = ["time series", "counterfactual invariance", "forecasting", "PyTorch", "pattern recognition"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
20
|
+
]
|
|
21
|
+
dependencies = ["torch>=2.1", "numpy>=1.24"]
|
|
22
|
+
|
|
23
|
+
[project.optional-dependencies]
|
|
24
|
+
dev = ["pytest>=8", "build>=1", "twine>=5"]
|
|
25
|
+
|
|
26
|
+
[project.scripts]
|
|
27
|
+
sgci = "sgci.cli:main"
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Repository = "https://github.com/anonymous-rl-lab/SGCI"
|
|
31
|
+
"Historical software archive" = "https://doi.org/10.5281/zenodo.21696299"
|
|
32
|
+
|
|
33
|
+
[tool.setuptools.dynamic]
|
|
34
|
+
version = {attr = "sgci._version.__version__"}
|
|
35
|
+
|
|
36
|
+
[tool.setuptools.packages.find]
|
|
37
|
+
where = ["src"]
|
|
38
|
+
|
|
39
|
+
[tool.pytest.ini_options]
|
|
40
|
+
testpaths = ["tests"]
|
sgci-0.2.0/setup.cfg
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Structure-guided counterfactual invariance for sequential models."""
|
|
2
|
+
from ._version import __version__
|
|
3
|
+
from .activity_workflow import ActivityPredictor, compare_activity, compare_activity_predictions, fit_activity
|
|
4
|
+
from .classification import ActivityClassifier, fit_activity_classifier
|
|
5
|
+
from .comparison import compare_forecasts, summarize_forecast_pairs
|
|
6
|
+
from .diagnostics import rank_directions
|
|
7
|
+
from .dynamics import StructuredDynamics
|
|
8
|
+
from .forecasting import fit_forecaster, prepare_custom_forecast_data, prepare_forecast_data, score_forecast
|
|
9
|
+
from .invariance import invariance_penalty
|
|
10
|
+
from .response import measure_direction
|
|
11
|
+
from .selection import ProbePolicy
|
|
12
|
+
from .sensor import SensorForecaster, fit_sensor_forecaster
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"__version__", "ActivityClassifier", "ActivityPredictor", "ProbePolicy", "SensorForecaster",
|
|
16
|
+
"StructuredDynamics", "compare_activity", "compare_activity_predictions", "compare_forecasts",
|
|
17
|
+
"fit_activity", "fit_activity_classifier", "fit_forecaster", "fit_sensor_forecaster",
|
|
18
|
+
"invariance_penalty", "measure_direction", "prepare_custom_forecast_data", "prepare_forecast_data",
|
|
19
|
+
"rank_directions", "score_forecast", "summarize_forecast_pairs",
|
|
20
|
+
]
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Write a completed file atomically in its destination directory."""
|
|
2
|
+
from contextlib import contextmanager
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import tempfile
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@contextmanager
|
|
9
|
+
def output_file(path, *, binary=False):
|
|
10
|
+
path = Path(path)
|
|
11
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
12
|
+
with tempfile.NamedTemporaryFile(mode="wb" if binary else "w", encoding=None if binary else "utf-8",
|
|
13
|
+
delete=False, dir=path.parent) as f:
|
|
14
|
+
temporary = Path(f.name)
|
|
15
|
+
try:
|
|
16
|
+
yield f
|
|
17
|
+
f.close()
|
|
18
|
+
os.replace(temporary, path)
|
|
19
|
+
finally:
|
|
20
|
+
temporary.unlink(missing_ok=True)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.2.0"
|