Skip to content

Source SMOTE

neureptrace.decoding.source_smote implements same-class source-row interpolation for feature matrices.

This is Category 1. Synthetic rows are convex combinations of source rows from the same class.

neureptrace.decoding.source_smote

Strict source-only SMOTE-style interpolation.

This module creates same-class interpolated source feature rows. It is intended as a dependency-light domain-generalization baseline for M/EEG feature matrices. Synthetic rows keep the sampled source class label and are generated only from source rows, so the protocol is strict source-only.

SourceSmoteConfig dataclass

Configuration for source-only same-class interpolation.

Source code in src/neureptrace/decoding/source_smote.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
@dataclass(frozen=True, slots=True)
class SourceSmoteConfig:
    """Configuration for source-only same-class interpolation."""

    synthetic_per_class: int | str = 0
    cross_domain_partner: bool | int | str = True
    preserve_original: bool | int | str = True
    random_state: Any = 13
    jitter_std: float | str = 0.0

    def __post_init__(self) -> None:
        """Normalize and validate direct dataclass construction."""

        object.__setattr__(self, "synthetic_per_class", _nonnegative_int(self.synthetic_per_class, name="synthetic_per_class"))
        object.__setattr__(self, "cross_domain_partner", _bool_value(self.cross_domain_partner, name="cross_domain_partner"))
        object.__setattr__(self, "preserve_original", _bool_value(self.preserve_original, name="preserve_original"))
        object.__setattr__(self, "random_state", _normalize_optional_random_state(self.random_state, name="random_state"))
        object.__setattr__(self, "jitter_std", _nonnegative_float(self.jitter_std, name="jitter_std"))

    @property
    def enabled(self) -> bool:
        """Whether this config requests synthetic rows."""

        return self.synthetic_per_class > 0

enabled property

Whether this config requests synthetic rows.

__post_init__()

Normalize and validate direct dataclass construction.

Source code in src/neureptrace/decoding/source_smote.py
35
36
37
38
39
40
41
42
def __post_init__(self) -> None:
    """Normalize and validate direct dataclass construction."""

    object.__setattr__(self, "synthetic_per_class", _nonnegative_int(self.synthetic_per_class, name="synthetic_per_class"))
    object.__setattr__(self, "cross_domain_partner", _bool_value(self.cross_domain_partner, name="cross_domain_partner"))
    object.__setattr__(self, "preserve_original", _bool_value(self.preserve_original, name="preserve_original"))
    object.__setattr__(self, "random_state", _normalize_optional_random_state(self.random_state, name="random_state"))
    object.__setattr__(self, "jitter_std", _nonnegative_float(self.jitter_std, name="jitter_std"))

SourceSmoteResult dataclass

Augmented source rows and interpolation provenance.

Source code in src/neureptrace/decoding/source_smote.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
@dataclass(frozen=True, slots=True)
class SourceSmoteResult:
    """Augmented source rows and interpolation provenance."""

    features: np.ndarray
    labels: np.ndarray
    synthetic_mask: np.ndarray
    content_indices: np.ndarray
    partner_indices: np.ndarray
    lambdas: np.ndarray
    metadata: dict[str, Any] = field(default_factory=dict)

    @property
    def n_synthetic(self) -> int:
        """Number of generated rows in the returned matrix."""

        return int(np.sum(self.synthetic_mask))

n_synthetic property

Number of generated rows in the returned matrix.

augment_source_with_smote(source_features, source_labels, *, source_domains=None, config=None)

Append same-class source interpolation rows.

Parameters:

Name Type Description Default
source_features Sequence[Sequence[float]] | ndarray

Source feature matrix.

required
source_labels Iterable[Any] | ndarray

One source label per row. Synthetic rows inherit the sampled class label.

required
source_domains Iterable[Hashable] | ndarray | None

Optional source-domain identifiers. When cross_domain_partner=True, interpolation partners are drawn from another source domain when possible.

None
config SourceSmoteConfig | Mapping[str, Any] | None

SMOTE options. Mappings are normalized through :func:source_smote_config.

