Skip to content

oversampleqa.types

oversampleqa.types

Core protocol and type definitions for oversampleqa.

ReferenceSet = Literal['hidden_minority', 'train_minority'] module-attribute

Which minority set validation compares synthetic points against.

ValidationMode

Bases: Enum

Validation execution modes.

Source code in src/oversampleqa/types.py
56
57
58
59
60
61
62
class ValidationMode(Enum):
    """Validation execution modes."""

    STANDARD = "standard"
    MEMORY_EFFICIENT = "memory_efficient"
    PARALLEL = "parallel"
    ASYNC = "async"

DistanceMetricProtocol

Bases: Protocol

Protocol for distance metric callables.

Source code in src/oversampleqa/types.py
65
66
67
68
class DistanceMetricProtocol(Protocol):
    """Protocol for distance metric callables."""

    def __call__(self, x1: FloatArray, x2: FloatArray, **kwargs: Any) -> float: ...

OversamplerProtocol

Bases: Protocol

Protocol for oversampler-like objects.

Source code in src/oversampleqa/types.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
class OversamplerProtocol(Protocol):
    """Protocol for oversampler-like objects."""

    def fit_resample(self, X: FloatArray, y: IntArray) -> tuple[FloatArray, IntArray]:
        """Fit and resample the dataset, returning resampled arrays.

        Args:
            X: Feature matrix.
            y: Target labels.

        Returns:
            Tuple of resampled ``(X, y)`` arrays.
        """
        ...

    @property
    def random_state(self) -> int | None:
        """Return the random state, if supported.

        Returns:
            Random state value or ``None``.
        """
        ...

    @random_state.setter
    def random_state(self, value: int | None) -> None:
        """Set the random state, if supported.

        Args:
            value: Random state to set.
        """
        ...

random_state property writable

Return the random state, if supported.

Returns:

Type Description
int | None

Random state value or None.

fit_resample(X, y)

Fit and resample the dataset, returning resampled arrays.

Parameters:

Name Type Description Default
X FloatArray

Feature matrix.

required
y IntArray

Target labels.

required

Returns:

Type Description
tuple[FloatArray, IntArray]

Tuple of resampled (X, y) arrays.

Source code in src/oversampleqa/types.py
74
75
76
77
78
79
80
81
82
83
84
def fit_resample(self, X: FloatArray, y: IntArray) -> tuple[FloatArray, IntArray]:
    """Fit and resample the dataset, returning resampled arrays.

    Args:
        X: Feature matrix.
        y: Target labels.

    Returns:
        Tuple of resampled ``(X, y)`` arrays.
    """
    ...

ValidatorProtocol

Bases: Protocol

Protocol for validator implementations.

Source code in src/oversampleqa/types.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
class ValidatorProtocol(Protocol):
    """Protocol for validator implementations."""

    def validate(
        self,
        X: FloatArray,
        y: IntArray,
        minority_label: int,
        oversampler: OversamplerProtocol,
        **kwargs: Any,
    ) -> float:
        """Validate an oversampler and return an error rate.

        Args:
            X: Feature matrix.
            y: Target labels.
            minority_label: Minority class label.
            oversampler: Oversampler instance.
            **kwargs: Implementation-specific options.

        Returns:
            Error rate.
        """
        ...

validate(X, y, minority_label, oversampler, **kwargs)

Validate an oversampler and return an error rate.

Parameters:

Name Type Description Default
X FloatArray

Feature matrix.

required
y IntArray

Target labels.

required
minority_label int

Minority class label.

required
oversampler OversamplerProtocol

Oversampler instance.

required
**kwargs Any

Implementation-specific options.

{}

Returns:

Type Description
float

Error rate.

Source code in src/oversampleqa/types.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def validate(
    self,
    X: FloatArray,
    y: IntArray,
    minority_label: int,
    oversampler: OversamplerProtocol,
    **kwargs: Any,
) -> float:
    """Validate an oversampler and return an error rate.

    Args:
        X: Feature matrix.
        y: Target labels.
        minority_label: Minority class label.
        oversampler: Oversampler instance.
        **kwargs: Implementation-specific options.

    Returns:
        Error rate.
    """
    ...

ValidationConfig dataclass

