braindecode 2.1.0.dev181714115__py3-none-any.whl → 2.1.0.dev182154342__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. braindecode/augmentation/functional.py +1 -1
  2. braindecode/augmentation/transforms.py +1 -1
  3. braindecode/datasets/base.py +17 -12
  4. braindecode/datasets/bids/hub.py +13 -1
  5. braindecode/datautil/serialization.py +7 -0
  6. braindecode/functional/__init__.py +10 -0
  7. braindecode/functional/attention.py +4 -14
  8. braindecode/functional/channels.py +282 -0
  9. braindecode/models/__init__.py +6 -0
  10. braindecode/models/attn_sleep.py +40 -6
  11. braindecode/models/base.py +50 -13
  12. braindecode/models/biot.py +10 -8
  13. braindecode/models/brainmodule.py +1 -13
  14. braindecode/models/codebrain.py +14 -19
  15. braindecode/models/eegpt.py +1 -1
  16. braindecode/models/eegtcnet.py +31 -4
  17. braindecode/models/emg2qwerty.py +8 -2
  18. braindecode/models/fnirs4d.py +761 -0
  19. braindecode/models/fnirs_cnn1d.py +339 -0
  20. braindecode/models/fnirs_t.py +785 -0
  21. braindecode/models/fnirsnet.py +268 -86
  22. braindecode/models/geonirs.py +1545 -0
  23. braindecode/models/guetschel2026.py +1 -1
  24. braindecode/models/jung_mae.py +596 -0
  25. braindecode/models/luna.py +43 -33
  26. braindecode/models/mapa.py +4 -5
  27. braindecode/models/model.html.jinja +24 -9
  28. braindecode/models/msvtnet.py +1 -2
  29. braindecode/models/mtrenirs.py +1053 -0
  30. braindecode/models/patchedtransformer.py +26 -15
  31. braindecode/models/reve.py +1 -4
  32. braindecode/models/signal_jepa.py +5 -6
  33. braindecode/models/sleepfm.py +98 -23
  34. braindecode/models/summary.csv +7 -0
  35. braindecode/models/util.py +139 -1
  36. braindecode/models/zuna.py +11 -24
  37. braindecode/modules/attention.py +9 -8
  38. braindecode/modules/channels.py +170 -30
  39. braindecode/modules/layers.py +2 -8
  40. braindecode/preprocessing/preprocess.py +4 -0
  41. braindecode/preprocessing/windowers.py +14 -6
  42. braindecode/util.py +21 -28
  43. braindecode/version.py +1 -1
  44. {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/METADATA +25 -9
  45. {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/RECORD +49 -42
  46. {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/licenses/NOTICE.txt +6 -0
  47. {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/WHEEL +0 -0
  48. {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/licenses/LICENSE.txt +0 -0
  49. {braindecode-2.1.0.dev181714115.dist-info → braindecode-2.1.0.dev182154342.dist-info}/top_level.txt +0 -0
@@ -22,88 +22,171 @@ class FNIRSNet(EEGModuleMixin, nn.Module, license="apache-2.0"):
22
22
 
23
23
  :bdg-success:`Convolution`
24
24
 
25
- .. versionadded:: 2.1
26
-
27
25
  .. figure:: https://braindecode.org/dev/_static/model/fnirsnet.png
28
26
  :align: center
29
27
  :alt: fNIRSNet architecture
30
28
 
31
29
  Fig. 2 of Wang et al. (2023), cropped
32
30
  (`CC BY 4.0 <https://creativecommons.org/licenses/by/4.0/>`_): "(a)
33
- Overview architecture of fNIRSNet. (b) Schema of receptive fields.
34
- [...] (c) Depthwise separable convolution."
35
-
36
- From the paper :footcite:`wang2023fnirsnet`: "fNIRSNet consists of a
37
- delayed hemodynamic response module (DHR Module) and a global module.
38
- [...] Delayed hemodynamic response convolutions (DHRConv) extract the
39
- channel-level features of delayed hemodynamic responses. Depthwise
40
- separable convolutions consisting of depthwise convolutions (DWConv) and
41
- pointwise convolutions (PWConv) are used to reduce model parameters."
42
-
43
- The input is the paper's fNIRS tensor of :math:`C` rows (``n_chans``,
44
- "twice (two chromophores: HbO and HbR) the number of fNIRS channels") by
45
- :math:`S` sampling points (``n_times``). As in Fig. 2(a) and the authors'
46
- loaders, the HbO rows come first, then the HbR rows; ``chs_info`` is not
47
- read, so keep the row order used in training. The DHRConv kernel spans the
48
- window, so the model has no sampling-rate argument (the paper: 3 s at
49
- 10 Hz, :math:`S = 30`, and at 13.3 Hz, :math:`S = 40`).
50
-
51
- Modules keep the authors' names: ``conv1`` (DHRConv, :math:`1 \times S`),
52
- ``bn1``, ``conv2.depth_conv`` (DWConv, :math:`C \times 1`, one filter per
53
- DHRConv map), ``conv2.point_conv`` (PWConv, :math:`F_1 \to F_2`), ``bn2``,
54
- sigmoid after each BN, and ``final_layer`` (FC). ``mapping`` renames their
55
- ``fc.*``, so an authors' ``state_dict`` loads with ``strict=True``; no
56
- weights are released. As in their code, the output is logits.
57
-
58
- The paper's two sizes (Section III-D), with the parameter counts of its
59
- Table III (this module gives the same counts):
60
-
61
- =================== ======= ====== ====== ====== ====== ==========
62
- Protocol Dataset C S F1 F2 Parameters
63
- =================== ======= ====== ====== ====== ====== ==========
64
- Subject-specific MA 72 30 4 8 498
65
- Subject-specific UFFT 40 40 4 8 419
66
- Subject-independent MA 72 30 16 32 2,370
67
- Subject-independent UFFT 40 40 16 32 2,051
68
- =================== ======= ====== ====== ====== ====== ==========
69
-
70
- The authors' released ``LOSO_Train.py`` uses :math:`F_1 = 8`,
71
- :math:`F_2 = 16`.
31
+ Overview architecture of fNIRSNet. (b) Schema of receptive fields. The
32
+ green and yellow feature maps are the output of DHRConv and DWConv,
33
+ respectively. [...] (c) Depthwise separable convolution."
34
+
35
+ Changes of oxygenated and deoxygenated hemoglobin (HbO, HbR) are "a slow
36
+ metabolic process manifested as delayed hemodynamic responses", and the
37
+ paper :footcite:`wang2023fnirsnet` argues that deep networks for fNIRS
38
+ ignore them: "A small kernel with a limited receptive field is
39
+ challenging to extract the features of delayed hemodynamic responses
40
+ because there is no significant change in HbO and HbR in small
41
+ neighborhoods. However, stacking more convolutional layers to obtain
42
+ larger receptive fields may cause overfitting on limited fNIRS data"
43
+ (Section I).
44
+
45
+ fNIRSNet answers with "two core ideas: 1) delayed hemodynamic responses
46
+ as domain knowledge should be introduced into fNIRS classification
47
+ models; 2) a simple and efficient model is beneficial to practical
48
+ applications on limited fNIRS data". It has "three convolutional layers
49
+ and one fully connected (FC) layer without pooling, dropout, and other
50
+ complicated structures": a convolution whose kernel spans the whole
51
+ window of one row, then one whose kernel spans all rows. With 4 and 8
52
+ filters it has 498 parameters on mental arithmetic (Table III).
53
+
54
+ .. rubric:: Architecture Overview
55
+
56
+ "fNIRSNet consists of a delayed hemodynamic response module (DHR Module)
57
+ and a global module" (Section II-B, Table I). With :math:`C` =
58
+ ``n_chans`` rows, :math:`S` = ``n_times`` samples, :math:`F_1` and
59
+ :math:`F_2` filters, and :math:`S' = S - k + 1` (1 for the paper's
60
+ kernel width :math:`k = S`)::
61
+
62
+ input (batch, C, S)
63
+ to_fnirs_tensor (batch, 1, C, S)
64
+ DHR Module: conv1 (1 x k), bn1, sigmoid (batch, F_1, C, S')
65
+ Global Module:
66
+ conv2.depth_conv (C x 1) (batch, F_1, 1, S')
67
+ conv2.point_conv (1 x 1), bn2, sigmoid (batch, F_2, 1, S')
68
+ flatten, final_layer (FC) (batch, n_outputs)
69
+
70
+ .. rubric:: Macro Components
71
+
72
+ - ``conv1``, ``bn1`` **DHR Module.** "Delayed hemodynamic response
73
+ convolutions (DHRConv) extract the channel-level features of delayed
74
+ hemodynamic responses." DHRConv is a standard convolution with
75
+ :math:`F_1` filters of :math:`1 \times S`: "the width of this kernel
76
+ equals the number of input sampling points" (Guideline 1). It stays a
77
+ standard convolution because "the depthwise separable convolution
78
+ performs poorly in low-dimensional space (the first layer)"
79
+ (Guideline 2). Batch normalization and a sigmoid follow.
80
+ - ``conv2``, ``bn2`` **Global Module.** A depthwise separable
81
+ convolution: DWConv, one :math:`C \times 1` filter per DHRConv map,
82
+ "can directly obtain global receptive fields without stacking layers",
83
+ and "the :math:`1 \times 1` PWConv projects the output of DWConv into
84
+ a new channel space" with :math:`F_2` filters; then batch
85
+ normalization and a sigmoid. Guideline 2 motivates the factorization
86
+ by the cost of a standard convolution against a depthwise separable
87
+ one, for a :math:`K_h \times K_w` kernel, :math:`F_{in}` input and
88
+ :math:`F_{out}` output channels and an :math:`M_h \times M_w` map
89
+ (Eqs. (2) and (3)):
90
+
91
+ .. math::
92
+
93
+ K_h K_w F_{in} F_{out} M_h M_w
94
+ \quad \text{vs.} \quad
95
+ K_h K_w F_{in} M_h M_w + F_{in} F_{out} M_h M_w ,
96
+
97
+ so the global module costs :math:`F_1 (C + F_2)` instead of
98
+ :math:`F_1 C F_2`, and "increasing the length of input signals only
99
+ increases the computational cost of DHRConv".
100
+ - ``activation`` **Saturating activations.** Guideline 3: "Activation
101
+ functions with saturated negative values can alleviate information
102
+ loss in the first layer"; sigmoid, tanh and ELU beat ReLU and leaky
103
+ ReLU in the ablation of Table VI, and the paper uses the sigmoid.
104
+ - ``final_layer`` **Classifier.** "The feature maps are flattened to 1D
105
+ vectors and then fed into an FC layer", without dropout; the paper's
106
+ softmax is left to the loss, and the module returns logits.
107
+
108
+ .. rubric:: Temporal, Spatial, and Spectral Encoding
109
+
110
+ - *Temporal:* one 3 s window of :math:`S = f \times T` samples (30 at
111
+ 10 Hz on MA, 40 at 13.3 Hz on UFFT). DHRConv covers all of it, because
112
+ the response it targets is long: the paper models it with the
113
+ canonical hemodynamic response function of three gamma functions
114
+ (Section II-A, Eq. (1)), whose :math:`A`, :math:`\alpha` and
115
+ :math:`\beta` "control the height and direction, shape, and scale of
116
+ hemodynamic responses":
117
+
118
+ .. math::
119
+
120
+ h(t) = \sum_{i=1}^{3} A_i \frac{t^{\alpha_i - 1}
121
+ \beta_i^{\alpha_i} e^{-\beta_i t}}{\Gamma(\alpha_i)} .
122
+
123
+ The kernel counts samples, so the model takes no sampling rate.
124
+ - *Spatial:* no montage or optode geometry. DWConv mixes all rows at
125
+ once, since "DHRConv alone cannot aggregate spatial information from
126
+ multi-channel fNIRS". ``chs_info`` is not read: the row order must be
127
+ the one used in training.
128
+ - *Chromophores:* :math:`C` "is twice (two chromophores: HbO and HbR) the
129
+ number of fNIRS channels" (Section II-B); as in Fig. 2(a) and the
130
+ authors' loaders, all HbO rows come first, then all HbR rows.
131
+ - *Spectral:* none in the model; the paper band-passes the
132
+ concentration changes to 0.01-0.1 Hz first (Section III-B).
133
+
134
+ .. rubric:: Pretrained Weights
135
+
136
+ None: the authors release code, not weights, and the paper trains one
137
+ model per subject or per left-out subject.
138
+
139
+ .. rubric:: Differences from the reference implementation
140
+
141
+ ``x`` is ``(batch, n_chans, n_times)``; ``to_fnirs_tensor`` adds the
142
+ depth axis of the authors' ``(batch, 1, C, S)`` input. The modules keep
143
+ the authors' names except ``fc``, now ``final_layer``; ``mapping``
144
+ renames ``fc.*``, so their ``state_dict`` loads with ``strict=True``.
145
+ Table I lists :math:`F_2` filters for DWConv, but the authors'
146
+ ``DWSConv`` and the cost :math:`F_1 (C + F_2)` above have :math:`F_1`
147
+ depthwise filters and an :math:`F_1 \to F_2` PWConv; this module
148
+ follows the code, which gives Table III's parameter counts. Two
149
+ additions: ``dhr_kernel_length`` may be shorter than the window (the
150
+ authors' FC layer only fits :math:`k = S`), and ``activation`` replaces
151
+ the fixed sigmoid. A training batch of one sample runs the BN layers on
152
+ their running statistics, and ``ch_mask`` raises a ``ValueError``.
72
153
 
73
154
  Parameters
74
155
  ----------
75
156
  n_dhr_filters : int, default=4
76
- DHRConv filters, :math:`F_1` (``num_DHRConv``). The paper's
77
- subject-specific value.
157
+ :math:`F_1`, the DHRConv filters (the authors' ``num_DHRConv``): 4
158
+ subject-specific, 16 subject-independent (Section III-D; the
159
+ authors' ``LOSO_Train.py`` uses 8). "Except for the number of
160
+ filters :math:`F_1` and :math:`F_2`, fNIRSNet has almost no other
161
+ hyperparameters."
78
162
  n_pw_filters : int, default=8
79
- PWConv filters, the width of the global module, :math:`F_2`
80
- (``num_DWConv`` in the authors' code). The paper's subject-specific
81
- value.
163
+ :math:`F_2`, the PWConv filters (the authors' ``num_DWConv``): 8
164
+ subject-specific, 32 subject-independent (``LOSO_Train.py``: 16).
165
+ The paper recommends "setting the value of :math:`F_2` to at least
166
+ twice that of :math:`F_1`" (Section IV-F).
82
167
  dhr_kernel_length : int or None, default=None
83
- DHRConv width :math:`k` (``DHRConv_width``), ``1 <= k <= S``. ``None``
84
- uses :math:`S`, the paper's Guideline 1. A shorter kernel, as in the
85
- paper's Table IV (:math:`k` = 10, 20, 30 on UFFT), gives
86
- :math:`F_2 (S - k + 1)` features to the FC layer.
168
+ DHRConv width :math:`k`, ``1 <= k <= n_times``; ``None`` uses
169
+ :math:`S` (Guideline 1). Table IV also tries :math:`k` = 10, 20 and
170
+ 30 on UFFT; the FC layer then reads :math:`F_2 (S - k + 1)` values.
87
171
  activation : type[nn.Module], default=nn.Sigmoid
88
- Activation after each BN (``act``). Guideline 3: activations "with
89
- saturated negative values" (sigmoid, tanh, ELU) work better.
172
+ Activation after each BN (the authors' ``act``).
90
173
 
91
174
  Notes
92
175
  -----
93
- Protocol (paper Section III; details from the authors' code): MA
176
+ Protocol (Section III, details from the authors' code): MA
94
177
  :footcite:`shin2017openaccess` (2 classes, 29 subjects, 10 Hz) and UFFT
95
- :footcite:`bak2019ufft` (3 classes, 30 subjects, 13.3 Hz); band-pass
96
- 0.01-0.1 Hz (third-order Butterworth, zero-phase), baseline correction,
97
- 3 s windows with a 1 s step, each window z-scored. Subject-specific:
98
- 5-fold CV over contiguous trial blocks, AdamW (lr 0.001), label smoothing
99
- 0.1, batch 64, 120 epochs, lr / 10 at epochs 60 and 90.
100
- Subject-independent: leave-one-subject-out, cosine lr over 30 epochs. Test
101
- metrics of the last epoch, averaged over folds and subjects.
102
-
103
- Replication on UFFT, accuracy / macro-F1 in %, the authors' training loops
104
- around this port and around their ``fNIRSNet`` (seeds 0-2). The LOSO runs
105
- use :math:`F_1 = 8`, :math:`F_2 = 16`, as the authors' ``LOSO_Train.py``;
106
- the paper's subject-independent row uses 16 and 32:
178
+ :footcite:`bak2019ufft` (3 classes, 30 subjects, 13.3 Hz), band-passed
179
+ 0.01-0.1 Hz, baseline-corrected, cut into 3 s windows with a 1 s step
180
+ and z-scored. Subject-specific runs use 5-fold CV over trial blocks for
181
+ 120 epochs, subject-independent runs leave one subject out for 30
182
+ epochs; AdamW (lr 0.001), label smoothing 0.1, last-epoch test metrics.
183
+ Table III gives 498 and 419 parameters for the subject-specific sizes
184
+ (MA :math:`C = 72, S = 30`; UFFT :math:`C = S = 40`) and 2,370 and 2,051
185
+ for the subject-independent ones; this module gives the same counts.
186
+
187
+ On UFFT, in the authors' training loops (seeds 0-2), the port and the
188
+ authors' ``fNIRSNet`` agree within 0.01 point (accuracy / macro-F1 in %;
189
+ the LOSO runs use the authors' :math:`F_1 = 8`, :math:`F_2 = 16`):
107
190
 
108
191
  =================== =============== ============= =============
109
192
  UFFT Paper, Table II This port Authors' code
@@ -112,6 +195,8 @@ class FNIRSNet(EEGModuleMixin, nn.Module, license="apache-2.0"):
112
195
  Subject-independent 64.43 / 63.57 64.52 / 63.67 64.51 / 63.67
113
196
  =================== =============== ============= =============
114
197
 
198
+ .. versionadded:: 2.1
199
+
115
200
  `License <https://github.com/wzhlearning/fNIRSNet/blob/11d9dad96308c65c039a0978b7eaf8a845065421/LICENSE>`_
116
201
 
117
202
  References
@@ -121,6 +206,7 @@ class FNIRSNet(EEGModuleMixin, nn.Module, license="apache-2.0"):
121
206
 
122
207
  def __init__(
123
208
  self,
209
+ # Braindecode parameters
124
210
  n_outputs: int | None = None,
125
211
  n_chans: int | None = None,
126
212
  chs_info: list[dict] | None = None,
@@ -128,36 +214,87 @@ class FNIRSNet(EEGModuleMixin, nn.Module, license="apache-2.0"):
128
214
  input_window_seconds: float | None = None,
129
215
  sfreq: float | None = None,
130
216
  *,
217
+ # Model-specific parameters
131
218
  n_dhr_filters: int = 4,
132
219
  n_pw_filters: int = 8,
133
220
  dhr_kernel_length: int | None = None,
134
221
  activation: type[nn.Module] = nn.Sigmoid,
135
222
  ) -> None:
136
223
  super().__init__(
137
- n_outputs, n_chans, chs_info, n_times, input_window_seconds, sfreq
224
+ n_outputs=n_outputs,
225
+ n_chans=n_chans,
226
+ chs_info=chs_info,
227
+ n_times=n_times,
228
+ input_window_seconds=input_window_seconds,
229
+ sfreq=sfreq,
138
230
  )
139
231
  del n_outputs, n_chans, chs_info, n_times, input_window_seconds, sfreq
232
+
233
+ # The authors' head is named ``fc``: their state_dict loads as is
234
+ self.mapping = {f"fc.{k}": f"final_layer.{k}" for k in ("weight", "bias")}
235
+
236
+ # Parameters
237
+ # Guideline 1: the DHRConv kernel is as wide as the window (k = S)
140
238
  kernel_length = self.n_times if dhr_kernel_length is None else dhr_kernel_length
239
+ # Samples left after DHRConv, S' = S - k + 1 (1 with the paper's k = S)
240
+ n_times_dhr = self.n_times - kernel_length + 1
241
+
242
+ # Checkers
243
+ # A kernel longer than the window has no valid position, and an empty
244
+ # one reads nothing
141
245
  if not 1 <= kernel_length <= self.n_times:
142
246
  raise ValueError(
143
247
  f"dhr_kernel_length must be in [1, n_times={self.n_times}], "
144
248
  f"got {dhr_kernel_length}."
145
249
  )
250
+
251
+ # Layers
252
+ # Following paper nomenclature (Section II-B, Table I)
253
+ # The authors' input has a depth axis: (batch, 1, C, S)
146
254
  self.to_fnirs_tensor = Rearrange("batch chans time -> batch 1 chans time")
147
- self.conv1 = nn.Conv2d(1, n_dhr_filters, (1, kernel_length))
255
+
256
+ # Delayed hemodynamic response module (DHR Module)
257
+ # DHRConv: F1 standard convolutions of 1 x k, so that one filter reads
258
+ # the whole slow response of one channel (Guidelines 1 and 2)
259
+ self.conv1 = nn.Conv2d(
260
+ in_channels=1,
261
+ out_channels=n_dhr_filters,
262
+ kernel_size=(1, kernel_length),
263
+ )
148
264
  self.bn1 = nn.BatchNorm2d(n_dhr_filters)
265
+
266
+ # Global module: a depthwise separable convolution
149
267
  self.conv2 = nn.Sequential(
150
268
  OrderedDict(
151
- depth_conv=DepthwiseConv2d(n_dhr_filters, 1, (self.n_chans, 1)),
152
- point_conv=nn.Conv2d(n_dhr_filters, n_pw_filters, 1),
269
+ # DWConv: one C x 1 filter per DHRConv map, a global receptive
270
+ # field over the channels without stacking layers
271
+ depth_conv=DepthwiseConv2d(
272
+ in_channels=n_dhr_filters,
273
+ depth_multiplier=1,
274
+ kernel_size=(self.n_chans, 1),
275
+ ),
276
+ # PWConv: 1 x 1, projects the F1 maps into F2 new ones
277
+ point_conv=nn.Conv2d(
278
+ in_channels=n_dhr_filters,
279
+ out_channels=n_pw_filters,
280
+ kernel_size=1,
281
+ ),
153
282
  )
154
283
  )
155
284
  self.bn2 = nn.BatchNorm2d(n_pw_filters)
285
+
286
+ # Guideline 3: an activation that saturates for negative inputs
287
+ # (sigmoid in the paper), used after both batch normalizations
156
288
  self.activation = activation()
289
+
290
+ # Flatten layer
157
291
  self.flatten = Rearrange("batch filters 1 time -> batch (filters time)")
158
- n_features = n_pw_filters * (self.n_times - kernel_length + 1)
159
- self.final_layer = nn.Linear(n_features, self.n_outputs)
160
- self.mapping = {f"fc.{k}": f"final_layer.{k}" for k in ("weight", "bias")}
292
+
293
+ # Final fully connected layer, without pooling or dropout
294
+ self.final_layer = nn.Linear(
295
+ in_features=n_pw_filters * n_times_dhr,
296
+ out_features=self.n_outputs,
297
+ )
161
298
 
162
299
  def reset_head(self, n_outputs: int) -> None:
163
300
  self._set_n_outputs(n_outputs)
@@ -170,23 +307,68 @@ class FNIRSNet(EEGModuleMixin, nn.Module, license="apache-2.0"):
170
307
  return_features: bool = False,
171
308
  ch_mask: torch.Tensor | None = None,
172
309
  ) -> torch.Tensor | dict[str, torch.Tensor | None]:
173
- """Logits ``(batch, n_outputs)`` of ``x`` ``(batch, n_chans, n_times)``.
310
+ """Forward pass of the fNIRSNet model.
174
311
 
175
- ``return_features=True`` gives ``{"features", "cls_token": None}``; a
176
- ``ch_mask`` raises a ``ValueError`` (DWConv spans all channels).
312
+ Parameters
313
+ ----------
314
+ x : torch.Tensor
315
+ Input tensor with shape ``(batch_size, n_chans, n_times)``.
316
+ return_features : bool, default=False
317
+ If True, return the flattened features that feed the FC layer.
318
+ ch_mask : torch.Tensor or None
319
+ Not supported: DWConv has one weight per channel.
320
+
321
+ Returns
322
+ -------
323
+ torch.Tensor or dict
324
+ Logits with shape ``(batch_size, n_outputs)``, or with
325
+ ``return_features=True`` the dict ``{"features", "cls_token"}``,
326
+ ``features`` of shape ``(batch_size, n_pw_filters * time')`` and
327
+ ``cls_token`` None.
177
328
  """
329
+ # DWConv has one weight per channel: a subset of the channels is
330
+ # another model
178
331
  if ch_mask is not None:
179
332
  raise ValueError("FNIRSNet does not accept ch_mask: DWConv spans n_chans.")
180
- # time' = n_times - dhr_kernel_length + 1 (1 with the default kernel)
181
- x = self.to_fnirs_tensor(x) # (batch, 1, n_chans, n_times)
182
- x = self.conv1(x) # DHRConv: (batch, n_dhr_filters, n_chans, time')
183
- x = self.bn1(x) # (batch, n_dhr_filters, n_chans, time')
184
- x = self.activation(x) # (batch, n_dhr_filters, n_chans, time')
185
- x = self.conv2.depth_conv(x) # DWConv: (batch, n_dhr_filters, 1, time')
186
- x = self.conv2.point_conv(x) # PWConv: (batch, n_pw_filters, 1, time')
187
- x = self.bn2(x) # (batch, n_pw_filters, 1, time')
188
- x = self.activation(x) # (batch, n_pw_filters, 1, time')
189
- features = self.flatten(x) # (batch, n_pw_filters * time')
333
+
334
+ # Below, F1 = n_dhr_filters, F2 = n_pw_filters, C = n_chans, S = n_times
335
+ # and S' = S - dhr_kernel_length + 1 (1 with the paper's kernel)
336
+
337
+ # Depth axis of the authors' input
338
+ # (batch, C, S) -> (batch, 1, C, S)
339
+ x = self.to_fnirs_tensor(x)
340
+
341
+ # DHR Module. Delayed hemodynamic response convolution (DHRConv,
342
+ # Guideline 1): each of the F1 filters reads the whole window of one
343
+ # channel, the channel-level feature of its slow response
344
+ # (batch, 1, C, S) -> (batch, F1, C, S')
345
+ x = self.conv1(x)
346
+ # Batch normalization of the F1 maps; shape unchanged
347
+ x = self.bn1(x)
348
+ # Saturating activation (Guideline 3: no information lost in the
349
+ # first layer for negative inputs); shape unchanged
350
+ x = self.activation(x)
351
+
352
+ # Global Module. DWConv: one C x 1 filter per DHRConv map aggregates
353
+ # all channels at once (global receptive field in space)
354
+ # (batch, F1, C, S') -> (batch, F1, 1, S')
355
+ x = self.conv2.depth_conv(x)
356
+ # PWConv: 1 x 1 projection of the F1 maps into F2 new ones
357
+ # (batch, F1, 1, S') -> (batch, F2, 1, S')
358
+ x = self.conv2.point_conv(x)
359
+ # Batch normalization of the F2 maps; shape unchanged
360
+ x = self.bn2(x)
361
+ # Same saturating activation as after DHRConv; shape unchanged
362
+ x = self.activation(x)
363
+
364
+ # "The feature maps are flattened to 1D vectors"
365
+ # (batch, F2, 1, S') -> (batch, F2 * S')
366
+ features = self.flatten(x)
367
+
190
368
  if return_features:
191
369
  return {"features": features, "cls_token": None}
192
- return self.final_layer(features) # (batch, n_outputs)
370
+
371
+ # FC layer; the paper's softmax is left to the loss
372
+ # (batch, F2 * S') -> (batch, n_outputs)
373
+ x = self.final_layer(features)
374
+ return x