None
Source code in src/neureptrace/decoding/source_smote.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def augment_source_with_smote(
    source_features: Sequence[Sequence[float]] | np.ndarray,
    source_labels: Iterable[Any] | np.ndarray,
    *,
    source_domains: Iterable[Hashable] | np.ndarray | None = None,
    config: SourceSmoteConfig | Mapping[str, Any] | None = None,
) -> SourceSmoteResult:
    """Append same-class source interpolation rows.

    Parameters
    ----------
    source_features:
        Source feature matrix.
    source_labels:
        One source label per row.  Synthetic rows inherit the sampled class label.
    source_domains:
        Optional source-domain identifiers.  When ``cross_domain_partner=True``,
        interpolation partners are drawn from another source domain when possible.
    config:
        SMOTE options.  Mappings are normalized through :func:`source_smote_config`.
    """

    cfg = source_smote_config() if config is None else _coerce_config(config)
    features = _feature_matrix(source_features, name="source_features")
    labels = _label_vector(source_labels, expected_length=features.shape[0], name="source_labels")
    domains = _domain_vector(source_domains, expected_length=features.shape[0])
    classes, _class_counts = label_counts(labels)
    domain_ids, _domain_counts = label_counts(domains)

    if not cfg.enabled:
        metadata = _metadata(
            cfg,
            n_source_rows=features.shape[0],
            n_synthetic_rows=0,
            n_classes=classes.shape[0],
            n_source_domains=domain_ids.shape[0],
            feature_dim=features.shape[1],
        )
        return SourceSmoteResult(
            features=features.astype(np.float32, copy=False),
            labels=labels.copy(),
            synthetic_mask=np.zeros(features.shape[0], dtype=bool),
            content_indices=np.empty(0, dtype=int),
            partner_indices=np.empty(0, dtype=int),
            lambdas=np.empty(0, dtype=float),
            metadata=metadata,
        )

    rng = np.random.default_rng(cfg.random_state)
    synthetic_rows: list[np.ndarray] = []
    synthetic_labels: list[Any] = []
    content_indices: list[int] = []
    partner_indices: list[int] = []
    lambdas: list[float] = []

    for class_label in classes.tolist():
        class_indices = np.flatnonzero(label_equal_mask(labels, class_label))
        if class_indices.size == 0:
            continue
        for _ in range(cfg.synthetic_per_class):
            content_index = int(rng.choice(class_indices))
            partner_pool = class_indices[class_indices != content_index] if class_indices.size > 1 else class_indices
            if cfg.cross_domain_partner and partner_pool.size > 0:
                same_domain_mask = label_equal_mask(domains[partner_pool], domains[content_index])
                cross_pool = partner_pool[~same_domain_mask]
                if cross_pool.size:
                    partner_pool = cross_pool
            if partner_pool.size == 0:
                partner_pool = np.asarray([content_index], dtype=int)
            partner_index = int(rng.choice(partner_pool))
            lam = float(rng.random())
            row = interpolate_rows(features[content_index], features[partner_index], lam)
            if cfg.jitter_std > 0.0:
                row = row + rng.normal(0.0, cfg.jitter_std, size=row.shape[0])
            synthetic_rows.append(row)
            synthetic_labels.append(class_label)
            content_indices.append(content_index)
            partner_indices.append(partner_index)
            lambdas.append(lam)

    synthetic_features = np.vstack(synthetic_rows).astype(np.float32, copy=False) if synthetic_rows else np.empty((0, features.shape[1]), dtype=np.float32)
    synthetic_label_array = _object_value_vector(synthetic_labels)
    if cfg.preserve_original:
        output_features = np.vstack([features, synthetic_features]).astype(np.float32, copy=False)
        output_labels = np.concatenate([labels, synthetic_label_array])
        synthetic_mask = np.concatenate([np.zeros(features.shape[0], dtype=bool), np.ones(synthetic_features.shape[0], dtype=bool)])
    else:
        output_features = synthetic_features
        output_labels = synthetic_label_array
        synthetic_mask = np.ones(synthetic_features.shape[0], dtype=bool)

    metadata = _metadata(
        cfg,
        n_source_rows=features.shape[0],
        n_synthetic_rows=synthetic_features.shape[0],
        n_classes=classes.shape[0],
        n_source_domains=domain_ids.shape[0],
        feature_dim=features.shape[1],
    )
    return SourceSmoteResult(
        features=output_features,
        labels=output_labels,
        synthetic_mask=synthetic_mask,
        content_indices=np.asarray(content_indices, dtype=int),
        partner_indices=np.asarray(partner_indices, dtype=int),
        lambdas=np.asarray(lambdas, dtype=float),
        metadata=metadata,
    )

interpolate_rows(content_row, partner_row, lam)

Return a convex interpolation of two feature rows.

Source code in src/neureptrace/decoding/source_smote.py
181
182
183
184
185
186
187
188
189
def interpolate_rows(content_row: Sequence[float] | np.ndarray, partner_row: Sequence[float] | np.ndarray, lam: float | str) -> np.ndarray:
    """Return a convex interpolation of two feature rows."""

    left = np.asarray(content_row, dtype=float).reshape(-1)
    right = np.asarray(partner_row, dtype=float).reshape(-1)
    if left.shape != right.shape or left.size == 0:
        raise ValueError("content_row and partner_row must be non-empty vectors with the same shape.")
    weight = _unit_interval_float(lam, name="lam")
    return (left + weight * (right - left)).astype(np.float32, copy=False)

source_smote_config(*, synthetic_per_class=0, cross_domain_partner=True, preserve_original=True, random_state=13, jitter_std=0.0)

Normalize public source-SMOTE options.

Source code in src/neureptrace/decoding/source_smote.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def source_smote_config(
    *,
    synthetic_per_class: int | str = 0,
    cross_domain_partner: bool | int | str = True,
    preserve_original: bool | int | str = True,
    random_state: Any = 13,
    jitter_std: float | str = 0.0,
) -> SourceSmoteConfig:
    """Normalize public source-SMOTE options."""

    return SourceSmoteConfig(
        synthetic_per_class=_nonnegative_int(synthetic_per_class, name="synthetic_per_class"),
        cross_domain_partner=_bool_value(cross_domain_partner, name="cross_domain_partner"),
        preserve_original=_bool_value(preserve_original, name="preserve_original"),
        random_state=_normalize_optional_random_state(random_state, name="random_state"),
        jitter_std=_nonnegative_float(jitter_std, name="jitter_std"),
    )