Immutable validation configuration.

Source code in src/oversampleqa/types.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
@dataclass(frozen=True)
class ValidationConfig:
    """Immutable validation configuration."""

    hidden_ratio: float = 0.1
    metric: str = "hassanat"
    return_details: bool = False
    random_state: int | None = 42
    reference: ReferenceSet = "hidden_minority"
    n_repeats: int = 1

    def __post_init__(self) -> None:
        if not 0 < self.hidden_ratio < 1:
            raise ValueError("hidden_ratio must be between 0 and 1")

ValidationDetails dataclass

Detailed outcome of a single validation run.

Replaces the former (error_rate, n_errors, dist_hidden, dist_min) 4-tuple returned by return_details=True.

Attributes

error_rate: Fraction of synthetic points strictly closer to the hidden majority than to the minority reference set. nan when no synthetic samples were produced -- that is an absent measurement, not a perfect score. n_errors: Count behind error_rate. n_synthetic: Number of synthetic points scored. n_ties: Points exactly equidistant from both reference sets. Counted separately rather than scored as errors; a large value indicates duplicated or heavily quantised features. duplication_rate: Fraction of synthetic points coinciding with a reference point. A sampler that only duplicates scores 1.0, and its error rate carries no information about synthesis quality. reference: Which minority set the comparison used. dist_hidden, dist_min: Distance matrices from synthetic points to the hidden majority and to the minority reference set.

Source code in src/oversampleqa/types.py
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
@dataclass(frozen=True)
class ValidationDetails:
    """Detailed outcome of a single validation run.

    Replaces the former ``(error_rate, n_errors, dist_hidden, dist_min)``
    4-tuple returned by ``return_details=True``.

    Attributes
    ----------
    error_rate:
        Fraction of synthetic points strictly closer to the hidden majority
        than to the minority reference set. ``nan`` when no synthetic samples
        were produced -- that is an absent measurement, not a perfect score.
    n_errors:
        Count behind ``error_rate``.
    n_synthetic:
        Number of synthetic points scored.
    n_ties:
        Points exactly equidistant from both reference sets. Counted
        separately rather than scored as errors; a large value indicates
        duplicated or heavily quantised features.
    duplication_rate:
        Fraction of synthetic points coinciding with a reference point. A
        sampler that only duplicates scores 1.0, and its error rate carries
        no information about synthesis quality.
    reference:
        Which minority set the comparison used.
    dist_hidden, dist_min:
        Distance matrices from synthetic points to the hidden majority and to
        the minority reference set.
    """

    error_rate: float
    n_errors: int
    n_synthetic: int
    n_ties: int
    duplication_rate: float
    reference: ReferenceSet
    dist_hidden: FloatArray
    dist_min: FloatArray
    n_repeats: int = 1
    rates: tuple[float, ...] = ()
    mean: float = float("nan")
    std: float = float("nan")
    interval: tuple[float, float] | None = None

    @property
    def has_dispersion(self) -> bool:
        """Whether more than one hold-out split was drawn."""
        return self.n_repeats > 1

    def to_dict(self) -> dict[str, Any]:
        """Flat, JSON-safe mapping.

        ``dist_hidden`` and ``dist_min`` are deliberately excluded: they are
        working arrays of shape ``(n_synthetic, n_reference)``, often megabytes,
        and they are inputs to the summary rather than part of it. Callers that
        need them have the dataclass.
        """
        return {
            "error_rate": self.error_rate,
            "n_errors": self.n_errors,
            "n_synthetic": self.n_synthetic,
            "n_ties": self.n_ties,
            "duplication_rate": self.duplication_rate,
            "reference": self.reference,
            "n_repeats": self.n_repeats,
            "rates": list(self.rates),
            "mean": self.mean,
            "std": self.std,
            "interval": list(self.interval) if self.interval else None,
        }

has_dispersion property

Whether more than one hold-out split was drawn.

to_dict()

Flat, JSON-safe mapping.

dist_hidden and dist_min are deliberately excluded: they are working arrays of shape (n_synthetic, n_reference), often megabytes, and they are inputs to the summary rather than part of it. Callers that need them have the dataclass.

