Feature Extraction
Transformers
Safetensors
English
setcon
imu
wearable-sensing
human-activity-recognition
zero-shot-classification
motion-language
time-series
custom_code
Instructions to use lschiweck/SetCon with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use lschiweck/SetCon with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="lschiweck/SetCon", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("lschiweck/SetCon", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
SetCon weights, inference and evaluation code
Browse files- .gitattributes +1 -0
- CHECKSUMS.txt +22 -0
- LICENSE +408 -0
- README.md +210 -0
- config.json +44 -0
- configuration_setcon.py +65 -0
- error_bank.json +41 -0
- examples/reproduce_table1.py +88 -0
- examples/zero_shot.py +57 -0
- model.safetensors +3 -0
- modeling_setcon.py +295 -0
- processing_setcon.py +251 -0
- requirements.txt +14 -0
- seed2/config.json +44 -0
- seed2/model.safetensors +3 -0
- seed3/config.json +44 -0
- seed3/model.safetensors +3 -0
- setcon/__init__.py +57 -0
- setcon/data.py +192 -0
- setcon/evaluate.py +101 -0
- setcon/protocol.py +213 -0
- setcon/references.py +113 -0
- setcon/tables.py +269 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
CHECKSUMS.txt
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
34448b82c17d60fec9b65b1f093c115ddbaadc04beb1b0140b6bfed2e012a930 .gitattributes
|
| 2 |
+
41003d4a74749c0220e33dd415042164b5a1093ed401f36277234f772d22d3d0 LICENSE
|
| 3 |
+
752be7acb6522c76700ebcbbdeb437293e536312b68c5db6c6160af0555b7b37 README.md
|
| 4 |
+
b69d37fcc55e362a0dbb728aee069047f2e847980cdda3f24c6e195d2c304174 config.json
|
| 5 |
+
dc956f3f7d08803de98fb2a773fe634cce9adb076a5aeaac151e5340073c7be0 configuration_setcon.py
|
| 6 |
+
5ea1c68276212f311d3f233f91947c3c5df9c78deaba83f86fa18f9c0cfb2742 error_bank.json
|
| 7 |
+
5b1fc8961fa2b1c120c7442e716c92cc45776aef72094f54239e51fb56f3c2e4 examples/reproduce_table1.py
|
| 8 |
+
48a2d7194375bf875150b52695fe7c48ade478d8414589718b82fd77567a2644 examples/zero_shot.py
|
| 9 |
+
50dc00dfa5bf377833329f3933929c9cc0eadc2bf66ba58fa9d45696d5c9bc9b model.safetensors
|
| 10 |
+
ba588c4e0cde8313bcc156e0517f078fc8648c8fdf87bd3d4d79c53667e73d3f modeling_setcon.py
|
| 11 |
+
2fae7f430b9a7f2295da9ee937304e743d80811a91cbed17f7d347e141fba18a processing_setcon.py
|
| 12 |
+
2f764642175065967a76c51e1cb237acec396e4fc421d7b298fb338ab02f9fc5 requirements.txt
|
| 13 |
+
b51738977aa0ada57da8794844d9e18f7e7ba093603e88a62f1eae4b96d0d894 seed2/config.json
|
| 14 |
+
ab0386be5d2ef7cf02cda9f2c18a0f6a29fdc7415049c9226553c619ad82d060 seed2/model.safetensors
|
| 15 |
+
8c83411b74ee4142f6751be6dcd5c5a99335918a6bbd90acc807ee19229b3954 seed3/config.json
|
| 16 |
+
cc6dd517b2ad2afe64fe184862e6e8035e1383f67b3581cbd78c4fe69c450b34 seed3/model.safetensors
|
| 17 |
+
25c19b94527ec4702b224dd8c7bcaed9e3143103a98a446793862ac162682b3c setcon/__init__.py
|
| 18 |
+
86c85d0c34628268b574b485da9f1781815634875112e0e6e49192db765262f0 setcon/data.py
|
| 19 |
+
6b3be2be21595767662cefac638c5049ec1d381d03b9108bc01ca4778227f4b7 setcon/evaluate.py
|
| 20 |
+
51515b56584eece993772e494ca27013dcd1108009316b0edc4e165ecd90639f setcon/protocol.py
|
| 21 |
+
4a8daea0d26be94f6d058d60fa263a521d2bcfd7345e1d76803d48f3143995b8 setcon/references.py
|
| 22 |
+
8eb9658218e6445eba115aba113127d8512d7e6809082713e85880ed503ece08 setcon/tables.py
|
LICENSE
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Attribution-NonCommercial 4.0 International
|
| 2 |
+
|
| 3 |
+
=======================================================================
|
| 4 |
+
|
| 5 |
+
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
| 6 |
+
does not provide legal services or legal advice. Distribution of
|
| 7 |
+
Creative Commons public licenses does not create a lawyer-client or
|
| 8 |
+
other relationship. Creative Commons makes its licenses and related
|
| 9 |
+
information available on an "as-is" basis. Creative Commons gives no
|
| 10 |
+
warranties regarding its licenses, any material licensed under their
|
| 11 |
+
terms and conditions, or any related information. Creative Commons
|
| 12 |
+
disclaims all liability for damages resulting from their use to the
|
| 13 |
+
fullest extent possible.
|
| 14 |
+
|
| 15 |
+
Using Creative Commons Public Licenses
|
| 16 |
+
|
| 17 |
+
Creative Commons public licenses provide a standard set of terms and
|
| 18 |
+
conditions that creators and other rights holders may use to share
|
| 19 |
+
original works of authorship and other material subject to copyright
|
| 20 |
+
and certain other rights specified in the public license below. The
|
| 21 |
+
following considerations are for informational purposes only, are not
|
| 22 |
+
exhaustive, and do not form part of our licenses.
|
| 23 |
+
|
| 24 |
+
Considerations for licensors: Our public licenses are
|
| 25 |
+
intended for use by those authorized to give the public
|
| 26 |
+
permission to use material in ways otherwise restricted by
|
| 27 |
+
copyright and certain other rights. Our licenses are
|
| 28 |
+
irrevocable. Licensors should read and understand the terms
|
| 29 |
+
and conditions of the license they choose before applying it.
|
| 30 |
+
Licensors should also secure all rights necessary before
|
| 31 |
+
applying our licenses so that the public can reuse the
|
| 32 |
+
material as expected. Licensors should clearly mark any
|
| 33 |
+
material not subject to the license. This includes other CC-
|
| 34 |
+
licensed material, or material used under an exception or
|
| 35 |
+
limitation to copyright. More considerations for licensors:
|
| 36 |
+
wiki.creativecommons.org/Considerations_for_licensors
|
| 37 |
+
|
| 38 |
+
Considerations for the public: By using one of our public
|
| 39 |
+
licenses, a licensor grants the public permission to use the
|
| 40 |
+
licensed material under specified terms and conditions. If
|
| 41 |
+
the licensor's permission is not necessary for any reason--for
|
| 42 |
+
example, because of any applicable exception or limitation to
|
| 43 |
+
copyright--then that use is not regulated by the license. Our
|
| 44 |
+
licenses grant only permissions under copyright and certain
|
| 45 |
+
other rights that a licensor has authority to grant. Use of
|
| 46 |
+
the licensed material may still be restricted for other
|
| 47 |
+
reasons, including because others have copyright or other
|
| 48 |
+
rights in the material. A licensor may make special requests,
|
| 49 |
+
such as asking that all changes be marked or described.
|
| 50 |
+
Although not required by our licenses, you are encouraged to
|
| 51 |
+
respect those requests where reasonable. More considerations
|
| 52 |
+
for the public:
|
| 53 |
+
wiki.creativecommons.org/Considerations_for_licensees
|
| 54 |
+
|
| 55 |
+
=======================================================================
|
| 56 |
+
|
| 57 |
+
Creative Commons Attribution-NonCommercial 4.0 International Public
|
| 58 |
+
License
|
| 59 |
+
|
| 60 |
+
By exercising the Licensed Rights (defined below), You accept and agree
|
| 61 |
+
to be bound by the terms and conditions of this Creative Commons
|
| 62 |
+
Attribution-NonCommercial 4.0 International Public License ("Public
|
| 63 |
+
License"). To the extent this Public License may be interpreted as a
|
| 64 |
+
contract, You are granted the Licensed Rights in consideration of Your
|
| 65 |
+
acceptance of these terms and conditions, and the Licensor grants You
|
| 66 |
+
such rights in consideration of benefits the Licensor receives from
|
| 67 |
+
making the Licensed Material available under these terms and
|
| 68 |
+
conditions.
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
Section 1 -- Definitions.
|
| 72 |
+
|
| 73 |
+
a. Adapted Material means material subject to Copyright and Similar
|
| 74 |
+
Rights that is derived from or based upon the Licensed Material
|
| 75 |
+
and in which the Licensed Material is translated, altered,
|
| 76 |
+
arranged, transformed, or otherwise modified in a manner requiring
|
| 77 |
+
permission under the Copyright and Similar Rights held by the
|
| 78 |
+
Licensor. For purposes of this Public License, where the Licensed
|
| 79 |
+
Material is a musical work, performance, or sound recording,
|
| 80 |
+
Adapted Material is always produced where the Licensed Material is
|
| 81 |
+
synched in timed relation with a moving image.
|
| 82 |
+
|
| 83 |
+
b. Adapter's License means the license You apply to Your Copyright
|
| 84 |
+
and Similar Rights in Your contributions to Adapted Material in
|
| 85 |
+
accordance with the terms and conditions of this Public License.
|
| 86 |
+
|
| 87 |
+
c. Copyright and Similar Rights means copyright and/or similar rights
|
| 88 |
+
closely related to copyright including, without limitation,
|
| 89 |
+
performance, broadcast, sound recording, and Sui Generis Database
|
| 90 |
+
Rights, without regard to how the rights are labeled or
|
| 91 |
+
categorized. For purposes of this Public License, the rights
|
| 92 |
+
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
| 93 |
+
Rights.
|
| 94 |
+
d. Effective Technological Measures means those measures that, in the
|
| 95 |
+
absence of proper authority, may not be circumvented under laws
|
| 96 |
+
fulfilling obligations under Article 11 of the WIPO Copyright
|
| 97 |
+
Treaty adopted on December 20, 1996, and/or similar international
|
| 98 |
+
agreements.
|
| 99 |
+
|
| 100 |
+
e. Exceptions and Limitations means fair use, fair dealing, and/or
|
| 101 |
+
any other exception or limitation to Copyright and Similar Rights
|
| 102 |
+
that applies to Your use of the Licensed Material.
|
| 103 |
+
|
| 104 |
+
f. Licensed Material means the artistic or literary work, database,
|
| 105 |
+
or other material to which the Licensor applied this Public
|
| 106 |
+
License.
|
| 107 |
+
|
| 108 |
+
g. Licensed Rights means the rights granted to You subject to the
|
| 109 |
+
terms and conditions of this Public License, which are limited to
|
| 110 |
+
all Copyright and Similar Rights that apply to Your use of the
|
| 111 |
+
Licensed Material and that the Licensor has authority to license.
|
| 112 |
+
|
| 113 |
+
h. Licensor means the individual(s) or entity(ies) granting rights
|
| 114 |
+
under this Public License.
|
| 115 |
+
|
| 116 |
+
i. NonCommercial means not primarily intended for or directed towards
|
| 117 |
+
commercial advantage or monetary compensation. For purposes of
|
| 118 |
+
this Public License, the exchange of the Licensed Material for
|
| 119 |
+
other material subject to Copyright and Similar Rights by digital
|
| 120 |
+
file-sharing or similar means is NonCommercial provided there is
|
| 121 |
+
no payment of monetary compensation in connection with the
|
| 122 |
+
exchange.
|
| 123 |
+
|
| 124 |
+
j. Share means to provide material to the public by any means or
|
| 125 |
+
process that requires permission under the Licensed Rights, such
|
| 126 |
+
as reproduction, public display, public performance, distribution,
|
| 127 |
+
dissemination, communication, or importation, and to make material
|
| 128 |
+
available to the public including in ways that members of the
|
| 129 |
+
public may access the material from a place and at a time
|
| 130 |
+
individually chosen by them.
|
| 131 |
+
|
| 132 |
+
k. Sui Generis Database Rights means rights other than copyright
|
| 133 |
+
resulting from Directive 96/9/EC of the European Parliament and of
|
| 134 |
+
the Council of 11 March 1996 on the legal protection of databases,
|
| 135 |
+
as amended and/or succeeded, as well as other essentially
|
| 136 |
+
equivalent rights anywhere in the world.
|
| 137 |
+
|
| 138 |
+
l. You means the individual or entity exercising the Licensed Rights
|
| 139 |
+
under this Public License. Your has a corresponding meaning.
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
Section 2 -- Scope.
|
| 143 |
+
|
| 144 |
+
a. License grant.
|
| 145 |
+
|
| 146 |
+
1. Subject to the terms and conditions of this Public License,
|
| 147 |
+
the Licensor hereby grants You a worldwide, royalty-free,
|
| 148 |
+
non-sublicensable, non-exclusive, irrevocable license to
|
| 149 |
+
exercise the Licensed Rights in the Licensed Material to:
|
| 150 |
+
|
| 151 |
+
a. reproduce and Share the Licensed Material, in whole or
|
| 152 |
+
in part, for NonCommercial purposes only; and
|
| 153 |
+
|
| 154 |
+
b. produce, reproduce, and Share Adapted Material for
|
| 155 |
+
NonCommercial purposes only.
|
| 156 |
+
|
| 157 |
+
2. Exceptions and Limitations. For the avoidance of doubt, where
|
| 158 |
+
Exceptions and Limitations apply to Your use, this Public
|
| 159 |
+
License does not apply, and You do not need to comply with
|
| 160 |
+
its terms and conditions.
|
| 161 |
+
|
| 162 |
+
3. Term. The term of this Public License is specified in Section
|
| 163 |
+
6(a).
|
| 164 |
+
|
| 165 |
+
4. Media and formats; technical modifications allowed. The
|
| 166 |
+
Licensor authorizes You to exercise the Licensed Rights in
|
| 167 |
+
all media and formats whether now known or hereafter created,
|
| 168 |
+
and to make technical modifications necessary to do so. The
|
| 169 |
+
Licensor waives and/or agrees not to assert any right or
|
| 170 |
+
authority to forbid You from making technical modifications
|
| 171 |
+
necessary to exercise the Licensed Rights, including
|
| 172 |
+
technical modifications necessary to circumvent Effective
|
| 173 |
+
Technological Measures. For purposes of this Public License,
|
| 174 |
+
simply making modifications authorized by this Section 2(a)
|
| 175 |
+
(4) never produces Adapted Material.
|
| 176 |
+
|
| 177 |
+
5. Downstream recipients.
|
| 178 |
+
|
| 179 |
+
a. Offer from the Licensor -- Licensed Material. Every
|
| 180 |
+
recipient of the Licensed Material automatically
|
| 181 |
+
receives an offer from the Licensor to exercise the
|
| 182 |
+
Licensed Rights under the terms and conditions of this
|
| 183 |
+
Public License.
|
| 184 |
+
|
| 185 |
+
b. No downstream restrictions. You may not offer or impose
|
| 186 |
+
any additional or different terms or conditions on, or
|
| 187 |
+
apply any Effective Technological Measures to, the
|
| 188 |
+
Licensed Material if doing so restricts exercise of the
|
| 189 |
+
Licensed Rights by any recipient of the Licensed
|
| 190 |
+
Material.
|
| 191 |
+
|
| 192 |
+
6. No endorsement. Nothing in this Public License constitutes or
|
| 193 |
+
may be construed as permission to assert or imply that You
|
| 194 |
+
are, or that Your use of the Licensed Material is, connected
|
| 195 |
+
with, or sponsored, endorsed, or granted official status by,
|
| 196 |
+
the Licensor or others designated to receive attribution as
|
| 197 |
+
provided in Section 3(a)(1)(A)(i).
|
| 198 |
+
|
| 199 |
+
b. Other rights.
|
| 200 |
+
|
| 201 |
+
1. Moral rights, such as the right of integrity, are not
|
| 202 |
+
licensed under this Public License, nor are publicity,
|
| 203 |
+
privacy, and/or other similar personality rights; however, to
|
| 204 |
+
the extent possible, the Licensor waives and/or agrees not to
|
| 205 |
+
assert any such rights held by the Licensor to the limited
|
| 206 |
+
extent necessary to allow You to exercise the Licensed
|
| 207 |
+
Rights, but not otherwise.
|
| 208 |
+
|
| 209 |
+
2. Patent and trademark rights are not licensed under this
|
| 210 |
+
Public License.
|
| 211 |
+
|
| 212 |
+
3. To the extent possible, the Licensor waives any right to
|
| 213 |
+
collect royalties from You for the exercise of the Licensed
|
| 214 |
+
Rights, whether directly or through a collecting society
|
| 215 |
+
under any voluntary or waivable statutory or compulsory
|
| 216 |
+
licensing scheme. In all other cases the Licensor expressly
|
| 217 |
+
reserves any right to collect such royalties, including when
|
| 218 |
+
the Licensed Material is used other than for NonCommercial
|
| 219 |
+
purposes.
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
Section 3 -- License Conditions.
|
| 223 |
+
|
| 224 |
+
Your exercise of the Licensed Rights is expressly made subject to the
|
| 225 |
+
following conditions.
|
| 226 |
+
|
| 227 |
+
a. Attribution.
|
| 228 |
+
|
| 229 |
+
1. If You Share the Licensed Material (including in modified
|
| 230 |
+
form), You must:
|
| 231 |
+
|
| 232 |
+
a. retain the following if it is supplied by the Licensor
|
| 233 |
+
with the Licensed Material:
|
| 234 |
+
|
| 235 |
+
i. identification of the creator(s) of the Licensed
|
| 236 |
+
Material and any others designated to receive
|
| 237 |
+
attribution, in any reasonable manner requested by
|
| 238 |
+
the Licensor (including by pseudonym if
|
| 239 |
+
designated);
|
| 240 |
+
|
| 241 |
+
ii. a copyright notice;
|
| 242 |
+
|
| 243 |
+
iii. a notice that refers to this Public License;
|
| 244 |
+
|
| 245 |
+
iv. a notice that refers to the disclaimer of
|
| 246 |
+
warranties;
|
| 247 |
+
|
| 248 |
+
v. a URI or hyperlink to the Licensed Material to the
|
| 249 |
+
extent reasonably practicable;
|
| 250 |
+
|
| 251 |
+
b. indicate if You modified the Licensed Material and
|
| 252 |
+
retain an indication of any previous modifications; and
|
| 253 |
+
|
| 254 |
+
c. indicate the Licensed Material is licensed under this
|
| 255 |
+
Public License, and include the text of, or the URI or
|
| 256 |
+
hyperlink to, this Public License.
|
| 257 |
+
|
| 258 |
+
2. You may satisfy the conditions in Section 3(a)(1) in any
|
| 259 |
+
reasonable manner based on the medium, means, and context in
|
| 260 |
+
which You Share the Licensed Material. For example, it may be
|
| 261 |
+
reasonable to satisfy the conditions by providing a URI or
|
| 262 |
+
hyperlink to a resource that includes the required
|
| 263 |
+
information.
|
| 264 |
+
|
| 265 |
+
3. If requested by the Licensor, You must remove any of the
|
| 266 |
+
information required by Section 3(a)(1)(A) to the extent
|
| 267 |
+
reasonably practicable.
|
| 268 |
+
|
| 269 |
+
4. If You Share Adapted Material You produce, the Adapter's
|
| 270 |
+
License You apply must not prevent recipients of the Adapted
|
| 271 |
+
Material from complying with this Public License.
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
Section 4 -- Sui Generis Database Rights.
|
| 275 |
+
|
| 276 |
+
Where the Licensed Rights include Sui Generis Database Rights that
|
| 277 |
+
apply to Your use of the Licensed Material:
|
| 278 |
+
|
| 279 |
+
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
| 280 |
+
to extract, reuse, reproduce, and Share all or a substantial
|
| 281 |
+
portion of the contents of the database for NonCommercial purposes
|
| 282 |
+
only;
|
| 283 |
+
|
| 284 |
+
b. if You include all or a substantial portion of the database
|
| 285 |
+
contents in a database in which You have Sui Generis Database
|
| 286 |
+
Rights, then the database in which You have Sui Generis Database
|
| 287 |
+
Rights (but not its individual contents) is Adapted Material; and
|
| 288 |
+
|
| 289 |
+
c. You must comply with the conditions in Section 3(a) if You Share
|
| 290 |
+
all or a substantial portion of the contents of the database.
|
| 291 |
+
|
| 292 |
+
For the avoidance of doubt, this Section 4 supplements and does not
|
| 293 |
+
replace Your obligations under this Public License where the Licensed
|
| 294 |
+
Rights include other Copyright and Similar Rights.
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
| 298 |
+
|
| 299 |
+
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
| 300 |
+
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
| 301 |
+
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
| 302 |
+
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
| 303 |
+
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
| 304 |
+
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
| 305 |
+
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
| 306 |
+
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
| 307 |
+
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
| 308 |
+
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
| 309 |
+
|
| 310 |
+
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
| 311 |
+
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
| 312 |
+
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
| 313 |
+
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
| 314 |
+
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
| 315 |
+
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
| 316 |
+
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
| 317 |
+
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
| 318 |
+
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
| 319 |
+
|
| 320 |
+
c. The disclaimer of warranties and limitation of liability provided
|
| 321 |
+
above shall be interpreted in a manner that, to the extent
|
| 322 |
+
possible, most closely approximates an absolute disclaimer and
|
| 323 |
+
waiver of all liability.
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
Section 6 -- Term and Termination.
|
| 327 |
+
|
| 328 |
+
a. This Public License applies for the term of the Copyright and
|
| 329 |
+
Similar Rights licensed here. However, if You fail to comply with
|
| 330 |
+
this Public License, then Your rights under this Public License
|
| 331 |
+
terminate automatically.
|
| 332 |
+
|
| 333 |
+
b. Where Your right to use the Licensed Material has terminated under
|
| 334 |
+
Section 6(a), it reinstates:
|
| 335 |
+
|
| 336 |
+
1. automatically as of the date the violation is cured, provided
|
| 337 |
+
it is cured within 30 days of Your discovery of the
|
| 338 |
+
violation; or
|
| 339 |
+
|
| 340 |
+
2. upon express reinstatement by the Licensor.
|
| 341 |
+
|
| 342 |
+
For the avoidance of doubt, this Section 6(b) does not affect any
|
| 343 |
+
right the Licensor may have to seek remedies for Your violations
|
| 344 |
+
of this Public License.
|
| 345 |
+
|
| 346 |
+
c. For the avoidance of doubt, the Licensor may also offer the
|
| 347 |
+
Licensed Material under separate terms or conditions or stop
|
| 348 |
+
distributing the Licensed Material at any time; however, doing so
|
| 349 |
+
will not terminate this Public License.
|
| 350 |
+
|
| 351 |
+
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
| 352 |
+
License.
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
Section 7 -- Other Terms and Conditions.
|
| 356 |
+
|
| 357 |
+
a. The Licensor shall not be bound by any additional or different
|
| 358 |
+
terms or conditions communicated by You unless expressly agreed.
|
| 359 |
+
|
| 360 |
+
b. Any arrangements, understandings, or agreements regarding the
|
| 361 |
+
Licensed Material not stated herein are separate from and
|
| 362 |
+
independent of the terms and conditions of this Public License.
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
Section 8 -- Interpretation.
|
| 366 |
+
|
| 367 |
+
a. For the avoidance of doubt, this Public License does not, and
|
| 368 |
+
shall not be interpreted to, reduce, limit, restrict, or impose
|
| 369 |
+
conditions on any use of the Licensed Material that could lawfully
|
| 370 |
+
be made without permission under this Public License.
|
| 371 |
+
|
| 372 |
+
b. To the extent possible, if any provision of this Public License is
|
| 373 |
+
deemed unenforceable, it shall be automatically reformed to the
|
| 374 |
+
minimum extent necessary to make it enforceable. If the provision
|
| 375 |
+
cannot be reformed, it shall be severed from this Public License
|
| 376 |
+
without affecting the enforceability of the remaining terms and
|
| 377 |
+
conditions.
|
| 378 |
+
|
| 379 |
+
c. No term or condition of this Public License will be waived and no
|
| 380 |
+
failure to comply consented to unless expressly agreed to by the
|
| 381 |
+
Licensor.
|
| 382 |
+
|
| 383 |
+
d. Nothing in this Public License constitutes or may be interpreted
|
| 384 |
+
as a limitation upon, or waiver of, any privileges and immunities
|
| 385 |
+
that apply to the Licensor or You, including from the legal
|
| 386 |
+
processes of any jurisdiction or authority.
|
| 387 |
+
|
| 388 |
+
=======================================================================
|
| 389 |
+
|
| 390 |
+
Creative Commons is not a party to its public
|
| 391 |
+
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
| 392 |
+
its public licenses to material it publishes and in those instances
|
| 393 |
+
will be considered the “Licensor.” The text of the Creative Commons
|
| 394 |
+
public licenses is dedicated to the public domain under the CC0 Public
|
| 395 |
+
Domain Dedication. Except for the limited purpose of indicating that
|
| 396 |
+
material is shared under a Creative Commons public license or as
|
| 397 |
+
otherwise permitted by the Creative Commons policies published at
|
| 398 |
+
creativecommons.org/policies, Creative Commons does not authorize the
|
| 399 |
+
use of the trademark "Creative Commons" or any other trademark or logo
|
| 400 |
+
of Creative Commons without its prior written consent including,
|
| 401 |
+
without limitation, in connection with any unauthorized modifications
|
| 402 |
+
to any of its public licenses or any other arrangements,
|
| 403 |
+
understandings, or agreements concerning use of licensed material. For
|
| 404 |
+
the avoidance of doubt, this paragraph does not form part of the
|
| 405 |
+
public licenses.
|
| 406 |
+
|
| 407 |
+
Creative Commons may be contacted at creativecommons.org.
|
| 408 |
+
|
README.md
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc-by-nc-4.0
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
library_name: transformers
|
| 6 |
+
pipeline_tag: feature-extraction
|
| 7 |
+
datasets:
|
| 8 |
+
- lschiweck/SetCon-eval
|
| 9 |
+
tags:
|
| 10 |
+
- imu
|
| 11 |
+
- wearable-sensing
|
| 12 |
+
- human-activity-recognition
|
| 13 |
+
- zero-shot-classification
|
| 14 |
+
- motion-language
|
| 15 |
+
- time-series
|
| 16 |
+
- custom_code
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# SetCon: Setup-Conditioned IMU-Language Learning from 3D Human Motion
|
| 21 |
+
|
| 22 |
+
Lennart Schiweck<sup>1</sup>, Alaa Saleh<sup>2</sup>, Cristóbal Curio<sup>1</sup>
|
| 23 |
+
|
| 24 |
+
<sup>1</sup> Cognitive Systems Group, Reutlingen University, Germany <sup>2</sup> Bosch Sensortec GmbH, Germany
|
| 25 |
+
|
| 26 |
+
[[Paper](https://arxiv.org/abs/2611.32548)]
|
| 27 |
+
[[Project page](https://lschiweck.github.io/setcon/)]
|
| 28 |
+
[[Evaluation data](https://huggingface.co/datasets/lschiweck/SetCon-eval)]
|
| 29 |
+
|
| 30 |
+
SetCon aligns inertial measurement unit (IMU) signals with text for zero-shot activity recognition across wearable
|
| 31 |
+
devices. Its encoder maps a 10-s window of a worn device into the text embedding space of the frozen CLIP ViT-B/32
|
| 32 |
+
text encoder, and the window is classified as the activity whose text embedding lies nearest. A worn device's signal
|
| 33 |
+
depends on its setup, the combination of body site and mounting. Instead of making the encoder invariant to the
|
| 34 |
+
mounting, SetCon replaces full invariance with selective invariance. A calibrator estimates the setup reference of
|
| 35 |
+
each device on its known body site from a few unlabeled windows, and the encoder receives every window rotated so
|
| 36 |
+
that gravity points up together with gravity in the segment frame. Both networks were trained only on IMU simulated
|
| 37 |
+
from the Nymeria motion capture. On 13 real datasets SetCon reaches 56.6 % mean zero-shot accuracy with class names
|
| 38 |
+
and 65.3 % with anchors, against 41.8 % and 46.7 % for AnyMo.
|
| 39 |
+
|
| 40 |
+
The model and its code are released for non-commercial research.
|
| 41 |
+
|
| 42 |
+
## Contents
|
| 43 |
+
|
| 44 |
+
```text
|
| 45 |
+
SetCon/
|
| 46 |
+
├── config.json, model.safetensors seed 1 (default): encoder + calibrator
|
| 47 |
+
├── seed2/, seed3/ the two other stage-2 seeds (same stage-1 model and calibrator)
|
| 48 |
+
├── configuration_setcon.py remote code: configuration
|
| 49 |
+
├── modeling_setcon.py remote code: encoder, calibrator, inference helpers
|
| 50 |
+
├── processing_setcon.py body sites, gravity canonicalization, calibrator input, 6-of-12 selection
|
| 51 |
+
├── setcon/ evaluation package that recomputes the paper's numbers
|
| 52 |
+
├── examples/zero_shot.py load, embed one window, classify against class names
|
| 53 |
+
├── examples/reproduce_table1.py Tab. 1 and the abstract (with --all: Tab. 2, Tab. 3, Sec. 4.3-4.4)
|
| 54 |
+
├── error_bank.json which calibrator the encoders were trained with, and its errors
|
| 55 |
+
├── requirements.txt, CHECKSUMS.txt
|
| 56 |
+
└── LICENSE CC BY-NC 4.0, for the weights and the code
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
Each checkpoint holds the graph encoder (6.4 M parameters plus a 0.13 M text projection) and the calibrator
|
| 60 |
+
(0.48 M), float32, the exponential moving average of the weights after 100 stage-2 epochs. The training-only heads
|
| 61 |
+
are not included.
|
| 62 |
+
|
| 63 |
+
## Usage
|
| 64 |
+
|
| 65 |
+
```python
|
| 66 |
+
import numpy as np
|
| 67 |
+
from transformers import AutoModel
|
| 68 |
+
|
| 69 |
+
model = AutoModel.from_pretrained("lschiweck/SetCon", trust_remote_code=True) # seed 1
|
| 70 |
+
# model = AutoModel.from_pretrained("lschiweck/SetCon", subfolder="seed2", trust_remote_code=True)
|
| 71 |
+
model = model.to("cuda").eval()
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
From raw windows of one device to zero-shot predictions (the processing helpers ship with the repository):
|
| 75 |
+
|
| 76 |
+
```python
|
| 77 |
+
import processing_setcon as P # from a local copy of this repository
|
| 78 |
+
|
| 79 |
+
windows = P.prepare_device(acc, gyro, fs=50) # acc (N, T, 3) m/s^2 with gravity, gyro (N, T, 3) rad/s or None
|
| 80 |
+
ref = model.estimate_reference(windows[context_idx], site="r_wrist") # six unlabeled windows of the same device
|
| 81 |
+
windows = P.set_reference(windows, ref["reference"])
|
| 82 |
+
x = P.place_devices({"r_wrist": windows}) # (N, 200, 22, 9); several devices: one entry per site
|
| 83 |
+
z = model.embed(x) # (N, 512) unit vectors in the CLIP ViT-B/32 text space
|
| 84 |
+
pred = (z @ class_vectors.T).argmax(1) # class_vectors: unit CLIP ViT-B/32 text embeddings
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
`examples/zero_shot.py` runs these steps on real data (a phone on the waist in UCI-HAR). Site names are listed in
|
| 88 |
+
`processing_setcon.SITE_NAMES`, for example `r_wrist`, `l_lowarm`, `c_spine1` (waist), `r_upleg` (thigh pocket),
|
| 89 |
+
`c_head`. A window is 10 s at 20 Hz; `prepare_device` resamples, wrap-pads shorter windows and cuts longer ones.
|
| 90 |
+
`model.select_context(windows12, site)` picks six of twelve unlabeled windows by the calibrator's tilt uncertainty,
|
| 91 |
+
as in the last row of Tab. 1.
|
| 92 |
+
|
| 93 |
+
## Reproducing the paper's numbers
|
| 94 |
+
|
| 95 |
+
```bash
|
| 96 |
+
pip install -r requirements.txt
|
| 97 |
+
hf download lschiweck/SetCon --local-dir SetCon
|
| 98 |
+
hf download lschiweck/SetCon-eval --repo-type dataset --local-dir SetCon-eval
|
| 99 |
+
hf download xiyuanz/UniMTS UniMTS_data.zip --revision 378531dbc1ec649b5bb792fd2e8f4c9a1a3ff99d --local-dir raw
|
| 100 |
+
python SetCon/examples/reproduce_table1.py --unimts-zip raw/UniMTS_data.zip --eval-data SetCon-eval --work work
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
The script checks the sha256 of the archive and of the 54 test files it extracts, builds the inputs of the 18 test
|
| 104 |
+
sets, runs all three seeds and prints every number next to the printed one. `--all` adds Tab. 2, Tab. 3 and the
|
| 105 |
+
numbers of Sec. 4.3 and 4.4 (about 7 min per seed on one H100; seeds can run in parallel with `--step evaluate
|
| 106 |
+
--seeds 2` and a final `--step tables`). The evaluation data also hold the paper's per-window predictions, and the
|
| 107 |
+
script reports how many of your predictions differ from them. In a clean environment with the reference settings
|
| 108 |
+
none differ, and all 29 SetCon numbers of Tab. 1-3 and Sec. 4.3-4.4 equal the printed ones.
|
| 109 |
+
|
| 110 |
+
The test windows come from `UniMTS_data.zip` of the UniMTS release (4,810,820,152 bytes, sha256
|
| 111 |
+
`ad8776dfbfc8acb5d57616f918289e32948a2842b4b54a228d13906e58d1d776`). The archive carries no license, so it is not
|
| 112 |
+
redistributed here. The working folder needs about 1.6 GB (1.2 GB extracted test files, 0.35 GB model inputs).
|
| 113 |
+
|
| 114 |
+
### Expected numbers
|
| 115 |
+
|
| 116 |
+
Mean-13 in %, mean ± sd (ddof 1) over the three stage-2 seeds, as printed in the paper. The seeds share one stage-1
|
| 117 |
+
model and calibrator, and a single seed alone does not give the printed value.
|
| 118 |
+
|
| 119 |
+
| Reading (paper) | Metric | Paper |
|
| 120 |
+
|---|---|---:|
|
| 121 |
+
| 6 of 12 windows (Tab. 1 last row, abstract) | accuracy, names | 56.6 ± 0.6 |
|
| 122 |
+
| | accuracy, anchors | 65.3 ± 0.4 |
|
| 123 |
+
| | macro-F1, names | 51.6 ± 0.7 |
|
| 124 |
+
| | macro-F1, anchors | 62.1 ± 0.4 |
|
| 125 |
+
| | class-mean readout | 91.6 ± 0.2 |
|
| 126 |
+
| 6 random windows (Tab. 1 row 3, Tab. 2) | accuracy, names | 55.9 ± 0.4 |
|
| 127 |
+
| | accuracy, anchors | 64.7 ± 0.6 |
|
| 128 |
+
| | macro-F1, names | 50.2 ± 0.6 |
|
| 129 |
+
| | macro-F1, anchors | 60.5 ± 0.5 |
|
| 130 |
+
| | class-mean readout | 91.5 ± 0.2 |
|
| 131 |
+
| Walking frame (Tab. 2) | accuracy, names / anchors | 54.6 ± 0.2 / 62.7 ± 0.6 |
|
| 132 |
+
| Zeroed reference (Tab. 2) | accuracy, names / anchors | 41.5 ± 0.7 / 48.0 ± 2.1 |
|
| 133 |
+
| One context window (Sec. 4.3) | accuracy, names | 53.7 |
|
| 134 |
+
|
| 135 |
+
With `--all` the script also prints the six groups of Tab. 3 and the remaining SetCon numbers of Sec. 4.3 and 4.4,
|
| 136 |
+
29 numbers in total, each with its per-seed values.
|
| 137 |
+
|
| 138 |
+
For comparison, on the windows of the last row of Tab. 1 the released UniMTS reaches 41.4 / 43.2 and the released
|
| 139 |
+
AnyMo 41.8 / 46.7 (names / anchors). These baselines are not part of this repository.
|
| 140 |
+
|
| 141 |
+
### Fixed settings
|
| 142 |
+
|
| 143 |
+
- **Device and precision.** Encoder on CUDA under bfloat16 autocast with batches of 64 windows; calibrator on CPU in
|
| 144 |
+
float32 with 4 threads. Reference environment: Python 3.9, torch 2.8.0+cu128, numpy 2.0.2, transformers 4.57.6.
|
| 145 |
+
Running the encoder on CPU in float32 or with another batch size changes a small share of the predictions and can
|
| 146 |
+
move a printed digit.
|
| 147 |
+
- **Devices and context.** All test windows of one participant at one site form one device (person ids in the
|
| 148 |
+
evaluation data; datasets without exact ids count as one participant). Draw k = 0..4 picks six context windows per
|
| 149 |
+
device with `numpy.random.default_rng(1000 + k)`. Context windows are never scored. Groups with fewer than 7
|
| 150 |
+
windows get no reference.
|
| 151 |
+
- **6 of 12.** Groups with at least 18 windows draw six extra context windows with
|
| 152 |
+
`numpy.random.default_rng([0xCA12, i, k, g])` (i = index of the dataset in the list of 18, g = group id). The
|
| 153 |
+
calibrator then drops windows one by one until the six with the smallest tilt uncertainty remain.
|
| 154 |
+
- **One context window** (Sec. 4.3): `numpy.random.default_rng([2000, k, g])` picks one of the six.
|
| 155 |
+
- **Class texts.** Names are the class strings of the datasets. An anchor (paper Eq. 8) averages the CLIP embeddings
|
| 156 |
+
of the name, its ten nearest Nymeria narrations and thirty LLM-written descriptions. The paper's exact vectors and
|
| 157 |
+
all their texts are in the evaluation data.
|
| 158 |
+
|
| 159 |
+
## Training
|
| 160 |
+
|
| 161 |
+
Stage 1 pretrains the encoder and the calibrator on IMU simulated on Momentum Human Rig (MHR) bodies fitted to the
|
| 162 |
+
Nymeria motion capture. One movement is simulated under several sets of worn devices, and the calibrator learns each
|
| 163 |
+
simulated device's known mounting. Stage 2 aligns the encoder with the frozen CLIP ViT-B/32 text encoder on Nymeria's
|
| 164 |
+
narrations and on captions that an LLM generates from the measured motion, under calibrator errors drawn from an
|
| 165 |
+
error bank, for 100 epochs. The three released checkpoints are three stage-2 seeds on one stage-1 model. No test
|
| 166 |
+
dataset or test participant is used in training. Training code is not part of this release.
|
| 167 |
+
|
| 168 |
+
## Not included
|
| 169 |
+
|
| 170 |
+
- The language model on top of the encoder (paper Sec. 3.6, the last row of Tab. 2 and the language-model numbers of
|
| 171 |
+
Sec. 4.4). Its numbers cannot be recomputed from this repository.
|
| 172 |
+
- Training code, the simulation and the training data pipeline.
|
| 173 |
+
- The baselines (UniMTS, AnyMo) and the test data themselves.
|
| 174 |
+
|
| 175 |
+
## Intended use and limitations
|
| 176 |
+
|
| 177 |
+
SetCon is meant for non-commercial research on wearable activity recognition, IMU-language representations and
|
| 178 |
+
zero-shot classification. It assumes that the body site of each device is known and that the mounting stays fixed
|
| 179 |
+
while the device is worn. Unscripted daily life, in which devices slip and sites are unknown, remains to be tested.
|
| 180 |
+
Activity recognition reveals what the wearer does, so deployment requires the wearers' informed consent. The model
|
| 181 |
+
must not be the sole basis for clinical or other high-stakes decisions.
|
| 182 |
+
|
| 183 |
+
## License
|
| 184 |
+
|
| 185 |
+
- Model weights: CC BY-NC 4.0 (`LICENSE`), because they were trained on Nymeria (CC BY-NC 4.0). The body model MHR
|
| 186 |
+
used for the simulation is licensed under Apache 2.0.
|
| 187 |
+
- Code in this repository: CC BY-NC 4.0 (`LICENSE`), like the weights.
|
| 188 |
+
- Evaluation data: CC BY-NC 4.0 (separate dataset repository; it contains Nymeria narration sentences).
|
| 189 |
+
- Test data: not included; each benchmark keeps its own terms.
|
| 190 |
+
|
| 191 |
+
## Acknowledgments
|
| 192 |
+
|
| 193 |
+
This research was funded by the European Regional Development Fund (ERDF) within the project 'AIDA' (grant
|
| 194 |
+
FEIH 2476184). L. Schiweck was supported by a scholarship from Bosch Sensortec GmbH. Views and opinions expressed are
|
| 195 |
+
those of the authors only and do not necessarily reflect those of the European Union. Neither the European Union nor
|
| 196 |
+
the granting authority can be held responsible for them.
|
| 197 |
+
|
| 198 |
+
## Citation
|
| 199 |
+
|
| 200 |
+
```bibtex
|
| 201 |
+
@misc{schiweck2026setcon,
|
| 202 |
+
title = {{SetCon}: Setup-Conditioned {IMU}-Language Learning from {3D} Human Motion},
|
| 203 |
+
author = {Schiweck, Lennart and Saleh, Alaa and Curio, Crist{\'o}bal},
|
| 204 |
+
year = {2026},
|
| 205 |
+
eprint = {2611.32548},
|
| 206 |
+
archivePrefix = {arXiv},
|
| 207 |
+
primaryClass = {cs.CV},
|
| 208 |
+
url = {https://arxiv.org/abs/2611.32548}
|
| 209 |
+
}
|
| 210 |
+
```
|
config.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"SetConModel"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_setcon.SetConConfig",
|
| 7 |
+
"AutoModel": "modeling_setcon.SetConModel"
|
| 8 |
+
},
|
| 9 |
+
"calibrator_body_parts": 14,
|
| 10 |
+
"calibrator_components": 2,
|
| 11 |
+
"calibrator_conv_channels": [
|
| 12 |
+
64,
|
| 13 |
+
128,
|
| 14 |
+
128,
|
| 15 |
+
128
|
| 16 |
+
],
|
| 17 |
+
"calibrator_conv_strides": [
|
| 18 |
+
2,
|
| 19 |
+
2,
|
| 20 |
+
2,
|
| 21 |
+
1
|
| 22 |
+
],
|
| 23 |
+
"calibrator_hidden_size": 128,
|
| 24 |
+
"calibrator_set_blocks": 2,
|
| 25 |
+
"calibrator_sides": 3,
|
| 26 |
+
"context_windows": 6,
|
| 27 |
+
"dtype": "float32",
|
| 28 |
+
"embedding_dim": 512,
|
| 29 |
+
"force_scale": 6.199315143837327,
|
| 30 |
+
"frames_per_patch": 4,
|
| 31 |
+
"hidden_size": 256,
|
| 32 |
+
"input_channels": 9,
|
| 33 |
+
"model_type": "setcon",
|
| 34 |
+
"num_graph_blocks": 8,
|
| 35 |
+
"num_patches": 50,
|
| 36 |
+
"num_sites": 22,
|
| 37 |
+
"rate_scale": 0.7396506117362955,
|
| 38 |
+
"sample_rate_hz": 20.0,
|
| 39 |
+
"stage2_epoch": 100,
|
| 40 |
+
"temporal_kernel": 9,
|
| 41 |
+
"text_encoder": "openai/clip ViT-B/32 (frozen)",
|
| 42 |
+
"training_seed": 1,
|
| 43 |
+
"transformers_version": "4.57.6"
|
| 44 |
+
}
|
configuration_setcon.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configuration of the SetCon model (Hugging Face remote code)."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from transformers import PretrainedConfig
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class SetConConfig(PretrainedConfig):
|
| 8 |
+
"""Sizes of the graph encoder and the calibrator, the fixed input scales and where the weights come from.
|
| 9 |
+
|
| 10 |
+
The input scales divide the canonicalized specific force (m/s^2) and angular velocity (rad/s) before the encoder
|
| 11 |
+
and the calibrator see them. They are the per-axis root-mean-square values of simulated joint-center signals on
|
| 12 |
+
500 training clips (paper Eq. 3: kappa_f and kappa_omega).
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
model_type = "setcon"
|
| 16 |
+
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
num_sites: int = 22,
|
| 20 |
+
num_patches: int = 50,
|
| 21 |
+
frames_per_patch: int = 4,
|
| 22 |
+
input_channels: int = 9,
|
| 23 |
+
hidden_size: int = 256,
|
| 24 |
+
num_graph_blocks: int = 8,
|
| 25 |
+
temporal_kernel: int = 9,
|
| 26 |
+
embedding_dim: int = 512,
|
| 27 |
+
force_scale: float = 6.2,
|
| 28 |
+
rate_scale: float = 0.74,
|
| 29 |
+
sample_rate_hz: float = 20.0,
|
| 30 |
+
calibrator_hidden_size: int = 128,
|
| 31 |
+
calibrator_conv_channels: tuple = (64, 128, 128, 128),
|
| 32 |
+
calibrator_conv_strides: tuple = (2, 2, 2, 1),
|
| 33 |
+
calibrator_set_blocks: int = 2,
|
| 34 |
+
calibrator_components: int = 2,
|
| 35 |
+
calibrator_body_parts: int = 14,
|
| 36 |
+
calibrator_sides: int = 3,
|
| 37 |
+
context_windows: int = 6,
|
| 38 |
+
text_encoder: str = "openai/clip ViT-B/32 (frozen)",
|
| 39 |
+
training_seed: int = 1,
|
| 40 |
+
stage2_epoch: int = 100,
|
| 41 |
+
**kwargs,
|
| 42 |
+
):
|
| 43 |
+
super().__init__(**kwargs)
|
| 44 |
+
self.num_sites = int(num_sites)
|
| 45 |
+
self.num_patches = int(num_patches)
|
| 46 |
+
self.frames_per_patch = int(frames_per_patch)
|
| 47 |
+
self.input_channels = int(input_channels)
|
| 48 |
+
self.hidden_size = int(hidden_size)
|
| 49 |
+
self.num_graph_blocks = int(num_graph_blocks)
|
| 50 |
+
self.temporal_kernel = int(temporal_kernel)
|
| 51 |
+
self.embedding_dim = int(embedding_dim)
|
| 52 |
+
self.force_scale = float(force_scale)
|
| 53 |
+
self.rate_scale = float(rate_scale)
|
| 54 |
+
self.sample_rate_hz = float(sample_rate_hz)
|
| 55 |
+
self.calibrator_hidden_size = int(calibrator_hidden_size)
|
| 56 |
+
self.calibrator_conv_channels = [int(c) for c in calibrator_conv_channels]
|
| 57 |
+
self.calibrator_conv_strides = [int(s) for s in calibrator_conv_strides]
|
| 58 |
+
self.calibrator_set_blocks = int(calibrator_set_blocks)
|
| 59 |
+
self.calibrator_components = int(calibrator_components)
|
| 60 |
+
self.calibrator_body_parts = int(calibrator_body_parts)
|
| 61 |
+
self.calibrator_sides = int(calibrator_sides)
|
| 62 |
+
self.context_windows = int(context_windows)
|
| 63 |
+
self.text_encoder = str(text_encoder)
|
| 64 |
+
self.training_seed = int(training_seed)
|
| 65 |
+
self.stage2_epoch = int(stage2_epoch)
|
error_bank.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"about": "Stage-2 error bank (paper Sec. 3.4): errors of the frozen calibrator, estimated from six held-out simulated Nymeria windows per device. The three encoders were trained under these errors. Not used at inference; it documents which calibrator the encoders belong to.",
|
| 3 |
+
"calibrator": "the calibrator.* tensors of model.safetensors, identical in seed 1, seed2/ and seed3/",
|
| 4 |
+
"calibrator_tensors_sha256": "5a0349019c5f7ac0eaacc9dd3fd899dff7dfc5472581264ff044c3cb3f094008",
|
| 5 |
+
"calibrator_tensors_sha256_rule": "sha256 over every calibrator.* tensor in sorted key order: key name, then raw bytes",
|
| 6 |
+
"context_windows": 6,
|
| 7 |
+
"devices_per_site_and_gyroscope_condition": 2000,
|
| 8 |
+
"sites": 22,
|
| 9 |
+
"heldout_recordings": 57,
|
| 10 |
+
"error_deg": {
|
| 11 |
+
"with_gyroscope": {
|
| 12 |
+
"up_axis": {
|
| 13 |
+
"median": 4.14,
|
| 14 |
+
"q25": 2.37,
|
| 15 |
+
"q75": 7.45,
|
| 16 |
+
"p90": 13.09
|
| 17 |
+
},
|
| 18 |
+
"reference_channels": {
|
| 19 |
+
"median": 19.34,
|
| 20 |
+
"q25": 5.02,
|
| 21 |
+
"q75": 39.17,
|
| 22 |
+
"p90": 64.3
|
| 23 |
+
}
|
| 24 |
+
},
|
| 25 |
+
"acceleration_only": {
|
| 26 |
+
"up_axis": {
|
| 27 |
+
"median": 4.7,
|
| 28 |
+
"q25": 2.7,
|
| 29 |
+
"q75": 8.41,
|
| 30 |
+
"p90": 14.78
|
| 31 |
+
},
|
| 32 |
+
"reference_channels": {
|
| 33 |
+
"median": 20.17,
|
| 34 |
+
"q25": 6.31,
|
| 35 |
+
"q75": 39.02,
|
| 36 |
+
"p90": 63.73
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
},
|
| 40 |
+
"note": "Reference channels = gravity in the segment frame; their horizontal part also depends on the forward sign that gait leaves open."
|
| 41 |
+
}
|
examples/reproduce_table1.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Recompute the SetCon numbers of the paper from the released weights and compare them with the printed values.
|
| 2 |
+
|
| 3 |
+
Default: Tab. 1 (both SetCon rows) and the abstract (Mean-13 accuracy 56.6 % with class names, 65.3 % with anchors)
|
| 4 |
+
for all three stage-2 seeds. With --all also Tab. 2 (reference at test), Tab. 3 and the numbers of Sec. 4.3-4.4.
|
| 5 |
+
|
| 6 |
+
python examples/reproduce_table1.py --unimts-zip UniMTS_data.zip --eval-data <SetCon-eval folder or hub id> \
|
| 7 |
+
--work work/
|
| 8 |
+
|
| 9 |
+
Steps (each can run alone, e.g. one seed per GPU):
|
| 10 |
+
--step prepare extract and check the 54 test files, build the model-ready caches (CPU, a few minutes)
|
| 11 |
+
--step evaluate --seeds 2 embeddings and predictions of one seed (GPU, about 5 min for the default readings)
|
| 12 |
+
--step tables the paper's numbers from the per-seed results
|
| 13 |
+
|
| 14 |
+
Reference settings: CUDA with bfloat16 autocast and batches of 64, calibrator on CPU in float32, torch 2.8.0+cu128,
|
| 15 |
+
numpy 2.0.2. A CPU run or another batch size changes a few predictions and can move a printed digit.
|
| 16 |
+
"""
|
| 17 |
+
import argparse
|
| 18 |
+
import json
|
| 19 |
+
import sys
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
|
| 24 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 25 |
+
from setcon import eval_data_dir, load_model # noqa: E402
|
| 26 |
+
from setcon import data, tables # noqa: E402
|
| 27 |
+
from setcon.evaluate import evaluate_seed # noqa: E402
|
| 28 |
+
from setcon.protocol import DATASETS, EvalData # noqa: E402
|
| 29 |
+
|
| 30 |
+
MAIN_READINGS = ("six_random", "six_of_twelve")
|
| 31 |
+
ALL_READINGS = ("six_random", "six_of_twelve", "walking_frame", "zeroed", "one_window")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def main():
|
| 35 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 36 |
+
ap.add_argument("--work", required=True, help="working folder (raw files, caches, results)")
|
| 37 |
+
ap.add_argument("--eval-data", default=None, help="SetCon-eval folder or hub id (default: the hub dataset)")
|
| 38 |
+
ap.add_argument("--unimts-zip", default=None, help="UniMTS_data.zip (extracted into <work>/UniMTS_data)")
|
| 39 |
+
ap.add_argument("--unimts-dir", default=None, help="already extracted UniMTS_data folder (checked by sha256)")
|
| 40 |
+
ap.add_argument("--model", default=None, help="model folder or hub id (default: this repository)")
|
| 41 |
+
ap.add_argument("--seeds", default="1,2,3")
|
| 42 |
+
ap.add_argument("--step", choices=("all", "prepare", "evaluate", "tables"), default="all")
|
| 43 |
+
ap.add_argument("--all", action="store_true", help="every SetCon number of Tab. 1-3 and Sec. 4.3-4.4")
|
| 44 |
+
ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
|
| 45 |
+
a = ap.parse_args()
|
| 46 |
+
work = Path(a.work)
|
| 47 |
+
ed_dir = eval_data_dir(a.eval_data)
|
| 48 |
+
seeds = [int(s) for s in a.seeds.split(",")]
|
| 49 |
+
readings = ALL_READINGS if a.all else MAIN_READINGS
|
| 50 |
+
caches = work / "benchmarks"
|
| 51 |
+
|
| 52 |
+
if a.step in ("all", "prepare"):
|
| 53 |
+
if a.unimts_zip:
|
| 54 |
+
print("extracting and checking the test files ...", flush=True)
|
| 55 |
+
raw = data.extract_test_files(a.unimts_zip, work / "UniMTS_data", ed_dir)
|
| 56 |
+
elif a.unimts_dir:
|
| 57 |
+
raw = Path(a.unimts_dir)
|
| 58 |
+
data.verify_test_files(raw, ed_dir)
|
| 59 |
+
else:
|
| 60 |
+
raise SystemExit("--unimts-zip or --unimts-dir is required for the prepare step")
|
| 61 |
+
print("building the model-ready caches ...", flush=True)
|
| 62 |
+
data.write_benchmarks(raw, caches, [d for d in DATASETS if not (caches / f"{d}.npz").exists()])
|
| 63 |
+
|
| 64 |
+
if a.step in ("all", "evaluate"):
|
| 65 |
+
if a.device != "cuda":
|
| 66 |
+
print("note: no CUDA - the numbers can differ from the paper in the last digit", flush=True)
|
| 67 |
+
ed = EvalData(ed_dir)
|
| 68 |
+
for seed in seeds:
|
| 69 |
+
model = load_model(seed=seed, model=a.model)
|
| 70 |
+
evaluate_seed(model, seed, caches, ed, work / "results", readings=readings, device=a.device)
|
| 71 |
+
|
| 72 |
+
if a.step in ("all", "tables"):
|
| 73 |
+
R = tables.Results(work / "results", seeds, ed_dir)
|
| 74 |
+
numbers = tables.main_numbers(R)
|
| 75 |
+
paper = dict(tables.PAPER_MAIN)
|
| 76 |
+
if a.all:
|
| 77 |
+
numbers.update(tables.more_numbers(R))
|
| 78 |
+
paper.update(tables.PAPER_MORE)
|
| 79 |
+
rows = tables.compare(numbers, paper)
|
| 80 |
+
print(tables.format_rows(rows))
|
| 81 |
+
n_ok = sum(r[-1] for r in rows)
|
| 82 |
+
print(f"\n{n_ok} of {len(rows)} numbers equal the printed values (seeds {', '.join(map(str, seeds))}).")
|
| 83 |
+
(work / "results" / "paper_numbers.json").write_text(json.dumps(
|
| 84 |
+
dict(seeds=seeds, numbers=numbers, matches={r[0]: r[-1] for r in rows}), indent=1) + "\n")
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
if __name__ == "__main__":
|
| 88 |
+
main()
|
examples/zero_shot.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Minimal zero-shot example on real data: a smartphone on the waist (UCI-HAR test split, participant 2).
|
| 2 |
+
|
| 3 |
+
1. load SetCon (seed 1) through transformers
|
| 4 |
+
2. turn the phone's raw windows into model windows (gravity canonicalization, 20 Hz, 10 s)
|
| 5 |
+
3. estimate the phone's setup reference from six unlabeled windows of the same participant
|
| 6 |
+
4. embed one window and classify it against the CLIP ViT-B/32 embeddings of the class names
|
| 7 |
+
|
| 8 |
+
python examples/zero_shot.py --unimts-dir <folder with UCIHAR/X_test.npy> (see setcon/data.py for the download)
|
| 9 |
+
"""
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
import sys
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch
|
| 17 |
+
|
| 18 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 19 |
+
from setcon import load_model, processing # noqa: E402
|
| 20 |
+
|
| 21 |
+
ap = argparse.ArgumentParser()
|
| 22 |
+
ap.add_argument("--unimts-dir", required=True)
|
| 23 |
+
ap.add_argument("--window", type=int, default=150, help="window of participant 2 to classify (0-301)")
|
| 24 |
+
a = ap.parse_args()
|
| 25 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 26 |
+
|
| 27 |
+
model = load_model(seed=1, device=device)
|
| 28 |
+
|
| 29 |
+
# UCI-HAR: 50 Hz, columns 3-5 angular velocity (rad/s), 6-8 total acceleration (g). Participant 2 = windows 0-301.
|
| 30 |
+
d = Path(a.unimts_dir) / "UCIHAR"
|
| 31 |
+
X = np.load(d / "X_test.npy")[:302].astype(np.float64)
|
| 32 |
+
y = np.load(d / "y_test.npy")[:302]
|
| 33 |
+
classes = [" ".join(v) for v in json.loads((d / "UCIHAR.json").read_text())["label_dictionary"].values()]
|
| 34 |
+
windows = processing.prepare_device(acc=X[:, :, 6:9] * 9.80665, gyro=X[:, :, 3:6], fs=50) # (302, 200, 9)
|
| 35 |
+
|
| 36 |
+
# Setup reference from six unlabeled windows of the same device; they are not classified.
|
| 37 |
+
context = np.random.default_rng(0).choice(len(windows), 6, replace=False)
|
| 38 |
+
ref = model.estimate_reference(windows[context], site="c_spine1")
|
| 39 |
+
print(f"setup reference estimated, tilt uncertainty {ref['tilt_sigma_deg']:.1f} deg")
|
| 40 |
+
windows = processing.set_reference(windows, ref["reference"])
|
| 41 |
+
x = processing.place_devices({"c_spine1": windows}) # (302, 200, 22, 9)
|
| 42 |
+
|
| 43 |
+
# Class names in the CLIP ViT-B/32 text space (the frozen text encoder SetCon was aligned with).
|
| 44 |
+
import clip # noqa: E402
|
| 45 |
+
clip_model, _ = clip.load("ViT-B/32", device=device)
|
| 46 |
+
with torch.no_grad():
|
| 47 |
+
text = clip_model.encode_text(clip.tokenize(classes, truncate=True).to(device)).float()
|
| 48 |
+
text = torch.nn.functional.normalize(text, dim=-1).cpu().numpy()
|
| 49 |
+
|
| 50 |
+
z = model.embed(x[a.window:a.window + 1]) # (1, 512)
|
| 51 |
+
scores = z @ text.T
|
| 52 |
+
print(f"window {a.window}: predicted '{classes[int(scores.argmax())]}', true '{classes[int(y[a.window])]}'")
|
| 53 |
+
print("cosine per class:", ", ".join(f"{c} {s:.3f}" for c, s in zip(classes, scores[0])))
|
| 54 |
+
|
| 55 |
+
scored = np.setdiff1d(np.arange(len(x)), context)
|
| 56 |
+
pred = (model.embed(x[scored]) @ text.T).argmax(1)
|
| 57 |
+
print(f"participant 2, {len(scored)} windows: accuracy {100 * np.mean(pred == y[scored]):.1f} % with class names")
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:50dc00dfa5bf377833329f3933929c9cc0eadc2bf66ba58fa9d45696d5c9bc9b
|
| 3 |
+
size 27962388
|
modeling_setcon.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SetCon: setup-conditioned IMU encoder with its calibrator (Hugging Face remote code).
|
| 2 |
+
|
| 3 |
+
model = AutoModel.from_pretrained("<repo>", trust_remote_code=True) # seed 1
|
| 4 |
+
model = AutoModel.from_pretrained("<repo>", subfolder="seed2", trust_remote_code=True)
|
| 5 |
+
|
| 6 |
+
Two networks share one checkpoint:
|
| 7 |
+
encoder spatio-temporal graph network over 22 body sites and 0.2-s patches -> 512-d window embedding in the
|
| 8 |
+
space of the frozen CLIP ViT-B/32 text encoder (paper Sec. 3.3)
|
| 9 |
+
calibrator estimates the setup reference of one device, the rotation from device axes into the segment frame,
|
| 10 |
+
from a few unlabeled windows, as a mixture of two Matrix-Fisher densities on SO(3) (paper Sec. 3.2)
|
| 11 |
+
|
| 12 |
+
Input preparation (gravity canonicalization, site names) lives in processing_setcon.py.
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn as nn
|
| 19 |
+
import torch.nn.functional as F
|
| 20 |
+
from transformers import PreTrainedModel
|
| 21 |
+
|
| 22 |
+
from .configuration_setcon import SetConConfig
|
| 23 |
+
from .processing_setcon import (BODY_PART_OF_SITE, SIDE_OF_SITE, SITE_INDEX, SITE_PARENTS, calibrator_input,
|
| 24 |
+
select_by_elimination, tilt_score, tilt_sigma)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# ---------------------------------------------------------------------------------------------- encoder
|
| 28 |
+
def body_adjacency(parents=SITE_PARENTS):
|
| 29 |
+
"""A[partition, receiver, sender] for the partitions self, parent -> child, child -> parent (row-normalized)."""
|
| 30 |
+
n = len(parents)
|
| 31 |
+
a = torch.zeros(3, n, n)
|
| 32 |
+
a[0] = torch.eye(n)
|
| 33 |
+
for child, parent in enumerate(parents):
|
| 34 |
+
if parent >= 0:
|
| 35 |
+
a[1, child, parent] = 1
|
| 36 |
+
a[2, parent, child] = 1
|
| 37 |
+
return a / a.sum(-1, keepdim=True).clamp_min(1)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class GraphBlock(nn.Module):
|
| 41 |
+
"""One residual block: graph convolution over the sites (learned edge weights), then a convolution along time
|
| 42 |
+
over `temporal_kernel` patches. Tensors are (batch, sites, patches, width); padded patches stay zero."""
|
| 43 |
+
|
| 44 |
+
def __init__(self, width, temporal_kernel=9):
|
| 45 |
+
super().__init__()
|
| 46 |
+
self.norm_spatial = nn.LayerNorm(width)
|
| 47 |
+
self.spatial = nn.Linear(width, 3 * width)
|
| 48 |
+
self.norm_temporal = nn.LayerNorm(width)
|
| 49 |
+
self.temporal = nn.Conv2d(width, width, (temporal_kernel, 1), padding=(temporal_kernel // 2, 0))
|
| 50 |
+
self.register_buffer("adjacency", body_adjacency())
|
| 51 |
+
self.edge_importance = nn.Parameter(torch.ones(3, len(SITE_PARENTS), len(SITE_PARENTS)))
|
| 52 |
+
|
| 53 |
+
def forward(self, x, patch_valid):
|
| 54 |
+
b, v, p, d = x.shape
|
| 55 |
+
valid = patch_valid[:, None, :, None]
|
| 56 |
+
h = self.spatial(self.norm_spatial(x)).reshape(b, v, p, 3, d)
|
| 57 |
+
a = self.adjacency * self.edge_importance
|
| 58 |
+
h = torch.einsum("bspkd,kvs->bvpd", h, a)
|
| 59 |
+
h = self.norm_temporal(F.gelu(h))
|
| 60 |
+
h = h.masked_fill(~valid, 0) # biases must not turn padded time into evidence
|
| 61 |
+
h = self.temporal(h.permute(0, 3, 2, 1)).permute(0, 3, 2, 1)
|
| 62 |
+
return (x + h).masked_fill(~valid, 0)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class SetConEncoder(nn.Module):
|
| 66 |
+
"""Patch tokens of every site -> graph blocks -> mean over worn sites and valid patches -> text space.
|
| 67 |
+
|
| 68 |
+
A worn site holds one token per patch (a linear map of its 4 frames x 9 channels). A site without a device holds
|
| 69 |
+
a learned mask token that relays information between worn sites; its output is never pooled. Every token also
|
| 70 |
+
gets learned embeddings of its site, its patch and its gyroscope flag, plus a linear map of the 44 worn-site and
|
| 71 |
+
gyroscope flags (the setup token)."""
|
| 72 |
+
|
| 73 |
+
def __init__(self, config):
|
| 74 |
+
super().__init__()
|
| 75 |
+
d, S, P = config.hidden_size, config.num_sites, config.num_patches
|
| 76 |
+
patch_values = config.frames_per_patch * config.input_channels
|
| 77 |
+
self.patch_embed = nn.Linear(patch_values, d)
|
| 78 |
+
self.site_embedding = nn.Parameter(torch.zeros(S, d))
|
| 79 |
+
self.time_embedding = nn.Parameter(torch.zeros(P, d))
|
| 80 |
+
self.gyro_flag_embedding = nn.Parameter(torch.zeros(2, d))
|
| 81 |
+
self.mask_token = nn.Parameter(torch.zeros(d))
|
| 82 |
+
self.setup_embed = nn.Linear(2 * S, d)
|
| 83 |
+
self.blocks = nn.ModuleList([GraphBlock(d, config.temporal_kernel) for _ in range(config.num_graph_blocks)])
|
| 84 |
+
self.final_norm = nn.LayerNorm(d)
|
| 85 |
+
self.text_projection = nn.Linear(d, config.embedding_dim)
|
| 86 |
+
self.logit_scale = nn.Parameter(torch.zeros(())) # learned CLIP temperature (log); not needed to embed
|
| 87 |
+
|
| 88 |
+
def forward(self, x, worn, gyro, patch_valid):
|
| 89 |
+
"""x (B, sites, patches, 36) scaled patch values, worn / gyro (B, sites) bool, patch_valid (B, patches) bool
|
| 90 |
+
-> unit embeddings (B, embedding_dim)."""
|
| 91 |
+
observed = worn[:, :, None] & patch_valid[:, None, :]
|
| 92 |
+
tok = self.patch_embed(x.masked_fill(~observed[..., None], 0))
|
| 93 |
+
tok = torch.where(observed[..., None], tok, self.mask_token)
|
| 94 |
+
gyro = gyro & worn
|
| 95 |
+
setup = self.setup_embed(torch.cat([worn.float(), gyro.float()], dim=1))
|
| 96 |
+
tok = tok + self.site_embedding[None, :, None, :] + self.time_embedding[None, None, :, :] \
|
| 97 |
+
+ self.gyro_flag_embedding[gyro.long()][:, :, None, :] + setup[:, None, None, :]
|
| 98 |
+
tok = tok.masked_fill(~patch_valid[:, None, :, None], 0)
|
| 99 |
+
for block in self.blocks:
|
| 100 |
+
tok = block(tok, patch_valid)
|
| 101 |
+
e = self.final_norm(tok).masked_fill(~observed[..., None], 0)
|
| 102 |
+
w = observed.float()[..., None]
|
| 103 |
+
pooled = (e * w).sum(dim=(1, 2)) / w.sum(dim=(1, 2)).clamp(min=1.0)
|
| 104 |
+
return F.normalize(self.text_projection(pooled), dim=-1)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
# ---------------------------------------------------------------------------------------------- calibrator
|
| 108 |
+
def gram_schmidt(v):
|
| 109 |
+
"""(..., 6) -> rotation matrices (..., 3, 3) whose first two columns follow the two 3-vectors."""
|
| 110 |
+
a1, a2 = v[..., 0:3], v[..., 3:6]
|
| 111 |
+
b1 = F.normalize(a1, dim=-1, eps=1e-6)
|
| 112 |
+
b2 = F.normalize(a2 - (b1 * a2).sum(-1, keepdim=True) * b1, dim=-1, eps=1e-6)
|
| 113 |
+
b3 = torch.cross(b1, b2, dim=-1)
|
| 114 |
+
return torch.stack([b1, b2, b3], dim=-1)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
CONCENTRATION_MAX = 3000.0
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class SetConCalibrator(nn.Module):
|
| 121 |
+
"""Set network over the unlabeled windows of one device.
|
| 122 |
+
|
| 123 |
+
Each window (T frames x 7 channels: acceleration and angular velocity in device axes, each divided by one scalar,
|
| 124 |
+
plus a missing-gyroscope flag) passes a small 1-D CNN; embeddings of body part, side and gyroscope flag are added;
|
| 125 |
+
two per-window residual MLP blocks follow; the set is pooled order-invariantly as [mean; max]; an MLP head outputs
|
| 126 |
+
a mixture of two Matrix-Fisher densities F_c = M_c V_c diag(s_c) V_c^T over the setup reference."""
|
| 127 |
+
|
| 128 |
+
def __init__(self, config):
|
| 129 |
+
super().__init__()
|
| 130 |
+
d = config.calibrator_hidden_size
|
| 131 |
+
self.conv_layers = nn.ModuleList()
|
| 132 |
+
c_in = 7
|
| 133 |
+
for c_out, stride in zip(config.calibrator_conv_channels, config.calibrator_conv_strides):
|
| 134 |
+
self.conv_layers.append(nn.ModuleDict(dict(
|
| 135 |
+
conv=nn.Conv1d(c_in, c_out, 5, stride=stride, padding=2), norm=nn.GroupNorm(8, c_out))))
|
| 136 |
+
c_in = c_out
|
| 137 |
+
self.strides = tuple(config.calibrator_conv_strides)
|
| 138 |
+
self.window_mlp = nn.Sequential(nn.Linear(2 * c_in, d), nn.GELU(), nn.Linear(d, d))
|
| 139 |
+
self.body_part_embedding = nn.Embedding(config.calibrator_body_parts, d)
|
| 140 |
+
self.side_embedding = nn.Embedding(config.calibrator_sides, d)
|
| 141 |
+
self.missing_gyro_embedding = nn.Embedding(2, d)
|
| 142 |
+
self.set_blocks = nn.ModuleList([nn.ModuleDict(dict(
|
| 143 |
+
norm=nn.LayerNorm(d), mlp=nn.Sequential(nn.Linear(d, 2 * d), nn.GELU(), nn.Linear(2 * d, d))))
|
| 144 |
+
for _ in range(config.calibrator_set_blocks)])
|
| 145 |
+
self.pool_norm = nn.LayerNorm(d)
|
| 146 |
+
self.pool_mlp = nn.Sequential(nn.Linear(2 * d, d), nn.GELU(), nn.Linear(d, d))
|
| 147 |
+
self.n_components = config.calibrator_components
|
| 148 |
+
self.head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, 2 * d), nn.GELU(), nn.Linear(2 * d, self.n_components * 16))
|
| 149 |
+
|
| 150 |
+
def window_features(self, w, valid):
|
| 151 |
+
"""w (B*, T, 7), valid (B*, T) -> (B*, d): CNN, then masked mean and max over time."""
|
| 152 |
+
dtype = self.window_mlp[0].weight.dtype
|
| 153 |
+
h = w.to(dtype).transpose(1, 2)
|
| 154 |
+
m = valid.to(dtype)[:, None, :]
|
| 155 |
+
for layer, stride in zip(self.conv_layers, self.strides):
|
| 156 |
+
h = F.gelu(layer["norm"](layer["conv"](h * m)))
|
| 157 |
+
if stride > 1:
|
| 158 |
+
m = F.max_pool1d(m, kernel_size=stride, stride=stride, ceil_mode=True)[..., :h.shape[-1]]
|
| 159 |
+
count = m.sum(-1).clamp(min=1.0)
|
| 160 |
+
mean = (h * m).sum(-1) / count
|
| 161 |
+
mx = h.masked_fill(m < 0.5, -1e4).amax(-1)
|
| 162 |
+
mx = torch.where(m.sum(-1) > 0, mx, torch.zeros_like(mx))
|
| 163 |
+
return self.window_mlp(torch.cat([mean, mx], -1))
|
| 164 |
+
|
| 165 |
+
def forward(self, windows, valid, set_mask, body_part, side, gyro_missing):
|
| 166 |
+
"""windows (B, N, T, 7), valid (B, N, T), set_mask (B, N) True = window present, body_part / side /
|
| 167 |
+
gyro_missing (B,). Returns dict(M, V (B, C, 3, 3), s (B, C, 3), logit (B, C))."""
|
| 168 |
+
B, N, T, _ = windows.shape
|
| 169 |
+
f = self.window_features(windows.reshape(B * N, T, -1), valid.reshape(B * N, T)).reshape(B, N, -1)
|
| 170 |
+
meta = self.body_part_embedding(body_part) + self.side_embedding(side) \
|
| 171 |
+
+ self.missing_gyro_embedding(gyro_missing.long())
|
| 172 |
+
h = f + meta[:, None]
|
| 173 |
+
for block in self.set_blocks:
|
| 174 |
+
h = h + block["mlp"](block["norm"](h))
|
| 175 |
+
x = self.pool_norm(h)
|
| 176 |
+
m = set_mask.to(x.dtype)[..., None]
|
| 177 |
+
count = m.sum(1).clamp(min=1.0)
|
| 178 |
+
mean = (x * m).sum(1) / count
|
| 179 |
+
mx = x.masked_fill(m < 0.5, -1e4).amax(1)
|
| 180 |
+
mx = torch.where(count > 0.5, mx, torch.zeros_like(mx))
|
| 181 |
+
o = self.head(self.pool_mlp(torch.cat([mean, mx], -1)) + meta)
|
| 182 |
+
o = (o.float() if o.dtype in (torch.float16, torch.bfloat16) else o).reshape(B, self.n_components, 16)
|
| 183 |
+
M = gram_schmidt(o[..., 0:6])
|
| 184 |
+
V = gram_schmidt(o[..., 6:12])
|
| 185 |
+
s = CONCENTRATION_MAX * torch.sigmoid(o[..., 12:15] - 8.0)
|
| 186 |
+
return dict(M=M, V=V, s=s, logit=o[..., 15])
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
# ---------------------------------------------------------------------------------------------- model
|
| 190 |
+
class SetConModel(PreTrainedModel):
|
| 191 |
+
"""Encoder + calibrator of one SetCon checkpoint, with NumPy helpers for inference.
|
| 192 |
+
|
| 193 |
+
Reference settings of the paper: encoder on CUDA under bfloat16 autocast with batches of 64 windows; calibrator
|
| 194 |
+
on CPU in float32. Other devices, precisions or batch sizes give embeddings that differ in the last bits."""
|
| 195 |
+
|
| 196 |
+
config_class = SetConConfig
|
| 197 |
+
base_model_prefix = "setcon"
|
| 198 |
+
main_input_name = "windows"
|
| 199 |
+
|
| 200 |
+
def __init__(self, config: SetConConfig):
|
| 201 |
+
super().__init__(config)
|
| 202 |
+
self.encoder = SetConEncoder(config)
|
| 203 |
+
self.calibrator = SetConCalibrator(config)
|
| 204 |
+
self.post_init()
|
| 205 |
+
|
| 206 |
+
def _init_weights(self, module):
|
| 207 |
+
"""Weights always come from a checkpoint; nothing to initialize."""
|
| 208 |
+
|
| 209 |
+
# ---------------------------------------------------------------- encoder
|
| 210 |
+
def encoder_inputs(self, windows):
|
| 211 |
+
"""(B, 200, 22, 9) float tensor -> encoder arguments (patch values, worn, gyro, patch_valid)."""
|
| 212 |
+
cfg = self.config
|
| 213 |
+
xb = windows.float().clone()
|
| 214 |
+
worn = xb.abs().sum(dim=(1, 3)) > 0
|
| 215 |
+
gyro = xb[..., 3:6].abs().sum(dim=(1, 3)) > 0
|
| 216 |
+
frame_valid = xb.abs().sum(dim=(2, 3)) > 0
|
| 217 |
+
patch_valid = frame_valid.reshape(-1, cfg.num_patches, cfg.frames_per_patch).all(dim=2)
|
| 218 |
+
xb[..., 0:3] /= cfg.force_scale
|
| 219 |
+
xb[..., 3:6] /= cfg.rate_scale
|
| 220 |
+
x = xb.permute(0, 2, 1, 3).reshape(-1, cfg.num_sites, cfg.num_patches,
|
| 221 |
+
cfg.frames_per_patch * cfg.input_channels)
|
| 222 |
+
return x, worn, gyro, patch_valid
|
| 223 |
+
|
| 224 |
+
def forward(self, windows):
|
| 225 |
+
"""windows (B, 200, 22, 9) -> unit embeddings (B, 512) in the CLIP ViT-B/32 text space."""
|
| 226 |
+
x, worn, gyro, patch_valid = self.encoder_inputs(windows)
|
| 227 |
+
return self.encoder(x, worn, gyro, patch_valid)
|
| 228 |
+
|
| 229 |
+
@torch.no_grad()
|
| 230 |
+
def embed(self, windows, batch_size=64):
|
| 231 |
+
"""NumPy windows (N, 200, 22, 9) -> NumPy unit embeddings (N, 512) float32, computed on the encoder's device
|
| 232 |
+
(bfloat16 autocast on CUDA)."""
|
| 233 |
+
device = next(self.encoder.parameters()).device
|
| 234 |
+
out = []
|
| 235 |
+
for i in range(0, len(windows), batch_size):
|
| 236 |
+
x, worn, gyro, patch_valid = self.encoder_inputs(torch.from_numpy(np.asarray(windows[i:i + batch_size])))
|
| 237 |
+
with torch.autocast("cuda", dtype=torch.bfloat16, enabled=device.type == "cuda"):
|
| 238 |
+
z = self.encoder(x.to(device), worn.to(device), gyro.to(device), patch_valid.to(device))
|
| 239 |
+
out.append(z.float().cpu())
|
| 240 |
+
return torch.cat(out).numpy() if out else np.zeros((0, self.config.embedding_dim), np.float32)
|
| 241 |
+
|
| 242 |
+
# ---------------------------------------------------------------- calibrator
|
| 243 |
+
@torch.no_grad()
|
| 244 |
+
def calibrate_batch(self, inputs, valid, sites, gyro_missing):
|
| 245 |
+
"""One calibrator pass over many devices with the same number of context windows.
|
| 246 |
+
|
| 247 |
+
inputs (B, n, T, 7) float32 and valid (B, n, T) from processing_setcon.calibrator_input, sites (B,) site
|
| 248 |
+
indices, gyro_missing (B,) bool. Returns NumPy float64 arrays: reference (B, 3, 3) = mode of the heaviest
|
| 249 |
+
component, and the mixture parameters M, V, s, logit."""
|
| 250 |
+
device = next(self.calibrator.parameters()).device
|
| 251 |
+
w = torch.from_numpy(np.stack(inputs) if isinstance(inputs, (list, tuple)) else inputs).float()
|
| 252 |
+
v = torch.from_numpy(np.stack(valid) if isinstance(valid, (list, tuple)) else valid)
|
| 253 |
+
site = torch.as_tensor(np.asarray(sites)).long()
|
| 254 |
+
part = torch.as_tensor(np.asarray(BODY_PART_OF_SITE))[site]
|
| 255 |
+
side = torch.as_tensor(np.asarray(SIDE_OF_SITE))[site]
|
| 256 |
+
set_mask = torch.ones(w.shape[:2], dtype=torch.bool)
|
| 257 |
+
out = self.calibrator(w.to(device), v.to(device), set_mask.to(device), part.to(device), side.to(device),
|
| 258 |
+
torch.tensor(list(gyro_missing)).to(device))
|
| 259 |
+
heaviest = out["logit"].argmax(-1)
|
| 260 |
+
reference = out["M"][torch.arange(len(heaviest), device=heaviest.device), heaviest]
|
| 261 |
+
res = {k: out[k].double().cpu().numpy() for k in ("M", "V", "s", "logit")}
|
| 262 |
+
res["reference"] = reference.double().cpu().numpy()
|
| 263 |
+
return res
|
| 264 |
+
|
| 265 |
+
def estimate_reference(self, context, site, has_gyro=None):
|
| 266 |
+
"""Setup reference of one device from its unlabeled context windows.
|
| 267 |
+
|
| 268 |
+
context (n, 200, 9) windows of the device as prepared by processing_setcon.prepare_device, site a name from
|
| 269 |
+
processing_setcon.SITE_NAMES. Returns dict(reference (3, 3), tilt_sigma_deg)."""
|
| 270 |
+
context = np.asarray(context, np.float32)
|
| 271 |
+
if has_gyro is None:
|
| 272 |
+
has_gyro = bool(np.abs(context[..., 3:6]).sum() > 0)
|
| 273 |
+
w, v = calibrator_input(context, has_gyro, self.config.force_scale, self.config.rate_scale)
|
| 274 |
+
res = self.calibrate_batch(w[None], v[None], [SITE_INDEX[site]], [not has_gyro])
|
| 275 |
+
c = int(res["logit"][0].argmax())
|
| 276 |
+
sigma = float(tilt_sigma(res["M"][0, c], res["V"][0, c], res["s"][0, c]))
|
| 277 |
+
return dict(reference=res["reference"][0], tilt_sigma_deg=float(np.degrees(sigma)))
|
| 278 |
+
|
| 279 |
+
def select_context(self, windows, site, keep=6, has_gyro=None):
|
| 280 |
+
"""Paper Sec. 3.5: from a pool of unlabeled windows of one device (n, 200, 9), repeatedly drop the window
|
| 281 |
+
whose removal leaves the smallest tilt uncertainty until `keep` remain. Returns their positions."""
|
| 282 |
+
windows = np.asarray(windows, np.float32)
|
| 283 |
+
if has_gyro is None:
|
| 284 |
+
has_gyro = bool(np.abs(windows[..., 3:6]).sum() > 0)
|
| 285 |
+
w, v = calibrator_input(windows, has_gyro, self.config.force_scale, self.config.rate_scale)
|
| 286 |
+
site_idx = SITE_INDEX[site]
|
| 287 |
+
|
| 288 |
+
def score(requests):
|
| 289 |
+
res = self.calibrate_batch(np.stack([w[list(p)] for _, p in requests]),
|
| 290 |
+
np.stack([v[list(p)] for _, p in requests]),
|
| 291 |
+
[site_idx] * len(requests), [not has_gyro] * len(requests))
|
| 292 |
+
sc = tilt_score(res["M"], res["V"], res["s"], res["logit"])
|
| 293 |
+
return {(key, p): float(sc[i]) for i, (key, p) in enumerate(requests)}
|
| 294 |
+
|
| 295 |
+
return select_by_elimination({0: len(windows)}, score, keep)[0]
|
processing_setcon.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Input preparation for SetCon: body sites, gravity canonicalization and the calibrator input.
|
| 2 |
+
|
| 3 |
+
Everything here is plain NumPy/SciPy. The file is loaded by `modeling_setcon.py` (Hugging Face remote code) and
|
| 4 |
+
can also be imported directly (`import processing_setcon`) by the evaluation package in this repository.
|
| 5 |
+
|
| 6 |
+
Model input contract
|
| 7 |
+
--------------------
|
| 8 |
+
A window is 10 s at 20 Hz (200 frames) on a graph of 22 body sites. Every worn site carries nine channels:
|
| 9 |
+
|
| 10 |
+
channels 0-2 specific force (m/s^2), rotated so that the estimated gravity direction points up (+y)
|
| 11 |
+
channels 3-5 angular velocity (rad/s), rotated by the same rotation; zero for a device without gyroscope
|
| 12 |
+
channels 6-8 the reference channels: the gravity direction in the segment frame, Q g_hat(t), where Q is the
|
| 13 |
+
setup reference of the device (see `SetConModel.estimate_reference`); zero when no reference exists
|
| 14 |
+
|
| 15 |
+
Sites without a device are all zero. A frame counts as valid when any of its channels is non-zero.
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
SAMPLE_RATE_HZ = 20.0
|
| 22 |
+
WINDOW_FRAMES = 200
|
| 23 |
+
|
| 24 |
+
# The 22 sites of the body graph. Each name is the body segment the site sits on; l_ / r_ / c_ = left, right, center.
|
| 25 |
+
SITE_NAMES = ("root", "l_upleg", "l_lowleg", "l_foot", "l_ball", "r_upleg", "r_lowleg", "r_foot", "r_ball",
|
| 26 |
+
"c_spine1", "c_spine2", "c_spine3", "c_neck", "c_head", "l_clavicle", "l_uparm", "l_lowarm", "l_wrist",
|
| 27 |
+
"r_clavicle", "r_uparm", "r_lowarm", "r_wrist")
|
| 28 |
+
SITE_INDEX = {name: i for i, name in enumerate(SITE_NAMES)}
|
| 29 |
+
# Parent of every site in the graph (-1 = root): left leg, right leg, spine to head, left arm, right arm.
|
| 30 |
+
SITE_PARENTS = (-1, 0, 1, 2, 3, 0, 5, 6, 7, 0, 9, 10, 11, 12, 11, 14, 15, 16, 11, 18, 19, 20)
|
| 31 |
+
# Calibrator conditioning: body part (left and right share one) and side (0 center, 1 left, 2 right) of every site.
|
| 32 |
+
BODY_PART_OF_SITE = (0, 1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 10, 11, 12, 13)
|
| 33 |
+
SIDE_OF_SITE = (0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2)
|
| 34 |
+
|
| 35 |
+
# Gravity estimation: a complementary (Mahony) filter when a gyroscope in rad/s is present. Some datasets ship
|
| 36 |
+
# gyroscopes in other units; a median rate above this threshold falls back to the low-pass estimate.
|
| 37 |
+
MAHONY_MAX_MEDIAN_RATE = 10.0
|
| 38 |
+
_ANTIPODAL_COS = -1.0 + 1e-12
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def unit(x):
|
| 42 |
+
"""Rows scaled to unit length (float64 in, float64 out)."""
|
| 43 |
+
return x / np.clip(np.linalg.norm(x, axis=-1, keepdims=True), 1e-9, None)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# ---------------------------------------------------------------------------------------------- gravity
|
| 47 |
+
def rotation_to_up(ghat):
|
| 48 |
+
"""Shortest rotation that turns the unit vectors ghat (..., 3) onto +y; returns (..., 3, 3) with det +1.
|
| 49 |
+
For ghat close to -y the rotation by pi about x is used."""
|
| 50 |
+
g = np.asarray(ghat, dtype=np.float64)
|
| 51 |
+
c = g[..., 1]
|
| 52 |
+
w = np.stack([-g[..., 2], np.zeros_like(c), g[..., 0]], axis=-1) # g x y
|
| 53 |
+
K = np.zeros(g.shape[:-1] + (3, 3))
|
| 54 |
+
K[..., 0, 1], K[..., 0, 2] = -w[..., 2], w[..., 1]
|
| 55 |
+
K[..., 1, 0], K[..., 1, 2] = w[..., 2], -w[..., 0]
|
| 56 |
+
K[..., 2, 0], K[..., 2, 1] = -w[..., 1], w[..., 0]
|
| 57 |
+
denom = np.where(c > _ANTIPODAL_COS, 1.0 + c, 1.0)
|
| 58 |
+
eye = np.broadcast_to(np.eye(3), K.shape)
|
| 59 |
+
R = eye + K + (K @ K) / denom[..., None, None]
|
| 60 |
+
R_pi = np.zeros_like(R)
|
| 61 |
+
R_pi[..., 0, 0], R_pi[..., 1, 1], R_pi[..., 2, 2] = 1.0, -1.0, -1.0
|
| 62 |
+
antipodal = (c <= _ANTIPODAL_COS)[..., None, None]
|
| 63 |
+
return np.where(antipodal, R_pi, R)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def canonicalize(acc, gyro, ghat):
|
| 67 |
+
"""acc, gyro, ghat (..., T, 3) -> (..., T, 9) = [R acc, R gyro, ghat], one rotation R per frame for both signals."""
|
| 68 |
+
n = np.linalg.norm(ghat, axis=-1, keepdims=True)
|
| 69 |
+
g = ghat / np.clip(n, 1e-9, None)
|
| 70 |
+
R = rotation_to_up(g)
|
| 71 |
+
acc_c = np.einsum("...ab,...b->...a", R, acc)
|
| 72 |
+
gyr_c = np.einsum("...ab,...b->...a", R, gyro)
|
| 73 |
+
return np.concatenate([acc_c, gyr_c, g], axis=-1)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def gravity_lowpass(acc, fs, cut_hz=0.3, order=2):
|
| 77 |
+
"""Gravity direction without a gyroscope: zero-phase Butterworth low-pass of the acceleration (time on axis -2).
|
| 78 |
+
Windows too short for filtfilt use their mean."""
|
| 79 |
+
from scipy.signal import butter, sosfiltfilt
|
| 80 |
+
T = acc.shape[-2]
|
| 81 |
+
sos = butter(order, cut_hz, btype="low", fs=fs, output="sos")
|
| 82 |
+
padlen = 3 * (2 * len(sos) + 1)
|
| 83 |
+
if T <= padlen:
|
| 84 |
+
g = np.broadcast_to(acc.mean(axis=-2, keepdims=True), acc.shape).copy()
|
| 85 |
+
else:
|
| 86 |
+
g = sosfiltfilt(sos, acc, axis=-2)
|
| 87 |
+
n = np.linalg.norm(g, axis=-1, keepdims=True)
|
| 88 |
+
return g / np.clip(n, 1e-9, None)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def gravity_mahony(acc, gyro, fs, kp=1.0):
|
| 92 |
+
"""Gravity direction with a gyroscope: complementary filter (gain kp in 1/s) that propagates the direction with
|
| 93 |
+
the angular velocity and pulls it towards the measured acceleration. acc in m/s^2, gyro in rad/s, (..., T, 3).
|
| 94 |
+
The start value is the mean acceleration direction of the first second."""
|
| 95 |
+
a = np.asarray(acc, dtype=np.float64)
|
| 96 |
+
w = np.asarray(gyro, dtype=np.float64)
|
| 97 |
+
T = a.shape[-2]
|
| 98 |
+
dt = 1.0 / fs
|
| 99 |
+
an = a / np.clip(np.linalg.norm(a, axis=-1, keepdims=True), 1e-9, None)
|
| 100 |
+
g0 = a[..., : min(T, max(3, int(fs))), :].mean(axis=-2)
|
| 101 |
+
g0 = g0 / np.clip(np.linalg.norm(g0, axis=-1, keepdims=True), 1e-9, None)
|
| 102 |
+
out = np.empty_like(a)
|
| 103 |
+
g = g0
|
| 104 |
+
out[..., 0, :] = g
|
| 105 |
+
for t in range(1, T):
|
| 106 |
+
e = np.cross(g, an[..., t, :]) # pulls g towards the measurement
|
| 107 |
+
g = g + dt * (-np.cross(w[..., t, :], g) + kp * np.cross(e, g)) # rotating frame: g_dot = -w x g
|
| 108 |
+
g = g / np.clip(np.linalg.norm(g, axis=-1, keepdims=True), 1e-9, None)
|
| 109 |
+
out[..., t, :] = g
|
| 110 |
+
return out
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def estimate_gravity(acc, gyro, fs):
|
| 114 |
+
"""-> (ghat, method, median rate). Mahony filter when the gyroscope looks like rad/s, else the low-pass."""
|
| 115 |
+
median_rate = None
|
| 116 |
+
if gyro is not None:
|
| 117 |
+
median_rate = float(np.median(np.linalg.norm(gyro, axis=-1)))
|
| 118 |
+
if median_rate < MAHONY_MAX_MEDIAN_RATE:
|
| 119 |
+
return gravity_mahony(acc, gyro, fs), "mahony", median_rate
|
| 120 |
+
return gravity_lowpass(acc, fs), "lowpass", median_rate
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def canonical_device_windows(acc, gyro, fs):
|
| 124 |
+
"""Raw windows of one device (N, T, 3) at their own rate -> (N, T, 9) gravity-canonical channels.
|
| 125 |
+
A gyroscope that fails the unit check is dropped (channels 3-5 zero), as is a missing one."""
|
| 126 |
+
ghat, method, _ = estimate_gravity(acc, gyro, fs)
|
| 127 |
+
use_gyro = gyro is not None and method == "mahony"
|
| 128 |
+
x9 = canonicalize(acc, gyro if use_gyro else np.zeros_like(acc), ghat)
|
| 129 |
+
if not use_gyro:
|
| 130 |
+
x9[..., 3:6] = 0.0
|
| 131 |
+
return x9, method
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def to_model_rate(x, fs):
|
| 135 |
+
"""(N, T, S, 9) at fs -> (N, 200, S, 9) float32 at 20 Hz: Fourier resampling to int(T / fs * 20) frames,
|
| 136 |
+
gravity channels renormalized (zero where a site is absent), wrap padding to 200 frames, then cut to 200."""
|
| 137 |
+
from scipy.signal import resample
|
| 138 |
+
N, T, S, C = x.shape
|
| 139 |
+
flat = x.reshape(N, T, S * C)
|
| 140 |
+
new_len = int(T / fs * SAMPLE_RATE_HZ)
|
| 141 |
+
res = np.array([resample(seq, new_len) for seq in flat]).reshape(N, new_len, S, C)
|
| 142 |
+
g = res[..., 6:9]
|
| 143 |
+
n = np.linalg.norm(g, axis=-1, keepdims=True)
|
| 144 |
+
res[..., 6:9] = np.where(n > 0.5, g / np.clip(n, 1e-9, None), 0.0)
|
| 145 |
+
res = res.reshape(N, new_len, S * C)
|
| 146 |
+
if res.shape[1] < WINDOW_FRAMES:
|
| 147 |
+
res = np.pad(res, ((0, 0), (0, WINDOW_FRAMES - res.shape[1]), (0, 0)), "wrap")
|
| 148 |
+
return res[:, :WINDOW_FRAMES].reshape(N, WINDOW_FRAMES, S, C).astype(np.float32)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def prepare_device(acc, gyro, fs):
|
| 152 |
+
"""Windows of one device -> model windows (N, 200, 9) at 20 Hz with zero reference channels.
|
| 153 |
+
|
| 154 |
+
acc (N, T, 3) in m/s^2 including gravity, gyro (N, T, 3) in rad/s or None, fs the sampling rate in Hz.
|
| 155 |
+
Each window should cover about 10 s; shorter windows are wrap-padded, longer ones cut."""
|
| 156 |
+
x9, _ = canonical_device_windows(np.asarray(acc, np.float64),
|
| 157 |
+
None if gyro is None else np.asarray(gyro, np.float64), fs)
|
| 158 |
+
return to_model_rate(x9[:, :, None, :], fs)[:, :, 0, :]
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def place_devices(devices, n_windows=None):
|
| 162 |
+
"""{site name: (N, 200, 9) windows} -> (N, 200, 22, 9) encoder input (other sites zero)."""
|
| 163 |
+
n = n_windows or len(next(iter(devices.values())))
|
| 164 |
+
x = np.zeros((n, WINDOW_FRAMES, len(SITE_NAMES), 9), np.float32)
|
| 165 |
+
for site, w in devices.items():
|
| 166 |
+
x[:, :, SITE_INDEX[site]] = w
|
| 167 |
+
return x
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def set_reference(windows, reference):
|
| 171 |
+
"""Reference channels of one device: channels 6-8 := Q g_hat(t) on valid frames, 0 elsewhere.
|
| 172 |
+
windows (N, 200, 9) with the gravity direction in channels 6-8 as prepared; reference Q (3, 3) or None."""
|
| 173 |
+
out = np.array(windows, copy=True)
|
| 174 |
+
g = out[..., 6:9].astype(np.float64)
|
| 175 |
+
valid = np.abs(g).sum(-1) > 0
|
| 176 |
+
if reference is None:
|
| 177 |
+
out[..., 6:9] = 0.0
|
| 178 |
+
else:
|
| 179 |
+
out[..., 6:9] = np.where(valid[..., None], unit(g) @ np.asarray(reference).T, 0.0).astype(out.dtype)
|
| 180 |
+
return out
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
# ---------------------------------------------------------------------------------------------- calibrator input
|
| 184 |
+
def device_frame_signals(windows):
|
| 185 |
+
"""Undo the canonicalization of one site: (n, T, 9) -> acc, gyro in device axes and the unit up direction."""
|
| 186 |
+
g = unit(windows[..., 6:9].astype(np.float64))
|
| 187 |
+
R = rotation_to_up(g)
|
| 188 |
+
return (np.einsum("ntba,ntb->nta", R, windows[..., 0:3].astype(np.float64)),
|
| 189 |
+
np.einsum("ntba,ntb->nta", R, windows[..., 3:6].astype(np.float64)), g)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def calibrator_input(windows, has_gyro, force_scale, rate_scale):
|
| 193 |
+
"""Context windows of one device (n, T, 9) with the gravity direction in channels 6-8 -> calibrator input
|
| 194 |
+
(n, T, 7) float32 and the valid frames (n, T). The calibrator sees the raw signals in device axes, gravity
|
| 195 |
+
included, divided by one scalar each, plus a flag for a missing gyroscope."""
|
| 196 |
+
acc, gyr, _ = device_frame_signals(windows)
|
| 197 |
+
valid = np.abs(windows[..., 6:9]).sum(-1) > 0
|
| 198 |
+
acc = np.where(valid[..., None], acc, 0.0)
|
| 199 |
+
gyr = np.where(valid[..., None], gyr, 0.0)
|
| 200 |
+
if not has_gyro:
|
| 201 |
+
gyr = np.zeros_like(gyr)
|
| 202 |
+
flag = np.full(acc.shape[:-1] + (1,), 0.0 if has_gyro else 1.0)
|
| 203 |
+
return np.concatenate([acc / force_scale, gyr / rate_scale, flag], -1).astype(np.float32), valid
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# ---------------------------------------------------------------------------------------------- context selection
|
| 207 |
+
TILT_REF_DEG = 10.0
|
| 208 |
+
TILT_SCORE_MIN, TILT_SCORE_MAX = float(np.log(1.0 / 10.0)), float(np.log(90.0 / 10.0))
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def tilt_sigma(M, V, s):
|
| 212 |
+
"""Spread (radians) of the up axis of a Matrix-Fisher density F = M V diag(s) V^T, from its Gaussian
|
| 213 |
+
approximation on the tangent space; inputs (..., 3, 3), (..., 3, 3), (..., 3)."""
|
| 214 |
+
M, V, s = (np.asarray(a, np.float64) for a in (M, V, s))
|
| 215 |
+
lam = np.stack([s[..., 1] + s[..., 2], s[..., 0] + s[..., 2], s[..., 0] + s[..., 1]], -1)
|
| 216 |
+
lam = np.clip(lam, 1e-3, None)
|
| 217 |
+
cov = np.einsum("...ab,...b,...cb->...ac", V, 1.0 / lam, V)
|
| 218 |
+
up = M[..., 1, :]
|
| 219 |
+
along = np.einsum("...a,...ab,...b->...", up, cov, up)
|
| 220 |
+
tr = np.trace(cov, axis1=-2, axis2=-1)
|
| 221 |
+
return np.sqrt(np.clip(0.5 * (tr - along), 1e-12, None))
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def tilt_score(M, V, s, logit):
|
| 225 |
+
"""Selection score of the calibrator output (batch of mixtures): log(sigma_up / 10 deg) of the heaviest
|
| 226 |
+
component, clipped to [log 0.1, log 9]. Smaller is more certain."""
|
| 227 |
+
c = np.asarray(logit).argmax(-1)
|
| 228 |
+
i = np.arange(len(c))
|
| 229 |
+
sig = tilt_sigma(np.asarray(M)[i, c], np.asarray(V)[i, c], np.asarray(s)[i, c])
|
| 230 |
+
return np.clip(np.log(sig) + np.log(180.0 / np.pi / TILT_REF_DEG), TILT_SCORE_MIN, TILT_SCORE_MAX)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def select_by_elimination(pool_sizes, score_fn, keep=6):
|
| 234 |
+
"""Greedy backward elimination for many devices at once (paper Sec. 3.5).
|
| 235 |
+
|
| 236 |
+
pool_sizes {device: n}; score_fn([(device, positions), ...]) -> {(device, positions): score}, called once per
|
| 237 |
+
elimination round for all candidate subsets of all devices. Each round drops, per device, the window whose removal
|
| 238 |
+
leaves the smallest score (ties: the lowest position). Returns {device: positions of the kept windows}."""
|
| 239 |
+
current = {key: tuple(range(n)) for key, n in pool_sizes.items()}
|
| 240 |
+
score_fn(list(current.items()))
|
| 241 |
+
while True:
|
| 242 |
+
active = [key for key in current if len(current[key]) > keep]
|
| 243 |
+
if not active:
|
| 244 |
+
break
|
| 245 |
+
candidates = {key: [tuple(p for p in current[key] if p != r) for r in current[key]] for key in active}
|
| 246 |
+
scores = score_fn([(key, c) for key in active for c in candidates[key]])
|
| 247 |
+
for key in active:
|
| 248 |
+
vals = [scores[(key, c)] for c in candidates[key]]
|
| 249 |
+
j = min(range(len(vals)), key=lambda i: (vals[i], i))
|
| 250 |
+
current[key] = candidates[key][j]
|
| 251 |
+
return current
|
requirements.txt
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Reference environment of the paper's numbers: Python 3.9, NVIDIA GPU with CUDA 12.8 wheels.
|
| 2 |
+
# Other versions load and run the model; only this set has been checked to reproduce every printed digit.
|
| 3 |
+
--extra-index-url https://download.pytorch.org/whl/cu128
|
| 4 |
+
torch==2.8.0+cu128
|
| 5 |
+
numpy==2.0.2
|
| 6 |
+
scipy==1.13.1
|
| 7 |
+
transformers==4.57.6
|
| 8 |
+
safetensors==0.7.0
|
| 9 |
+
huggingface_hub==0.36.2
|
| 10 |
+
|
| 11 |
+
# Only for examples/zero_shot.py (CLIP ViT-B/32 text encoder for your own class names). The paper's class vectors
|
| 12 |
+
# are part of the evaluation data, so reproducing the numbers does not need CLIP. Install separately:
|
| 13 |
+
# pip install torchvision==0.23.0+cu128 ftfy==6.3.1 regex --extra-index-url https://download.pytorch.org/whl/cu128
|
| 14 |
+
# pip install "setuptools<81" && pip install --no-build-isolation git+https://github.com/openai/CLIP.git@a1d071733d7111c9c014f024669f959182114e33
|
seed2/config.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"SetConModel"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_setcon.SetConConfig",
|
| 7 |
+
"AutoModel": "modeling_setcon.SetConModel"
|
| 8 |
+
},
|
| 9 |
+
"calibrator_body_parts": 14,
|
| 10 |
+
"calibrator_components": 2,
|
| 11 |
+
"calibrator_conv_channels": [
|
| 12 |
+
64,
|
| 13 |
+
128,
|
| 14 |
+
128,
|
| 15 |
+
128
|
| 16 |
+
],
|
| 17 |
+
"calibrator_conv_strides": [
|
| 18 |
+
2,
|
| 19 |
+
2,
|
| 20 |
+
2,
|
| 21 |
+
1
|
| 22 |
+
],
|
| 23 |
+
"calibrator_hidden_size": 128,
|
| 24 |
+
"calibrator_set_blocks": 2,
|
| 25 |
+
"calibrator_sides": 3,
|
| 26 |
+
"context_windows": 6,
|
| 27 |
+
"dtype": "float32",
|
| 28 |
+
"embedding_dim": 512,
|
| 29 |
+
"force_scale": 6.199315143837327,
|
| 30 |
+
"frames_per_patch": 4,
|
| 31 |
+
"hidden_size": 256,
|
| 32 |
+
"input_channels": 9,
|
| 33 |
+
"model_type": "setcon",
|
| 34 |
+
"num_graph_blocks": 8,
|
| 35 |
+
"num_patches": 50,
|
| 36 |
+
"num_sites": 22,
|
| 37 |
+
"rate_scale": 0.7396506117362955,
|
| 38 |
+
"sample_rate_hz": 20.0,
|
| 39 |
+
"stage2_epoch": 100,
|
| 40 |
+
"temporal_kernel": 9,
|
| 41 |
+
"text_encoder": "openai/clip ViT-B/32 (frozen)",
|
| 42 |
+
"training_seed": 2,
|
| 43 |
+
"transformers_version": "4.57.6"
|
| 44 |
+
}
|
seed2/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ab0386be5d2ef7cf02cda9f2c18a0f6a29fdc7415049c9226553c619ad82d060
|
| 3 |
+
size 27962388
|
seed3/config.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"SetConModel"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_setcon.SetConConfig",
|
| 7 |
+
"AutoModel": "modeling_setcon.SetConModel"
|
| 8 |
+
},
|
| 9 |
+
"calibrator_body_parts": 14,
|
| 10 |
+
"calibrator_components": 2,
|
| 11 |
+
"calibrator_conv_channels": [
|
| 12 |
+
64,
|
| 13 |
+
128,
|
| 14 |
+
128,
|
| 15 |
+
128
|
| 16 |
+
],
|
| 17 |
+
"calibrator_conv_strides": [
|
| 18 |
+
2,
|
| 19 |
+
2,
|
| 20 |
+
2,
|
| 21 |
+
1
|
| 22 |
+
],
|
| 23 |
+
"calibrator_hidden_size": 128,
|
| 24 |
+
"calibrator_set_blocks": 2,
|
| 25 |
+
"calibrator_sides": 3,
|
| 26 |
+
"context_windows": 6,
|
| 27 |
+
"dtype": "float32",
|
| 28 |
+
"embedding_dim": 512,
|
| 29 |
+
"force_scale": 6.199315143837327,
|
| 30 |
+
"frames_per_patch": 4,
|
| 31 |
+
"hidden_size": 256,
|
| 32 |
+
"input_channels": 9,
|
| 33 |
+
"model_type": "setcon",
|
| 34 |
+
"num_graph_blocks": 8,
|
| 35 |
+
"num_patches": 50,
|
| 36 |
+
"num_sites": 22,
|
| 37 |
+
"rate_scale": 0.7396506117362955,
|
| 38 |
+
"sample_rate_hz": 20.0,
|
| 39 |
+
"stage2_epoch": 100,
|
| 40 |
+
"temporal_kernel": 9,
|
| 41 |
+
"text_encoder": "openai/clip ViT-B/32 (frozen)",
|
| 42 |
+
"training_seed": 3,
|
| 43 |
+
"transformers_version": "4.57.6"
|
| 44 |
+
}
|
seed3/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cc6dd517b2ad2afe64fe184862e6e8035e1383f67b3581cbd78c4fe69c450b34
|
| 3 |
+
size 27962388
|
setcon/__init__.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evaluation package of SetCon: recomputes the zero-shot numbers of the paper from the released weights.
|
| 2 |
+
|
| 3 |
+
setcon.data the 18 test sets: download notes, extraction with sha256 checks, model-ready caches
|
| 4 |
+
setcon.protocol the test protocol: datasets, person groups, gait test, walking frame, seeded context draws
|
| 5 |
+
setcon.references the setup reference of every device under each reading of the paper
|
| 6 |
+
setcon.evaluate embeddings, zero-shot predictions and class-mean readout for one seed
|
| 7 |
+
setcon.tables the paper's numbers (Tab. 1-3, abstract, Sec. 4.3-4.4) from the per-seed results
|
| 8 |
+
|
| 9 |
+
The model itself is loaded through transformers (remote code in the repository root):
|
| 10 |
+
|
| 11 |
+
from setcon import load_model
|
| 12 |
+
model = load_model(seed=1)
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import importlib.util
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
REPO_ROOT = Path(__file__).resolve().parents[1]
|
| 20 |
+
# Hugging Face repositories of the release.
|
| 21 |
+
MODEL_REPO = "lschiweck/SetCon"
|
| 22 |
+
EVAL_DATA_REPO = "lschiweck/SetCon-eval"
|
| 23 |
+
SEEDS = (1, 2, 3)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _load_processing():
|
| 27 |
+
spec = importlib.util.spec_from_file_location("processing_setcon", REPO_ROOT / "processing_setcon.py")
|
| 28 |
+
module = importlib.util.module_from_spec(spec)
|
| 29 |
+
spec.loader.exec_module(module)
|
| 30 |
+
return module
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
processing = _load_processing()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def load_model(seed=1, model=None, device="cpu"):
|
| 37 |
+
"""The SetCon checkpoint of one stage-2 seed (1, 2 or 3) via AutoModel with trust_remote_code. `model` is a local
|
| 38 |
+
folder or a hub id; default: the repository this package lives in. Seed 1 is the repository root, seeds 2 and 3
|
| 39 |
+
are the subfolders seed2/ and seed3/. Returns the model in eval mode on `device`."""
|
| 40 |
+
from transformers import AutoModel
|
| 41 |
+
if seed not in SEEDS:
|
| 42 |
+
raise ValueError(f"seed must be one of {SEEDS}")
|
| 43 |
+
kwargs = {} if seed == 1 else {"subfolder": f"seed{seed}"}
|
| 44 |
+
m = AutoModel.from_pretrained(str(model or REPO_ROOT), trust_remote_code=True, **kwargs)
|
| 45 |
+
if m.config.training_seed != seed:
|
| 46 |
+
raise ValueError(f"checkpoint reports training seed {m.config.training_seed}, expected {seed}")
|
| 47 |
+
return m.to(device).eval()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def eval_data_dir(path_or_repo=None):
|
| 51 |
+
"""Local folder of the evaluation data (class vectors, person groups, window lists, reference predictions):
|
| 52 |
+
an existing folder is used as it is, otherwise the dataset repository is downloaded from the hub."""
|
| 53 |
+
p = Path(path_or_repo) if path_or_repo else None
|
| 54 |
+
if p is not None and p.is_dir():
|
| 55 |
+
return p
|
| 56 |
+
from huggingface_hub import snapshot_download
|
| 57 |
+
return Path(snapshot_download(repo_id=str(path_or_repo or EVAL_DATA_REPO), repo_type="dataset"))
|
setcon/data.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The 18 public test sets of the UniMTS suite in the model's input format.
|
| 2 |
+
|
| 3 |
+
Raw data
|
| 4 |
+
--------
|
| 5 |
+
The test windows come from `UniMTS_data.zip` of the UniMTS release on the Hugging Face hub. The archive has no
|
| 6 |
+
license and is not redistributed here. Download it once:
|
| 7 |
+
|
| 8 |
+
hf download xiyuanz/UniMTS UniMTS_data.zip --revision 378531dbc1ec649b5bb792fd2e8f4c9a1a3ff99d --local-dir <dir>
|
| 9 |
+
|
| 10 |
+
`extract_test_files` checks the archive's sha256, extracts only the 54 test files used here (X_test.npy, y_test.npy
|
| 11 |
+
and <dataset>.json of each set, about 1.2 GB) and checks each file's sha256 against raw_data.json of the evaluation
|
| 12 |
+
data. If the archive changes upstream, the check fails instead of giving different numbers.
|
| 13 |
+
|
| 14 |
+
Model-ready caches
|
| 15 |
+
------------------
|
| 16 |
+
Every sensor goes to one of the 22 body sites. Columns, units and the resampling to 20 Hz follow UniMTS's data loader
|
| 17 |
+
(github.com/xiyuanzh/UniMTS, data.py). Each sensor is gravity-canonicalized at its original rate before resampling
|
| 18 |
+
(processing_setcon.py). A cache holds X9 (N, 200, 22, 9) float32, y (N,) and the class names.
|
| 19 |
+
"""
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import hashlib
|
| 23 |
+
import json
|
| 24 |
+
import zipfile
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
from . import processing as PS
|
| 30 |
+
from .protocol import ACC_ONLY_SETS, DATASETS
|
| 31 |
+
|
| 32 |
+
G = 9.80665
|
| 33 |
+
SITE = PS.SITE_INDEX
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def sha256(path, chunk=1 << 22):
|
| 37 |
+
h = hashlib.sha256()
|
| 38 |
+
with open(path, "rb") as f:
|
| 39 |
+
for block in iter(lambda: f.read(chunk), b""):
|
| 40 |
+
h.update(block)
|
| 41 |
+
return h.hexdigest()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# ---------------------------------------------------------------------------------------------- raw files
|
| 45 |
+
def raw_manifest(eval_data):
|
| 46 |
+
return json.loads((Path(eval_data) / "raw_data.json").read_text())
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def extract_test_files(zip_path, out_dir, eval_data, check_archive=True):
|
| 50 |
+
"""Extract the 54 test files from UniMTS_data.zip into out_dir/<dataset>/ and verify every sha256."""
|
| 51 |
+
man = raw_manifest(eval_data)
|
| 52 |
+
zip_path, out_dir = Path(zip_path), Path(out_dir)
|
| 53 |
+
if check_archive:
|
| 54 |
+
digest = sha256(zip_path)
|
| 55 |
+
if digest != man["archive"]["sha256"]:
|
| 56 |
+
raise SystemExit(f"{zip_path}: sha256 {digest} differs from the expected {man['archive']['sha256']}")
|
| 57 |
+
with zipfile.ZipFile(zip_path) as z:
|
| 58 |
+
for rel, rec in man["files"].items():
|
| 59 |
+
dst = out_dir / rel
|
| 60 |
+
if dst.exists() and sha256(dst) == rec["sha256"]:
|
| 61 |
+
continue
|
| 62 |
+
data = z.read(rec["member"])
|
| 63 |
+
if hashlib.sha256(data).hexdigest() != rec["sha256"]:
|
| 64 |
+
raise SystemExit(f"{rec['member']}: sha256 mismatch")
|
| 65 |
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
| 66 |
+
dst.write_bytes(data)
|
| 67 |
+
verify_test_files(out_dir, eval_data)
|
| 68 |
+
return out_dir
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def verify_test_files(unimts_dir, eval_data):
|
| 72 |
+
"""Every one of the 54 test files exists under unimts_dir with the expected sha256."""
|
| 73 |
+
man = raw_manifest(eval_data)
|
| 74 |
+
bad = [rel for rel, rec in man["files"].items()
|
| 75 |
+
if not (Path(unimts_dir) / rel).exists() or sha256(Path(unimts_dir) / rel) != rec["sha256"]]
|
| 76 |
+
if bad:
|
| 77 |
+
raise SystemExit(f"{len(bad)} test files missing or changed under {unimts_dir}, e.g. {bad[:3]}")
|
| 78 |
+
return True
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# ---------------------------------------------------------------------------------------------- sensors
|
| 82 |
+
def sensors(dataset, X, y):
|
| 83 |
+
"""Sensor columns of one dataset -> [(site, acc (N, T, 3) m/s^2, gyro (N, T, 3) rad/s or None, window subset or
|
| 84 |
+
None)], sampling rate. Only UTD-MHAD uses a subset: its sensor sits on the right wrist for the first 21 classes
|
| 85 |
+
and on the right thigh for the last 6 (the convention of the UniMTS loader)."""
|
| 86 |
+
A = None
|
| 87 |
+
if dataset == "PAMAP":
|
| 88 |
+
return [(SITE["r_wrist"], X[:, :, 0:3], X[:, :, 3:6], A), (SITE["c_spine3"], X[:, :, 18:21], X[:, :, 21:24], A),
|
| 89 |
+
(SITE["r_foot"], X[:, :, 9:12], X[:, :, 12:15], A)], 100
|
| 90 |
+
if dataset == "USCHAD":
|
| 91 |
+
return [(SITE["r_upleg"], X[:, :, 0:3] * G, X[:, :, 3:6] / 180 * np.pi, A)], 100
|
| 92 |
+
if dataset == "UCIHAR":
|
| 93 |
+
return [(SITE["c_spine1"], X[:, :, 6:9] * G, X[:, :, 3:6], A)], 50
|
| 94 |
+
if dataset == "Opp_g":
|
| 95 |
+
return [(SITE[name], X[:, :, a:a + 3] / 1000 * 9.8, X[:, :, a + 3:a + 6] / 1000, A)
|
| 96 |
+
for name, a in (("c_spine2", 0), ("r_uparm", 9), ("r_lowarm", 18), ("l_uparm", 27),
|
| 97 |
+
("l_lowarm", 36))], 30
|
| 98 |
+
if dataset == "WISDM":
|
| 99 |
+
return [(SITE["r_wrist"], X[:, :, 0:3], X[:, :, 3:6], A)], 20
|
| 100 |
+
if dataset == "DSADS":
|
| 101 |
+
return [(SITE[name], X[:, :, a:a + 3], X[:, :, a + 3:a + 6], A)
|
| 102 |
+
for name, a in (("c_spine3", 0), ("r_wrist", 9), ("l_wrist", 18), ("r_lowleg", 27),
|
| 103 |
+
("l_lowleg", 36))], 25
|
| 104 |
+
if dataset == "Harth":
|
| 105 |
+
return [(SITE["c_spine1"], X[:, :, 0:3] * G, None, A), (SITE["r_lowleg"], X[:, :, 3:6] * G, None, A)], 50
|
| 106 |
+
if dataset == "Wharf":
|
| 107 |
+
Xc = -14.709 + X / 63 * (2 * 14.709)
|
| 108 |
+
return [(SITE["r_wrist"], Xc[:, :, 0:3], None, A)], 32
|
| 109 |
+
if dataset == "Mhealth":
|
| 110 |
+
return [(SITE["c_spine3"], X[:, :, 0:3], None, A),
|
| 111 |
+
(SITE["l_foot"], X[:, :, 6:9], X[:, :, 9:12] / 180 * np.pi, A),
|
| 112 |
+
(SITE["r_wrist"], X[:, :, 15:18], X[:, :, 18:21] / 180 * np.pi, A)], 50
|
| 113 |
+
if dataset == "UTD-MHAD":
|
| 114 |
+
wrist = (y < 21)
|
| 115 |
+
return [(SITE["r_wrist"], X[:, :, 0:3] * G, X[:, :, 3:6] / 180 * np.pi, wrist),
|
| 116 |
+
(SITE["r_upleg"], X[:, :, 0:3] * G, X[:, :, 3:6] / 180 * np.pi, ~wrist)], 50
|
| 117 |
+
if dataset == "MotionSense":
|
| 118 |
+
return [(SITE["r_upleg"], X[:, :, 0:3] * G, X[:, :, 3:6], A),
|
| 119 |
+
(SITE["l_upleg"], X[:, :, 0:3] * G, X[:, :, 3:6], A)], 50
|
| 120 |
+
if dataset == "w-HAR":
|
| 121 |
+
return [(SITE["r_foot"], X[:, :, 0:3] * G, X[:, :, 3:6] / 180 * np.pi, A)], 250
|
| 122 |
+
if dataset == "Shoaib":
|
| 123 |
+
return [(SITE[name], X[:, :, a:a + 3], X[:, :, a + 3:a + 6], A)
|
| 124 |
+
for name, a in (("l_upleg", 0), ("r_upleg", 6), ("r_wrist", 12), ("r_lowarm", 18), ("root", 24))], 50
|
| 125 |
+
if dataset == "har70plus":
|
| 126 |
+
return [(SITE["root"], X[:, :, 0:3] * G, None, A), (SITE["r_upleg"], X[:, :, 3:6] * G, None, A)], 50
|
| 127 |
+
if dataset == "MMAct":
|
| 128 |
+
return [(SITE["r_upleg"], X[:, :, 0:3], X[:, :, 3:6], A), (SITE["r_wrist"], X[:, :, 6:9], None, A)], 50
|
| 129 |
+
if dataset == "realworld":
|
| 130 |
+
return [(SITE[name], X[:, :, a:a + 3], X[:, :, a + 3:a + 6], A)
|
| 131 |
+
for name, a in (("l_clavicle", 0), ("l_lowarm", 6), ("c_head", 12), ("l_foot", 18),
|
| 132 |
+
("l_upleg", 24), ("l_uparm", 30), ("c_spine1", 36))], 50
|
| 133 |
+
if dataset == "TNDA-HAR":
|
| 134 |
+
return [(SITE[name], X[:, :, a:a + 3], X[:, :, a + 3:a + 6], A)
|
| 135 |
+
for name, a in (("r_lowarm", 0), ("l_lowleg", 6), ("r_wrist", 12), ("l_foot", 18),
|
| 136 |
+
("c_spine3", 24))], 50
|
| 137 |
+
if dataset == "ut-complex":
|
| 138 |
+
return [(SITE["r_upleg"], X[:, :, 0:3], X[:, :, 3:6], A), (SITE["r_wrist"], X[:, :, 6:9], X[:, :, 9:12], A)], 50
|
| 139 |
+
raise ValueError(dataset)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def build_benchmark(dataset, unimts_dir):
|
| 143 |
+
"""-> X9 (N, 200, 22, 9) float32, y (N,), class names, per-sensor log (site, gravity method, gyro used)."""
|
| 144 |
+
d = Path(unimts_dir) / dataset
|
| 145 |
+
X = np.load(d / "X_test.npy").astype(np.float64)
|
| 146 |
+
y = np.load(d / "y_test.npy")
|
| 147 |
+
meta = json.loads((d / f"{dataset}.json").read_text())
|
| 148 |
+
N, T = X.shape[0], X.shape[1]
|
| 149 |
+
sens, fs = sensors(dataset, X, y)
|
| 150 |
+
all9 = np.zeros((N, T, len(PS.SITE_NAMES), 9))
|
| 151 |
+
log = []
|
| 152 |
+
for site, acc, gyro, subset in sens:
|
| 153 |
+
sel = slice(None) if subset is None else subset
|
| 154 |
+
acc_s = acc[sel]
|
| 155 |
+
if acc_s.shape[0] == 0:
|
| 156 |
+
continue
|
| 157 |
+
x9, method = PS.canonical_device_windows(acc_s, None if gyro is None else gyro[sel], fs)
|
| 158 |
+
all9[sel, :, site] = x9
|
| 159 |
+
log.append(dict(site=PS.SITE_NAMES[site], gravity=method, gyro=gyro is not None and method == "mahony",
|
| 160 |
+
windows=int(acc_s.shape[0])))
|
| 161 |
+
X9 = PS.to_model_rate(all9, fs)
|
| 162 |
+
classes = [" ".join(v) for v in meta["label_dictionary"].values()]
|
| 163 |
+
return X9, np.asarray(y), classes, log
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def check_gyro_rule(dataset, X9):
|
| 167 |
+
"""Mean-13 holds the sets in which every worn site has a gyroscope; the other five must have an
|
| 168 |
+
acceleration-only site. Fails loudly if a cache disagrees with protocol.ACC_ONLY_SETS."""
|
| 169 |
+
acc_only = [PS.SITE_NAMES[s] for s in range(X9.shape[2])
|
| 170 |
+
if np.any(X9[:, :, s, 6:9] != 0) and not np.any(X9[:, :, s, 3:6] != 0)]
|
| 171 |
+
if bool(acc_only) != (dataset in ACC_ONLY_SETS):
|
| 172 |
+
raise SystemExit(f"{dataset}: acceleration-only sites {acc_only} disagree with the Mean-13 rule")
|
| 173 |
+
return acc_only
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def write_benchmarks(unimts_dir, out_dir, datasets=DATASETS):
|
| 177 |
+
"""Build and store every cache as <out_dir>/<dataset>.npz (compressed, no pickles; about 0.35 GB in total)."""
|
| 178 |
+
out_dir = Path(out_dir)
|
| 179 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 180 |
+
for ds in datasets:
|
| 181 |
+
X9, y, classes, log = build_benchmark(ds, unimts_dir)
|
| 182 |
+
check_gyro_rule(ds, X9)
|
| 183 |
+
np.savez_compressed(out_dir / f"{ds}.npz", X9=X9, y=y.astype(np.int64), classes=np.array(classes),
|
| 184 |
+
sensors=np.array(json.dumps(log)))
|
| 185 |
+
print(f" {ds:12s} {X9.shape[0]:5d} windows " +
|
| 186 |
+
", ".join(f"{s['site']} ({s['gravity']})" for s in log), flush=True)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def load_benchmark(cache_dir, dataset):
|
| 190 |
+
"""-> X9, y, class names from <cache_dir>/<dataset>.npz."""
|
| 191 |
+
with np.load(Path(cache_dir) / f"{dataset}.npz", allow_pickle=False) as z:
|
| 192 |
+
return z["X9"], z["y"].astype(int), [str(c) for c in z["classes"]]
|
setcon/evaluate.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Zero-shot evaluation of one seed: embeddings of every scored window under each reading, predictions against the
|
| 2 |
+
class names, the anchors and names + descriptions, and the class-mean readout.
|
| 3 |
+
|
| 4 |
+
Reference settings (as in the paper): encoder on CUDA under bfloat16 autocast, batches of 64 scored windows in
|
| 5 |
+
window order; calibrator on CPU in float32 with 4 threads. Every reading embeds the same windows (all windows except
|
| 6 |
+
the six context windows of their device); the 6-of-12 reading scores them without its six extra context windows.
|
| 7 |
+
|
| 8 |
+
Output: <out>/seed<S>/<reading>.npz with, per dataset, predictions (5 draws x windows, -1 = not scored) for the three
|
| 9 |
+
class texts, the scored windows, the windows without walking-frame reference and the class-mean readout per draw.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import json
|
| 14 |
+
import time
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import torch
|
| 19 |
+
|
| 20 |
+
from . import processing as PS
|
| 21 |
+
from .data import load_benchmark
|
| 22 |
+
from .protocol import DATASETS, DRAWS, Draw, EvalData, dataset_protocol
|
| 23 |
+
from .references import READINGS, reading_inputs
|
| 24 |
+
|
| 25 |
+
TEXTS = ("names", "anchors", "names_descriptions")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def unit_embeddings(model, X, batch_size):
|
| 29 |
+
"""Embeddings as the paper stored them: model output, unit length in float64, kept as float32."""
|
| 30 |
+
z = model.embed(X, batch_size=batch_size)
|
| 31 |
+
return PS.unit(z.astype(np.float64)).astype(np.float32).astype(np.float64)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def class_mean_readout(Z, y, names):
|
| 35 |
+
"""Accuracy (%) of the nearest class center: center = unit mean embedding of the class's windows (the class-name
|
| 36 |
+
vector for a class without windows). Uses the test labels by definition; a diagnostic of separation."""
|
| 37 |
+
U = lambda x: x / np.clip(np.linalg.norm(x, axis=-1, keepdims=True), 1e-12, None) # noqa: E731
|
| 38 |
+
C = U(np.stack([Z[y == c].mean(0) if (y == c).any() else names[c] for c in range(len(names))]))
|
| 39 |
+
return 100 * float(np.mean((Z @ C.T).argmax(1) == y))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def evaluate_seed(model, seed, cache_dir, eval_data, out_dir, readings=READINGS, datasets=DATASETS, device="cuda",
|
| 43 |
+
batch_size=64):
|
| 44 |
+
torch.set_num_threads(4)
|
| 45 |
+
ed = eval_data if isinstance(eval_data, EvalData) else EvalData(eval_data)
|
| 46 |
+
model.calibrator.to("cpu").float().eval()
|
| 47 |
+
model.encoder.to(device).eval()
|
| 48 |
+
out = Path(out_dir) / f"seed{seed}"
|
| 49 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 50 |
+
results = {r: {} for r in readings}
|
| 51 |
+
reference = ed.reference_predictions(seed)
|
| 52 |
+
check = {r: dict(windows=0, differing=0, readout_max_abs_diff=0.0) for r in readings}
|
| 53 |
+
t0 = time.time()
|
| 54 |
+
for ds in datasets:
|
| 55 |
+
X, y, classes = load_benchmark(cache_dir, ds)
|
| 56 |
+
groups, gait, ref = dataset_protocol(ds, X, ed)
|
| 57 |
+
if classes != ref["classes"]:
|
| 58 |
+
raise SystemExit(f"{ds}: class names differ from the evaluation data")
|
| 59 |
+
V = ed.class_vectors(ds)
|
| 60 |
+
N = len(y)
|
| 61 |
+
for r in readings:
|
| 62 |
+
results[r].update({f"{ds}/{t}": np.full((DRAWS, N), -1, np.int16) for t in TEXTS})
|
| 63 |
+
results[r].update({f"{ds}/scored": np.zeros((DRAWS, N), bool), f"{ds}/no_walking_frame":
|
| 64 |
+
np.zeros((DRAWS, N), bool), f"{ds}/class_mean_readout": np.zeros(DRAWS)})
|
| 65 |
+
results[r][f"{ds}/labels"] = y.astype(np.int64)
|
| 66 |
+
for k in range(DRAWS):
|
| 67 |
+
draw = Draw(ds, X, groups, gait, k, ref)
|
| 68 |
+
idx = np.flatnonzero(draw.scored)
|
| 69 |
+
inputs = reading_inputs(model, X, groups, draw, readings)
|
| 70 |
+
for r in readings:
|
| 71 |
+
assert np.array_equal(inputs[r][..., :6], X[..., :6]), "signal channels changed"
|
| 72 |
+
Z = unit_embeddings(model, inputs[r][idx], batch_size)
|
| 73 |
+
for t in TEXTS:
|
| 74 |
+
results[r][f"{ds}/{t}"][k, idx] = (Z @ V[t].T).argmax(1)
|
| 75 |
+
keep = ~draw.extra[idx] if r == "six_of_twelve" else np.ones(len(idx), bool)
|
| 76 |
+
results[r][f"{ds}/scored"][k, idx[keep]] = True
|
| 77 |
+
results[r][f"{ds}/no_walking_frame"][k] = draw.no_frame
|
| 78 |
+
results[r][f"{ds}/class_mean_readout"][k] = class_mean_readout(Z[keep], y[idx][keep], V["names"])
|
| 79 |
+
for r in readings:
|
| 80 |
+
for t in ("names", "anchors"):
|
| 81 |
+
key = f"{r}/{t}/{ds}"
|
| 82 |
+
if key in reference:
|
| 83 |
+
check[r]["windows"] += int((reference[key] >= 0).sum())
|
| 84 |
+
check[r]["differing"] += int((results[r][f"{ds}/{t}"] != reference[key]).sum())
|
| 85 |
+
key = f"{r}/class_mean_readout/{ds}"
|
| 86 |
+
if key in reference:
|
| 87 |
+
diff = float(np.abs(results[r][f"{ds}/class_mean_readout"] - reference[key]).max())
|
| 88 |
+
check[r]["readout_max_abs_diff"] = max(check[r]["readout_max_abs_diff"], diff)
|
| 89 |
+
print(f"seed {seed}: {ds:12s} done ({time.time() - t0:.0f} s)", flush=True)
|
| 90 |
+
for r in readings:
|
| 91 |
+
np.savez(out / f"{r}.npz", **results[r])
|
| 92 |
+
summary = dict(seed=seed, device=device, batch_size=batch_size, datasets=list(datasets), readings=list(readings),
|
| 93 |
+
torch=torch.__version__, numpy=np.__version__, comparison_with_paper_predictions=check,
|
| 94 |
+
finished=time.strftime("%Y-%m-%d %H:%M:%S"))
|
| 95 |
+
(out / "summary.json").write_text(json.dumps(summary, indent=1) + "\n")
|
| 96 |
+
for r in readings:
|
| 97 |
+
c = check[r]
|
| 98 |
+
if c["windows"]:
|
| 99 |
+
print(f"seed {seed} {r:14s}: {c['differing']} of {c['windows']} window predictions differ from the "
|
| 100 |
+
f"paper's; class-mean readout max |diff| {c['readout_max_abs_diff']:.2e}", flush=True)
|
| 101 |
+
return out
|
setcon/protocol.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The fixed test protocol of the paper (Sec. 3.5 and 4.1).
|
| 2 |
+
|
| 3 |
+
Device all windows of one participant at one site share one mounting. Participants come from
|
| 4 |
+
person_groups.json of the evaluation data (kind "exact"); datasets without exact ids count as one group.
|
| 5 |
+
Context draw k = 0..4 uses numpy.random.default_rng(1000 + k): every group with at least 7 windows gives six random
|
| 6 |
+
context windows, which are never scored. Smaller groups have no context and get zero reference channels.
|
| 7 |
+
6 of 12 (last row of Tab. 1) groups with at least 18 windows draw six extra context windows from their scored
|
| 8 |
+
windows, numpy.random.default_rng([0xCA12, i, k, g]) with i the dataset's index in DATASETS and g the group;
|
| 9 |
+
the extras are not scored either.
|
| 10 |
+
Gait test autocorrelation of the acceleration magnitude, peak at a lag of 0.4-1.4 s >= 0.5 and standard deviation
|
| 11 |
+
>= 0.5 m/s^2; used only by the walking-frame reading. No label is used anywhere except to count.
|
| 12 |
+
Metrics accuracy per dataset = mean over the five draws of the share of correct scored windows; Mean-13 = the
|
| 13 |
+
unweighted mean over the 13 sets in which every sensor has a gyroscope; macro-F1 over the classes present
|
| 14 |
+
in a draw's scored labels; seeds: mean and sample standard deviation (ddof 1).
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import json
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
|
| 23 |
+
from . import processing as PS
|
| 24 |
+
|
| 25 |
+
DATASETS = ["Opp_g", "UCIHAR", "MotionSense", "w-HAR", "Shoaib", "har70plus", "realworld", "TNDA-HAR", "PAMAP",
|
| 26 |
+
"USCHAD", "Mhealth", "Harth", "ut-complex", "Wharf", "WISDM", "DSADS", "UTD-MHAD", "MMAct"]
|
| 27 |
+
# Five sets with at least one acceleration-only sensor; the other 13 form Mean-13.
|
| 28 |
+
ACC_ONLY_SETS = {"har70plus", "Harth", "Wharf", "Mhealth", "MMAct"}
|
| 29 |
+
MEAN13 = [d for d in DATASETS if d not in ACC_ONLY_SETS]
|
| 30 |
+
DRAWS = 5
|
| 31 |
+
CONTEXT, MIN_GROUP = 6, 7
|
| 32 |
+
MIN_GROUP_12, EXTRA = 18, 6
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class EvalData:
|
| 36 |
+
"""The evaluation-data folder: class vectors, class texts, person groups, reference window lists and the
|
| 37 |
+
paper's per-window predictions."""
|
| 38 |
+
|
| 39 |
+
def __init__(self, folder):
|
| 40 |
+
self.dir = Path(folder)
|
| 41 |
+
self.groups = json.loads((self.dir / "protocol" / "person_groups.json").read_text())["datasets"]
|
| 42 |
+
self._vectors = None
|
| 43 |
+
|
| 44 |
+
def class_vectors(self, dataset):
|
| 45 |
+
"""{'names', 'anchors', 'names_descriptions'}: (C, 512) float64 unit vectors in CLIP ViT-B/32 space."""
|
| 46 |
+
if self._vectors is None:
|
| 47 |
+
from safetensors.numpy import load_file
|
| 48 |
+
self._vectors = load_file(str(self.dir / "anchors" / "clip_vit_b32_class_vectors.safetensors"))
|
| 49 |
+
return {t: self._vectors[f"{dataset}/{t}"] for t in ("names", "anchors", "names_descriptions")}
|
| 50 |
+
|
| 51 |
+
def windows(self, dataset):
|
| 52 |
+
return json.loads((self.dir / "protocol" / "windows" / f"{dataset}.json").read_text())
|
| 53 |
+
|
| 54 |
+
def person_groups(self, dataset, n):
|
| 55 |
+
"""Group id per window (kind 'exact'; otherwise one group)."""
|
| 56 |
+
e = self.groups.get(dataset)
|
| 57 |
+
if not e or e["kind"] != "exact":
|
| 58 |
+
return np.zeros(n, int)
|
| 59 |
+
g = np.concatenate([np.full(int(c), int(v), np.int64) for v, c in e["rle"]])
|
| 60 |
+
if len(g) != n:
|
| 61 |
+
raise ValueError(f"{dataset}: person_groups.json covers {len(g)} windows, the data has {n}")
|
| 62 |
+
return g.astype(int)
|
| 63 |
+
|
| 64 |
+
def reference_predictions(self, seed):
|
| 65 |
+
from safetensors.numpy import load_file
|
| 66 |
+
f = self.dir / "reference" / f"predictions_seed{seed}.safetensors"
|
| 67 |
+
return load_file(str(f)) if f.exists() else {}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# ---------------------------------------------------------------------------------------------- gait test
|
| 71 |
+
GAIT_LAGS = (8, 29) # 0.4-1.4 s at 20 Hz
|
| 72 |
+
GAIT_MIN_PEAK, GAIT_MIN_SD = 0.5, 0.5
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def gait_mask(X):
|
| 76 |
+
"""(N, T, 22, 9) -> bool (N,): autocorrelation of the acceleration magnitude (mean over worn sites)."""
|
| 77 |
+
occ = np.abs(X[..., :3]).sum((0, 1, 3)) > 0
|
| 78 |
+
a = np.linalg.norm(X[:, :, occ, :3].astype(np.float64), axis=-1)
|
| 79 |
+
valid = np.abs(X[:, :, occ, :3]).sum(-1) > 0
|
| 80 |
+
a = np.where(valid, a, np.nan)
|
| 81 |
+
a = a - np.nanmean(a, 1, keepdims=True)
|
| 82 |
+
a = np.nan_to_num(a)
|
| 83 |
+
sd = a.std(1).mean(1)
|
| 84 |
+
den = (a ** 2).sum(1) + 1e-9
|
| 85 |
+
r = np.stack([(a[:, :-lag] * a[:, lag:]).sum(1) / den for lag in range(*GAIT_LAGS)], 1)
|
| 86 |
+
return (r.mean(2).max(1) >= GAIT_MIN_PEAK) & (sd >= GAIT_MIN_SD)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# ---------------------------------------------------------------------------------------------- walking frame
|
| 90 |
+
def walking_frame(acc, gyr, g):
|
| 91 |
+
"""Training-free reference (paper Sec. 3.2): up = mean gravity direction, forward = principal horizontal axis of
|
| 92 |
+
the dynamic acceleration, over the given windows. Returns D = [right; up; forward] (3, 3)."""
|
| 93 |
+
has_gyro = np.abs(gyr).sum() > 0
|
| 94 |
+
e = (gyr ** 2).sum(-1).mean(1) if has_gyro else acc.std(1).sum(-1)
|
| 95 |
+
moving = e >= np.quantile(e, 0.0) # all given windows (they already passed the gait test)
|
| 96 |
+
up = PS.unit(g[moving].mean((0, 1)))
|
| 97 |
+
dyn = acc[moving] - acc[moving].mean(1, keepdims=True)
|
| 98 |
+
h = dyn - (dyn @ up)[..., None] * up
|
| 99 |
+
_, V = np.linalg.eigh(np.einsum("nti,ntj->ij", h, h))
|
| 100 |
+
f = PS.unit(V[:, -1] - (V[:, -1] @ up) * up)
|
| 101 |
+
return np.stack([np.cross(up, f), up, f])
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def apply_walking_frame(X, frame_windows):
|
| 105 |
+
"""Reference channels of every worn site := D g_t with D from the windows `frame_windows` (bool over X)."""
|
| 106 |
+
Xb = X.copy()
|
| 107 |
+
for s in np.where(np.abs(X[..., 6:9]).sum((0, 1, 3)) > 0)[0]:
|
| 108 |
+
D = walking_frame(*PS.device_frame_signals(X[frame_windows][:, :, s]))
|
| 109 |
+
ge = PS.unit(X[:, :, s, 6:9].astype(np.float64))
|
| 110 |
+
valid = np.abs(X[:, :, s, 6:9]).sum(-1) > 0
|
| 111 |
+
Xb[:, :, s, 6:9] = np.where(valid[..., None], ge @ D.T, 0.0).astype(X.dtype)
|
| 112 |
+
return Xb
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# ---------------------------------------------------------------------------------------------- context draws
|
| 116 |
+
def context_draw(X, groups, gait, k):
|
| 117 |
+
"""Draw k: six random context windows per group (rng 1000 + k). Returns
|
| 118 |
+
walking X with the walking-frame reference (from the gait windows among the six; zero if there is none)
|
| 119 |
+
context bool (N,) the context windows (never scored)
|
| 120 |
+
no_frame bool (N,) windows of devices without a walking-frame reference (also every group < 7 windows)"""
|
| 121 |
+
rng = np.random.default_rng(1000 + k)
|
| 122 |
+
Xb = X.copy()
|
| 123 |
+
cal = np.zeros(len(X), bool)
|
| 124 |
+
unknown = np.zeros(len(X), bool)
|
| 125 |
+
for g in np.unique(groups):
|
| 126 |
+
idx = np.where(groups == g)[0]
|
| 127 |
+
if len(idx) < MIN_GROUP:
|
| 128 |
+
unknown[idx] = True
|
| 129 |
+
Xb[idx, :, :, 6:9] = 0
|
| 130 |
+
continue
|
| 131 |
+
c = rng.choice(idx, CONTEXT, replace=False)
|
| 132 |
+
cal[c] = True
|
| 133 |
+
frame_rows = np.zeros(len(X), bool)
|
| 134 |
+
frame_rows[c[gait[c]]] = True
|
| 135 |
+
if frame_rows.any():
|
| 136 |
+
Xb[idx] = apply_walking_frame(X[idx], frame_rows[idx])
|
| 137 |
+
else:
|
| 138 |
+
unknown[idx] = True
|
| 139 |
+
Xb[idx, :, :, 6:9] = 0
|
| 140 |
+
return Xb, cal, unknown
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def worn_sites(X):
|
| 144 |
+
return np.where(np.abs(X[..., 6:9]).sum((0, 1, 3)) > 0)[0]
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def device_keys(X, groups, context):
|
| 148 |
+
"""[(group, site)] of every device (group >= 7 windows x worn site) and the six context rows of every group."""
|
| 149 |
+
keys, rows = [], {}
|
| 150 |
+
for g in np.unique(groups):
|
| 151 |
+
idx = np.where(groups == g)[0]
|
| 152 |
+
if len(idx) < MIN_GROUP:
|
| 153 |
+
continue
|
| 154 |
+
c = idx[context[idx]]
|
| 155 |
+
assert len(c) == CONTEXT, (g, len(c))
|
| 156 |
+
rows[int(g)] = c
|
| 157 |
+
for s in worn_sites(X[idx]):
|
| 158 |
+
keys.append((int(g), int(s)))
|
| 159 |
+
return keys, rows
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def extra_context(groups, context, context_rows, dataset_index, k):
|
| 163 |
+
"""6 of 12: six extra context windows for every group with >= 18 windows, drawn from its scored windows.
|
| 164 |
+
Returns the extra windows (bool (N,)) and the twelve-window pool of every such group."""
|
| 165 |
+
big = [int(g) for g in np.unique(groups) if (groups == g).sum() >= MIN_GROUP_12]
|
| 166 |
+
extra = np.zeros(len(groups), bool)
|
| 167 |
+
pools = {}
|
| 168 |
+
for g in sorted(context_rows):
|
| 169 |
+
if g not in big:
|
| 170 |
+
continue
|
| 171 |
+
rows_g = np.where(groups == g)[0]
|
| 172 |
+
candidates = rows_g[~context[rows_g]]
|
| 173 |
+
ex = np.sort(np.random.default_rng([0xCA12, dataset_index, k, g]).choice(candidates, EXTRA, replace=False))
|
| 174 |
+
extra[ex] = True
|
| 175 |
+
pools[g] = np.sort(np.concatenate([context_rows[g], ex]))
|
| 176 |
+
return extra, pools
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class Draw:
|
| 180 |
+
"""One context draw of one dataset, checked against the reference window lists of the evaluation data."""
|
| 181 |
+
|
| 182 |
+
def __init__(self, dataset, X, groups, gait, k, reference):
|
| 183 |
+
self.k = k
|
| 184 |
+
self.walking, self.context, self.no_frame = context_draw(X, groups, gait, k)
|
| 185 |
+
self.keys, self.rows = device_keys(X, groups, self.context)
|
| 186 |
+
self.extra, self.pools = extra_context(groups, self.context, self.rows, DATASETS.index(dataset), k)
|
| 187 |
+
r = reference["draws"][k]
|
| 188 |
+
assert np.array_equal(np.flatnonzero(self.context), r["context"]), f"{dataset} draw {k}: context differs"
|
| 189 |
+
assert np.array_equal(np.flatnonzero(self.no_frame), r["no_walking_frame"]), f"{dataset} draw {k}: walking frame"
|
| 190 |
+
assert np.array_equal(np.flatnonzero(self.extra), r["extra_context_six_of_twelve"]), f"{dataset} draw {k}: 6 of 12"
|
| 191 |
+
self.scored = ~self.context # every reading embeds these windows, in this order
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def dataset_protocol(dataset, X, eval_data):
|
| 195 |
+
"""Person groups and gait windows of one dataset (checked against the reference lists) -> (groups, gait, ref)."""
|
| 196 |
+
groups = eval_data.person_groups(dataset, len(X))
|
| 197 |
+
gait = gait_mask(X)
|
| 198 |
+
ref = eval_data.windows(dataset)
|
| 199 |
+
assert ref["n_windows"] == len(X), dataset
|
| 200 |
+
assert np.array_equal(np.flatnonzero(gait), ref["gait"]), f"{dataset}: gait windows differ"
|
| 201 |
+
return groups, gait, ref
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def macro_f1(pred, y, n_classes):
|
| 205 |
+
f = []
|
| 206 |
+
for c in range(n_classes):
|
| 207 |
+
tp = np.sum((pred == c) & (y == c))
|
| 208 |
+
fp = np.sum((pred == c) & (y != c))
|
| 209 |
+
fn = np.sum((pred != c) & (y == c))
|
| 210 |
+
if tp + fn == 0:
|
| 211 |
+
continue
|
| 212 |
+
f.append(0.0 if tp == 0 else 2 * tp / (2 * tp + fp + fn))
|
| 213 |
+
return 100 * float(np.mean(f))
|
setcon/references.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reference channels of every device under the five readings of the paper.
|
| 2 |
+
|
| 3 |
+
six_random calibrator on the six random context windows of the device (Tab. 1 row 3, Tab. 2 'Calibrator')
|
| 4 |
+
six_of_twelve calibrator on the six of twelve context windows it selects itself (Tab. 1 last row, abstract)
|
| 5 |
+
walking_frame training-free walking frame from the gait windows among the six (Tab. 2 'Walking frame')
|
| 6 |
+
zeroed reference channels zero everywhere (Tab. 2 'Zeroed')
|
| 7 |
+
one_window calibrator on one of the six windows, numpy.random.default_rng([2000, k, g]) (Sec. 4.3)
|
| 8 |
+
|
| 9 |
+
The calibrator always runs on CPU in float32 with the batching of the paper: one pass over all devices of a dataset
|
| 10 |
+
and draw; for 6 of 12, one pass per elimination round over all candidate subsets of all devices. Devices of groups
|
| 11 |
+
with fewer than 7 windows keep zero reference channels.
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
from . import processing as PS
|
| 18 |
+
from .protocol import Draw
|
| 19 |
+
|
| 20 |
+
READINGS = ("six_random", "six_of_twelve", "walking_frame", "zeroed", "one_window")
|
| 21 |
+
CHUNK = 4096
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def device_input(model, X, rows, site):
|
| 25 |
+
"""Calibrator input of one device from its windows `rows` at `site`. Whether the device has a gyroscope is a
|
| 26 |
+
property of the dataset's sensor at that site."""
|
| 27 |
+
has_gyro = bool(np.abs(X[:, :, site, 3:6]).sum() > 0)
|
| 28 |
+
w, v = PS.calibrator_input(X[rows][:, :, site], has_gyro, model.config.force_scale, model.config.rate_scale)
|
| 29 |
+
return w, v, has_gyro
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def calibrate(model, X, keys, rows_of):
|
| 33 |
+
"""{(group, site): reference (3, 3)} in one calibrator pass; rows_of(group) gives the context rows."""
|
| 34 |
+
if not keys:
|
| 35 |
+
return {}
|
| 36 |
+
ws, vs, missing = [], [], []
|
| 37 |
+
for g, s in keys:
|
| 38 |
+
w, v, has_gyro = device_input(model, X, rows_of(g), s)
|
| 39 |
+
ws.append(w)
|
| 40 |
+
vs.append(v)
|
| 41 |
+
missing.append(not has_gyro)
|
| 42 |
+
res = model.calibrate_batch(np.stack(ws), np.stack(vs), [s for _, s in keys], missing)
|
| 43 |
+
return {key: res["reference"][i] for i, key in enumerate(keys)}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def six_of_twelve(model, X, draw: Draw):
|
| 47 |
+
"""{(group, site): reference} for the devices whose group has a twelve-window pool, by greedy elimination."""
|
| 48 |
+
pool = {}
|
| 49 |
+
for g, s in draw.keys:
|
| 50 |
+
if g in draw.pools:
|
| 51 |
+
w, v, has_gyro = device_input(model, X, draw.pools[g], s)
|
| 52 |
+
pool[(g, s)] = (w, v, s, not has_gyro)
|
| 53 |
+
store = {}
|
| 54 |
+
|
| 55 |
+
def score(requests):
|
| 56 |
+
need = list(dict.fromkeys(q for q in requests if q not in store))
|
| 57 |
+
by_size = {}
|
| 58 |
+
for q in need:
|
| 59 |
+
by_size.setdefault(len(q[1]), []).append(q)
|
| 60 |
+
for _, qs in sorted(by_size.items()):
|
| 61 |
+
for c0 in range(0, len(qs), CHUNK):
|
| 62 |
+
chunk = qs[c0:c0 + CHUNK]
|
| 63 |
+
res = model.calibrate_batch(np.stack([pool[q[0]][0][list(q[1])] for q in chunk]),
|
| 64 |
+
np.stack([pool[q[0]][1][list(q[1])] for q in chunk]),
|
| 65 |
+
[pool[q[0]][2] for q in chunk], [pool[q[0]][3] for q in chunk])
|
| 66 |
+
sc = PS.tilt_score(res["M"], res["V"], res["s"], res["logit"])
|
| 67 |
+
for i, q in enumerate(chunk):
|
| 68 |
+
store[q] = (res["reference"][i], float(sc[i]))
|
| 69 |
+
return {q: store[q][1] for q in requests}
|
| 70 |
+
|
| 71 |
+
if not pool:
|
| 72 |
+
return {}
|
| 73 |
+
chosen = PS.select_by_elimination({key: 12 for key in pool}, score, keep=6)
|
| 74 |
+
return {key: store[(key, chosen[key])][0] for key in pool}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def put(Xr, X, groups, key, reference):
|
| 78 |
+
"""Reference channels of one device := Q g_t on its valid frames."""
|
| 79 |
+
g, s = key
|
| 80 |
+
rows = np.where(groups == g)[0]
|
| 81 |
+
Xr[rows, :, s] = PS.set_reference(X[rows][:, :, s], reference)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def reading_inputs(model, X, groups, draw: Draw, readings):
|
| 85 |
+
"""{reading: X with the reference channels of that reading} for one draw."""
|
| 86 |
+
out = {}
|
| 87 |
+
six = None
|
| 88 |
+
if {"six_random", "six_of_twelve"} & set(readings):
|
| 89 |
+
six = calibrate(model, X, draw.keys, lambda g: draw.rows[g])
|
| 90 |
+
for r in readings:
|
| 91 |
+
if r == "walking_frame":
|
| 92 |
+
out[r] = draw.walking
|
| 93 |
+
elif r == "zeroed":
|
| 94 |
+
Xz = X.copy()
|
| 95 |
+
Xz[..., 6:9] = 0.0
|
| 96 |
+
out[r] = Xz
|
| 97 |
+
else:
|
| 98 |
+
if r == "six_random":
|
| 99 |
+
refs = six
|
| 100 |
+
elif r == "six_of_twelve":
|
| 101 |
+
sel = six_of_twelve(model, X, draw)
|
| 102 |
+
refs = {key: sel.get(key, six[key]) for key in draw.keys}
|
| 103 |
+
elif r == "one_window":
|
| 104 |
+
sub = {g: np.sort(np.random.default_rng([2000, draw.k, int(g)]).choice(rows, 1, replace=False))
|
| 105 |
+
for g, rows in draw.rows.items()}
|
| 106 |
+
refs = calibrate(model, X, draw.keys, lambda g: sub[g])
|
| 107 |
+
else:
|
| 108 |
+
raise ValueError(r)
|
| 109 |
+
Xr = draw.walking.copy()
|
| 110 |
+
for key in draw.keys:
|
| 111 |
+
put(Xr, X, groups, key, refs[key])
|
| 112 |
+
out[r] = Xr
|
| 113 |
+
return out
|
setcon/tables.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The paper's SetCon numbers from the per-seed results of setcon.evaluate, compared with the printed values.
|
| 2 |
+
|
| 3 |
+
Seeds give mean and sample standard deviation (ddof 1). A number matches when it rounds to the printed digits.
|
| 4 |
+
"""
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
import statistics
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
from .protocol import DATASETS, MEAN13, macro_f1
|
| 14 |
+
|
| 15 |
+
# Tab. 3: motion group of every Mean-13 class, from the class name only.
|
| 16 |
+
POSTURE, TRANSITION, LOCOMOTION, DIRECTION, HAND, WHOLE_BODY = (
|
| 17 |
+
"posture", "transition", "locomotion", "direction", "hand/arm", "other whole-body")
|
| 18 |
+
P, T, L, D, H, O = POSTURE, TRANSITION, LOCOMOTION, DIRECTION, HAND, WHOLE_BODY
|
| 19 |
+
VERTICAL = ("stair", "upstairs", "downstairs", "climbing", "elevator")
|
| 20 |
+
GROUP_OF_CLASS = {
|
| 21 |
+
"Opp_g": {"stand": P, "walk": L, "sit": P, "lie": P},
|
| 22 |
+
"UCIHAR": {"walk": L, "walk upstairs": D, "walk downstairs": D, "sit": P, "stand": P, "lay": P},
|
| 23 |
+
"MotionSense": {"downstairs": D, "jogging": L, "sit": P, "stand up": P, "upstairs": D, "walking": L},
|
| 24 |
+
"w-HAR": {"walk": L, "sit": P, "stand": P, "jump": O, "lie down": P, "stairs up": D, "stairs down": D},
|
| 25 |
+
"Shoaib": {"walking": L, "standing": P, "jogging": L, "sitting": P, "biking": O, "upstairs": D, "downstairs": D},
|
| 26 |
+
"realworld": {"lying": P, "jumping": O, "standing": P, "walking": L, "sitting": P, "climbing down": D,
|
| 27 |
+
"climbing up": D, "running": L},
|
| 28 |
+
"TNDA-HAR": {"sitting": P, "standing": P, "lying down": P, "ascending stairs": D, "descending stairs": D,
|
| 29 |
+
"riding": O, "walking": L, "jogging": L},
|
| 30 |
+
"PAMAP": {"lying": P, "sitting": P, "standing": P, "walking": L, "running": L, "cycling": O, "nordic walking": L,
|
| 31 |
+
"ascending stairs": D, "descending stairs": D, "vacuum cleaning": H, "ironing": H, "rope jumping": O},
|
| 32 |
+
"USCHAD": {"walk forward": L, "walk left": D, "walk right": D, "walk upstairs": D, "walk downstairs": D,
|
| 33 |
+
"run forward": L, "jump up": O, "sit": P, "stand": P, "sleep": P, "elevator up": D, "elevator down": D},
|
| 34 |
+
"ut-complex": {"walking": L, "standing": P, "jogging": L, "sitting": P, "biking": O, "upstairs": D,
|
| 35 |
+
"downstairs": D, "typing": H, "writing": H, "drinking coffee": H, "giving a talk": H, "smoking": H,
|
| 36 |
+
"eating": H},
|
| 37 |
+
"WISDM": {"walking": L, "jogging": L, "stairs": L, "sitting": P, "standing": P, "typing": H, "brushing teeth": H,
|
| 38 |
+
"eating soup": H, "eating chips": H, "eating pasta": H, "drinking cup": H, "eating sandwich": H,
|
| 39 |
+
"kicking ball": O, "playing ball": O, "dribbling ball": O, "writing": H, "clapping": H,
|
| 40 |
+
"folding clothes": H},
|
| 41 |
+
"DSADS": {"sitting": P, "standing": P, "lying on back": P, "lying on right side": P, "ascending stairs": D,
|
| 42 |
+
"descending stairs": D, "standing in an elevator still": P, "moving around in an elevator": O,
|
| 43 |
+
"walking slowly": L, "walking on a treadmill in flat positions)": L,
|
| 44 |
+
"walking on a treadmill in inclined positions)": L, "running on a treadmill fast": L,
|
| 45 |
+
"exercising on a stepper": O, "exercising on a cross trainer": O,
|
| 46 |
+
"cycling on an exercise bike in horizontal positions": O,
|
| 47 |
+
"cycling on an exercise bike in vertical positions": O, "rowing": O, "jumping": O,
|
| 48 |
+
"playing basketball": O},
|
| 49 |
+
"UTD-MHAD": {"right arm swipe to the left": D, "right arm swipe to the right": D, "right hand wave": H,
|
| 50 |
+
"two hand front clap": H, "right arm throw": H, "cross arms in the chest": H, "basketball shoot": H,
|
| 51 |
+
"right hand draw x": H, "right hand draw circle (clockwise)": D,
|
| 52 |
+
"right hand draw circle (counter clockwise)": D, "draw triangle": H, "bowling (right hand)": H,
|
| 53 |
+
"front boxing": H, "baseball swing from right": H, "tennis right hand forehand swing": H,
|
| 54 |
+
"arm curl (two arms)": H, "tennis serve": H, "two hand push": H, "right hand knock on door": H,
|
| 55 |
+
"right hand catch an object": H, "right hand pick up and throw": H, "jogging in place": L,
|
| 56 |
+
"walking in place": L, "sit to stand": T, "stand to sit": T,
|
| 57 |
+
"forward lunge (left foot forward)": O, "squat (two arms stretch out)": O},
|
| 58 |
+
}
|
| 59 |
+
TAB3_GROUPS = (("Posture", lambda g, c: g == P),
|
| 60 |
+
("Stairs, elevator", lambda g, c: g == D and any(w in c for w in VERTICAL)),
|
| 61 |
+
("Left/right, circle", lambda g, c: g == D and not any(w in c for w in VERTICAL)),
|
| 62 |
+
("Locomotion", lambda g, c: g == L), ("Hand and arm", lambda g, c: g == H),
|
| 63 |
+
("Other whole-body", lambda g, c: g == O))
|
| 64 |
+
POSTURE_NAMES = {"sit": {"sit", "sitting", "sitting relaxing"}, "stand": {"stand", "standing", "standing still"},
|
| 65 |
+
"lie": {"lying", "lying down", "lay", "lie", "lie down", "lying on back", "lying on right side",
|
| 66 |
+
"sleep"}}
|
| 67 |
+
|
| 68 |
+
# Printed values: (mean, sd or None, decimals).
|
| 69 |
+
PAPER_MAIN = {
|
| 70 |
+
"Tab. 1, 6 random windows: class-mean readout": (91.5, 0.2, 1),
|
| 71 |
+
"Tab. 1, 6 random windows: accuracy, names": (55.9, 0.4, 1),
|
| 72 |
+
"Tab. 1, 6 random windows: accuracy, anchors": (64.7, 0.6, 1),
|
| 73 |
+
"Tab. 1, 6 random windows: macro-F1, names": (50.2, 0.6, 1),
|
| 74 |
+
"Tab. 1, 6 random windows: macro-F1, anchors": (60.5, 0.5, 1),
|
| 75 |
+
"Tab. 1, 6 of 12 windows: class-mean readout": (91.6, 0.2, 1),
|
| 76 |
+
"Tab. 1, 6 of 12 windows: accuracy, names (abstract)": (56.6, 0.6, 1),
|
| 77 |
+
"Tab. 1, 6 of 12 windows: accuracy, anchors (abstract, Fig. 1)": (65.3, 0.4, 1),
|
| 78 |
+
"Tab. 1, 6 of 12 windows: macro-F1, names": (51.6, 0.7, 1),
|
| 79 |
+
"Tab. 1, 6 of 12 windows: macro-F1, anchors": (62.1, 0.4, 1),
|
| 80 |
+
}
|
| 81 |
+
PAPER_MORE = {
|
| 82 |
+
"Tab. 2, calibrator: names": (55.9, 0.4, 1),
|
| 83 |
+
"Tab. 2, calibrator: anchors": (64.7, 0.6, 1),
|
| 84 |
+
"Tab. 2, walking frame: names": (54.6, 0.2, 1),
|
| 85 |
+
"Tab. 2, walking frame: anchors": (62.7, 0.6, 1),
|
| 86 |
+
"Tab. 2, zeroed: names": (41.5, 0.7, 1),
|
| 87 |
+
"Tab. 2, zeroed: anchors": (48.0, 2.1, 1),
|
| 88 |
+
"Tab. 3, Posture": (53.3, 0.8, 1),
|
| 89 |
+
"Tab. 3, Stairs, elevator": (53.2, 1.8, 1),
|
| 90 |
+
"Tab. 3, Left/right, circle": (18.8, 3.8, 1),
|
| 91 |
+
"Tab. 3, Locomotion": (64.0, 4.7, 1),
|
| 92 |
+
"Tab. 3, Hand and arm": (17.8, 1.1, 1),
|
| 93 |
+
"Tab. 3, Other whole-body": (56.2, 2.5, 1),
|
| 94 |
+
"Sec. 4.3: zeroed reference, anchors, posture windows called lying (%)": (86, None, 0),
|
| 95 |
+
"Sec. 4.3: one context window, names": (53.7, None, 1),
|
| 96 |
+
"Sec. 4.3: scored windows without gait context (%)": (15, None, 0),
|
| 97 |
+
"Sec. 4.3: calibrator minus zeroed on those windows, names": (9.6, None, 1),
|
| 98 |
+
"Sec. 4.4: anchor gain (anchors minus names)": (8.7, None, 1),
|
| 99 |
+
"Sec. 4.4: descriptions added to the name (gain over names)": (6.3, None, 1),
|
| 100 |
+
"Sec. 4.4: class-mean readout minus names": (36, None, 0),
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def msd(values):
|
| 105 |
+
values = [float(v) for v in values]
|
| 106 |
+
return dict(mean=float(np.mean(values)), sd=statistics.stdev(values) if len(values) > 1 else None,
|
| 107 |
+
per_seed=values)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class Results:
|
| 111 |
+
"""The per-seed result files of setcon.evaluate."""
|
| 112 |
+
|
| 113 |
+
def __init__(self, results_dir, seeds, eval_data):
|
| 114 |
+
self.dir = Path(results_dir)
|
| 115 |
+
self.seeds = list(seeds)
|
| 116 |
+
self.classes = {ds: json.loads((Path(eval_data) / "protocol" / "windows" / f"{ds}.json").read_text())["classes"]
|
| 117 |
+
for ds in DATASETS}
|
| 118 |
+
self._cache = {}
|
| 119 |
+
|
| 120 |
+
def load(self, seed, reading):
|
| 121 |
+
key = (seed, reading)
|
| 122 |
+
if key not in self._cache:
|
| 123 |
+
f = self.dir / f"seed{seed}" / f"{reading}.npz"
|
| 124 |
+
with np.load(f, allow_pickle=False) as z:
|
| 125 |
+
self._cache[key] = {k: z[k] for k in z.files}
|
| 126 |
+
return self._cache[key]
|
| 127 |
+
|
| 128 |
+
def has(self, reading):
|
| 129 |
+
return all((self.dir / f"seed{s}" / f"{reading}.npz").exists() for s in self.seeds)
|
| 130 |
+
|
| 131 |
+
def draws(self, seed, reading, ds, text):
|
| 132 |
+
"""[(scored mask, predictions on the scored windows, labels of the scored windows)] per draw."""
|
| 133 |
+
z = self.load(seed, reading)
|
| 134 |
+
y = z[f"{ds}/labels"]
|
| 135 |
+
return [(sc, z[f"{ds}/{text}"][k][sc], y[sc]) for k, sc in enumerate(z[f"{ds}/scored"])]
|
| 136 |
+
|
| 137 |
+
def dataset_metric(self, seed, reading, ds, text, metric):
|
| 138 |
+
if metric == "readout":
|
| 139 |
+
return float(np.mean(self.load(seed, reading)[f"{ds}/class_mean_readout"]))
|
| 140 |
+
vals = []
|
| 141 |
+
for _, p, y in self.draws(seed, reading, ds, text):
|
| 142 |
+
vals.append(100 * np.mean(p == y) if metric == "acc" else macro_f1(p, y, len(self.classes[ds])))
|
| 143 |
+
return float(np.mean(vals))
|
| 144 |
+
|
| 145 |
+
def mean13(self, reading, text, metric="acc"):
|
| 146 |
+
return msd([np.mean([self.dataset_metric(s, reading, d, text, metric) for d in MEAN13]) for s in self.seeds])
|
| 147 |
+
|
| 148 |
+
def class_recall(self, seed, reading, ds, text="names"):
|
| 149 |
+
rec = {}
|
| 150 |
+
draws = self.draws(seed, reading, ds, text)
|
| 151 |
+
for c, name in enumerate(self.classes[ds]):
|
| 152 |
+
vals = [100 * np.mean(p[y == c] == c) for _, p, y in draws if (y == c).any()]
|
| 153 |
+
if vals:
|
| 154 |
+
rec[name] = float(np.mean(vals))
|
| 155 |
+
return rec
|
| 156 |
+
|
| 157 |
+
def tab3(self, reading="six_random"):
|
| 158 |
+
out = {}
|
| 159 |
+
for gname, f in TAB3_GROUPS:
|
| 160 |
+
per_seed = []
|
| 161 |
+
for s in self.seeds:
|
| 162 |
+
vals = [v for d in MEAN13 for c, v in self.class_recall(s, reading, d).items()
|
| 163 |
+
if f(GROUP_OF_CLASS[d][c], c)]
|
| 164 |
+
per_seed.append(float(np.mean(vals)))
|
| 165 |
+
out[gname] = dict(**msd(per_seed), n_classes=len(vals))
|
| 166 |
+
return out
|
| 167 |
+
|
| 168 |
+
def posture_shares(self, reading, text="anchors"):
|
| 169 |
+
"""Share (%) of the sit / stand / lie windows predicted as sit / stand / lie: 7 Mean-13 sets with >= 20
|
| 170 |
+
windows of each posture, draws pooled, equal mean over sets, then over the three true postures."""
|
| 171 |
+
fam = lambda t: next((f for f, s in POSTURE_NAMES.items() if t in s), "other") # noqa: E731
|
| 172 |
+
labels = {d: self.load(self.seeds[0], reading)[f"{d}/labels"] for d in MEAN13}
|
| 173 |
+
sets = [d for d in MEAN13 if min(int((np.array([fam(t) for t in self.classes[d]])[labels[d]] == f).sum())
|
| 174 |
+
for f in ("sit", "stand", "lie")) >= 20]
|
| 175 |
+
shares = []
|
| 176 |
+
for s in self.seeds:
|
| 177 |
+
mats = []
|
| 178 |
+
for d in sets:
|
| 179 |
+
tf = np.array([fam(t) for t in self.classes[d]])
|
| 180 |
+
pf = np.array([("sit", "stand", "lie", "other").index(fam(t)) for t in self.classes[d]])
|
| 181 |
+
M = np.zeros((3, 4))
|
| 182 |
+
for i, true in enumerate(("sit", "stand", "lie")):
|
| 183 |
+
c = np.zeros(4)
|
| 184 |
+
for _, p, y in self.draws(s, reading, d, text):
|
| 185 |
+
c += np.bincount(pf[p[tf[y] == true]], minlength=4)
|
| 186 |
+
M[i] = 100 * c / c.sum()
|
| 187 |
+
mats.append(M)
|
| 188 |
+
shares.append(np.mean(mats, 0)[:, :3].mean(0))
|
| 189 |
+
S = np.array(shares)
|
| 190 |
+
return dict(datasets=sets, sit=msd(S[:, 0]), stand=msd(S[:, 1]), lie=msd(S[:, 2]))
|
| 191 |
+
|
| 192 |
+
def no_gait(self):
|
| 193 |
+
"""Windows of devices whose six context windows hold no gait window: share of all scored windows (Mean-13)
|
| 194 |
+
and accuracy of the calibrator reference minus the zeroed reference on them (names)."""
|
| 195 |
+
sub = tot = 0
|
| 196 |
+
gains = []
|
| 197 |
+
for i, s in enumerate(self.seeds):
|
| 198 |
+
co = cz = n = 0
|
| 199 |
+
for d in MEAN13:
|
| 200 |
+
zo, zz = self.load(s, "six_random"), self.load(s, "zeroed")
|
| 201 |
+
y = zo[f"{d}/labels"]
|
| 202 |
+
for k in range(len(zo[f"{d}/scored"])):
|
| 203 |
+
sc = zo[f"{d}/scored"][k]
|
| 204 |
+
assert np.array_equal(sc, zz[f"{d}/scored"][k])
|
| 205 |
+
unk = zo[f"{d}/no_walking_frame"][k][sc]
|
| 206 |
+
yy = y[sc]
|
| 207 |
+
co += int((zo[f"{d}/names"][k][sc][unk] == yy[unk]).sum())
|
| 208 |
+
cz += int((zz[f"{d}/names"][k][sc][unk] == yy[unk]).sum())
|
| 209 |
+
n += int(unk.sum())
|
| 210 |
+
if i == 0:
|
| 211 |
+
sub += int(unk.sum())
|
| 212 |
+
tot += int(sc.sum())
|
| 213 |
+
gains.append(100 * (co - cz) / n)
|
| 214 |
+
return dict(share=100 * sub / tot, windows=sub, all=tot, gain=msd(gains))
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def main_numbers(R: Results):
|
| 218 |
+
out = {}
|
| 219 |
+
for reading, label in (("six_random", "6 random windows"), ("six_of_twelve", "6 of 12 windows")):
|
| 220 |
+
out[f"Tab. 1, {label}: class-mean readout"] = R.mean13(reading, "names", "readout")
|
| 221 |
+
out[f"Tab. 1, {label}: accuracy, names" + (" (abstract)" if reading == "six_of_twelve" else "")] = \
|
| 222 |
+
R.mean13(reading, "names")
|
| 223 |
+
out[f"Tab. 1, {label}: accuracy, anchors" + (" (abstract, Fig. 1)" if reading == "six_of_twelve" else "")] = \
|
| 224 |
+
R.mean13(reading, "anchors")
|
| 225 |
+
out[f"Tab. 1, {label}: macro-F1, names"] = R.mean13(reading, "names", "f1")
|
| 226 |
+
out[f"Tab. 1, {label}: macro-F1, anchors"] = R.mean13(reading, "anchors", "f1")
|
| 227 |
+
return out
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def more_numbers(R: Results):
|
| 231 |
+
out = {}
|
| 232 |
+
for reading, label in (("six_random", "calibrator"), ("walking_frame", "walking frame"), ("zeroed", "zeroed")):
|
| 233 |
+
for text in ("names", "anchors"):
|
| 234 |
+
out[f"Tab. 2, {label}: {text}"] = R.mean13(reading, text)
|
| 235 |
+
for gname, v in R.tab3().items():
|
| 236 |
+
out[f"Tab. 3, {gname}"] = v
|
| 237 |
+
out["Sec. 4.3: zeroed reference, anchors, posture windows called lying (%)"] = R.posture_shares("zeroed")["lie"]
|
| 238 |
+
out["Sec. 4.3: one context window, names"] = R.mean13("one_window", "names")
|
| 239 |
+
ng = R.no_gait()
|
| 240 |
+
out["Sec. 4.3: scored windows without gait context (%)"] = dict(mean=ng["share"], sd=None, per_seed=[])
|
| 241 |
+
out["Sec. 4.3: calibrator minus zeroed on those windows, names"] = ng["gain"]
|
| 242 |
+
names, anchors = R.mean13("six_random", "names"), R.mean13("six_random", "anchors")
|
| 243 |
+
desc, readout = R.mean13("six_random", "names_descriptions"), R.mean13("six_random", "names", "readout")
|
| 244 |
+
diff = lambda a, b: msd([x - y for x, y in zip(a["per_seed"], b["per_seed"])]) # noqa: E731
|
| 245 |
+
out["Sec. 4.4: anchor gain (anchors minus names)"] = diff(anchors, names)
|
| 246 |
+
out["Sec. 4.4: descriptions added to the name (gain over names)"] = diff(desc, names)
|
| 247 |
+
out["Sec. 4.4: class-mean readout minus names"] = diff(readout, names)
|
| 248 |
+
return out
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def compare(numbers, paper):
|
| 252 |
+
"""Rows (label, printed, recomputed, per seed, match) for every number with a printed value."""
|
| 253 |
+
rows = []
|
| 254 |
+
for label, (pm, psd, dec) in paper.items():
|
| 255 |
+
v = numbers[label]
|
| 256 |
+
got = f"{v['mean']:.{dec}f}" + (f" ± {v['sd']:.{dec}f}" if psd is not None else "")
|
| 257 |
+
printed = f"{pm:.{dec}f}" + (f" ± {psd:.{dec}f}" if psd is not None else "")
|
| 258 |
+
seeds = " / ".join(f"{x:.2f}" for x in v["per_seed"])
|
| 259 |
+
rows.append((label, printed, got, f"{v['mean']:.3f}" + (f" ± {v['sd']:.3f}" if v["sd"] is not None else ""),
|
| 260 |
+
seeds, got == printed))
|
| 261 |
+
return rows
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def format_rows(rows):
|
| 265 |
+
w = max(len(r[0]) for r in rows)
|
| 266 |
+
lines = [f"{'number':<{w}} {'paper':>12} {'recomputed':>12} {'full precision':>16} seeds 1 / 2 / 3"]
|
| 267 |
+
for label, printed, got, full, seeds, ok in rows:
|
| 268 |
+
lines.append(f"{label:<{w}} {printed:>12} {got:>12} {full:>16} {seeds} {'ok' if ok else 'differs'}")
|
| 269 |
+
return "\n".join(lines)
|