Source code in src/oversampleqa/types.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def to_dict(self) -> dict[str, Any]:
    """Flat, JSON-safe mapping.

    ``dist_hidden`` and ``dist_min`` are deliberately excluded: they are
    working arrays of shape ``(n_synthetic, n_reference)``, often megabytes,
    and they are inputs to the summary rather than part of it. Callers that
    need them have the dataclass.
    """
    return {
        "error_rate": self.error_rate,
        "n_errors": self.n_errors,
        "n_synthetic": self.n_synthetic,
        "n_ties": self.n_ties,
        "duplication_rate": self.duplication_rate,
        "reference": self.reference,
        "n_repeats": self.n_repeats,
        "rates": list(self.rates),
        "mean": self.mean,
        "std": self.std,
        "interval": list(self.interval) if self.interval else None,
    }

BenchmarkConfig dataclass

Configuration for benchmarking experiments.

Source code in src/oversampleqa/types.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
@dataclass(frozen=True)
class BenchmarkConfig:
    """Configuration for benchmarking experiments."""

    n_runs: int = 10
    hidden_ratios: list[float] = field(default_factory=lambda: [0.1, 0.25, 0.5])
    metrics: list[str] = field(default_factory=lambda: ["hassanat", "euclidean"])
    validation_mode: ValidationMode = ValidationMode.STANDARD
    n_jobs: int = 1

    def __post_init__(self) -> None:
        if self.n_runs <= 0:
            raise ValueError("n_runs must be positive")
        if any(ratio <= 0 or ratio >= 1 for ratio in self.hidden_ratios):
            raise ValueError("All hidden ratios must be in (0, 1)")

ValidationResult

Bases: TypedDict

Typed structure for validation result.

Source code in src/oversampleqa/types.py
238
239
240
241
242
243
244
245
class ValidationResult(TypedDict, total=False):
    """Typed structure for validation result."""

    error_rate: float
    n_errors: int
    n_synthetic: int
    confidence_interval: tuple[float, float]
    metadata: dict[str, Any]

BaseValidator

Bases: ABC, Generic[T]

Abstract base class for validators.

Source code in src/oversampleqa/types.py
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
class BaseValidator(ABC, Generic[T]):
    """Abstract base class for validators."""

    @abstractmethod
    def validate(
        self,
        X: FloatArray,
        y: IntArray,
        minority_label: int,
        oversampler: OversamplerProtocol,
        config: ValidationConfig,
    ) -> T:
        """Run validation and return a result.

        Args:
            X: Feature matrix.
            y: Target labels.
            minority_label: Minority class label.
            oversampler: Oversampler instance.
            config: ValidationConfig.

        Returns:
            Validation result.
        """
        ...

    @abstractmethod
    async def validate_async(
        self,
        X: FloatArray,
        y: IntArray,
        minority_label: int,
        oversampler: OversamplerProtocol,
        config: ValidationConfig,
    ) -> T:
        """Run validation asynchronously and return a result.

        Args:
            X: Feature matrix.
            y: Target labels.
            minority_label: Minority class label.
            oversampler: Oversampler instance.
            config: ValidationConfig.

        Returns:
            Validation result.
        """
        ...

validate(X, y, minority_label, oversampler, config) abstractmethod

Run validation and return a result.

Parameters:

Name Type Description Default
X FloatArray

Feature matrix.

required
y IntArray

Target labels.

required
minority_label int

Minority class label.

required
oversampler OversamplerProtocol

Oversampler instance.

required
config ValidationConfig

ValidationConfig.

required

Returns:

Type Description
T

Validation result.

Source code in src/oversampleqa/types.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
@abstractmethod
def validate(
    self,
    X: FloatArray,
    y: IntArray,
    minority_label: int,
    oversampler: OversamplerProtocol,
    config: ValidationConfig,
) -> T:
    """Run validation and return a result.

    Args:
        X: Feature matrix.
        y: Target labels.
        minority_label: Minority class label.
        oversampler: Oversampler instance.
        config: ValidationConfig.

    Returns:
        Validation result.
    """
    ...

validate_async(X, y, minority_label, oversampler, config) abstractmethod async

Run validation asynchronously and return a result.

Parameters:

Name Type Description Default
X FloatArray

Feature matrix.

required
y IntArray

Target labels.

required
minority_label int

Minority class label.

required
oversampler OversamplerProtocol

Oversampler instance.

required
config ValidationConfig

ValidationConfig.

required

Returns:

Type Description
T

Validation result.

Source code in src/oversampleqa/types.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
@abstractmethod
async def validate_async(
    self,
    X: FloatArray,
    y: IntArray,
    minority_label: int,
    oversampler: OversamplerProtocol,
    config: ValidationConfig,
) -> T:
    """Run validation asynchronously and return a result.

    Args:
        X: Feature matrix.
        y: Target labels.
        minority_label: Minority class label.
        oversampler: Oversampler instance.
        config: ValidationConfig.

    Returns:
        Validation result.
    """
    ...

Dataset

Bases: ABC

Abstract dataset definition.

Source code in src/oversampleqa/types.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
class Dataset(ABC):
    """Abstract dataset definition."""

    @property
    @abstractmethod
    def X(self) -> FloatArray:
        """Return feature matrix.

        Returns:
            Feature matrix.
        """
        ...

    @property
    @abstractmethod
    def y(self) -> IntArray:
        """Return target labels.

        Returns:
            Target labels.
        """
        ...

    @property
    @abstractmethod
    def name(self) -> str:
        """Return dataset name.

        Returns:
            Dataset name.
        """
        ...

    @property
    @abstractmethod
    def minority_label(self) -> int:
        """Return the minority class label.

        Returns:
            Minority class label.
        """
        ...

X abstractmethod property

Return feature matrix.

Returns:

Type Description
FloatArray

Feature matrix.

y abstractmethod property

Return target labels.

Returns:

Type Description
IntArray

Target labels.

name abstractmethod property

Return dataset name.

Returns:

Type Description
str

Dataset name.

minority_label abstractmethod property

Return the minority class label.

Returns:

Type Description
int

Minority class label.

ValidatorFactory

Bases: Protocol

Factory for validators.

Source code in src/oversampleqa/types.py
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
class ValidatorFactory(Protocol):
    """Factory for validators."""

    def create_validator(
        self, mode: ValidationMode, **kwargs: Any
    ) -> BaseValidator[Any]:
        """Create a validator instance for the given mode.

        Args:
            mode: Validation execution mode.
            **kwargs: Implementation-specific options.

        Returns:
            Validator instance.
        """
        ...

create_validator(mode, **kwargs)

Create a validator instance for the given mode.

Parameters:

Name Type Description Default
mode ValidationMode

Validation execution mode.

required
**kwargs Any

Implementation-specific options.

{}

Returns:

Type Description
BaseValidator[Any]

Validator instance.

Source code in src/oversampleqa/types.py
350
351
352
353
354
355
356
357
358
359
360
361
362
def create_validator(
    self, mode: ValidationMode, **kwargs: Any
) -> BaseValidator[Any]:
    """Create a validator instance for the given mode.

    Args:
        mode: Validation execution mode.
        **kwargs: Implementation-specific options.

    Returns:
        Validator instance.
    """
    ...

MetricFactory

Bases: Protocol

Factory for distance metrics.

Source code in src/oversampleqa/types.py
365
366
367
368
369
370
371
372
373
374
375
376
377
378
class MetricFactory(Protocol):
    """Factory for distance metrics."""

    def create_metric(self, name: str, **kwargs: Any) -> DistanceMetricProtocol:
        """Create a distance metric by name.

        Args:
            name: Metric identifier.
            **kwargs: Metric-specific parameters.

        Returns:
            Distance metric callable.
        """
        ...

create_metric(name, **kwargs)

Create a distance metric by name.

Parameters:

Name Type Description Default
name str

Metric identifier.

required
**kwargs Any

Metric-specific parameters.

{}

Returns:

Type Description
DistanceMetricProtocol

Distance metric callable.

Source code in src/oversampleqa/types.py
368
369
370
371
372
373
374
375
376
377
378
def create_metric(self, name: str, **kwargs: Any) -> DistanceMetricProtocol:
    """Create a distance metric by name.

    Args:
        name: Metric identifier.
        **kwargs: Metric-specific parameters.

    Returns:
        Distance metric callable.
    """
    ...