Skip to main content

Test-data generator for validating the weighted k-NN (wkNN) method.

Project description

generate-test-data-for-wknn

PyPI Python License: MIT

EN — Synthetic test-data generator for validating the weighted k-NN (wkNN) method. RU — Генератор синтетических тестовых данных для проверки метода взвешенного k-NN (wkNN).

Authors / Авторы: Ferubko Andrey, Kazakov Oleg Organization / Организация: Bryansk State Technological University of Engineering / Брянский государственный инженерно-технологический университет.


Installation / Установка

pip install generate-test-data-for-wknn
# or with uv:
uv add generate-test-data-for-wknn

English documentation

The library exposes a single public function, generate (also available as WknnDataGenerator.generate), which builds a labelled dataset (x, y) for testing weighted k-NN.

Model. Each class is given one random anchor point inside the cube [min_coord, max_abs_coord]^dim. The anchor is the maximum of that class's weight field (and is itself excluded from the output). For a point p and class c with anchor A_c, the weight uses the per-coordinate distances x_i = |p_i − A_{c,i}|. A point is labelled by the class with the largest weight, and is kept only where that class leads the runner-up by at least margin (default 10%) — so samples come from regions of strong class superiority rather than the decision boundary. This keeps each point's nearest neighbour in the same class with high probability.

Points are drawn and classified iteratively until every class reaches its balanced target (stratified top-up). Small samples work: a binary request for 2 objects yields exactly 1 point per class.

Weight functions and parameter layout

Weights use per-coordinate distances, so params has 2·dim + 1 shared values [a₁, b₁, …, a_d, b_d, f] — the same coefficients for every class. Both types require aᵢ ≥ 0 and bᵢ > 0 (weight decreases with distance).

weight_type Formula params length Constraint
"inverse" w = Σᵢ aᵢ / xᵢ^bᵢ + f 2·dim + 1 aᵢ ≥ 0, bᵢ > 0
"exponential" w = Σᵢ aᵢ·exp(−bᵢ·xᵢ) + f 2·dim + 1 aᵢ ≥ 0, bᵢ > 0

Example: dim=2, inverse, params=[2, 1, 3, 4, 1]w = 2/x₁¹ + 3/x₂⁴ + 1.

Note on exponential: distances are normalised by the cube width, so choose bᵢ on the order of 1 (not 0.01). Very small bᵢ make exp(−bᵢ·xᵢ) nearly constant across the cube, so no class clears the margin and generation fails with a clear diagnostic.

Parameters

Name Default Meaning
n_classes 2 number of classes (binary by default)
dim 2 dimensionality of each point
n_samples 30 number of objects in the dataset (exact)
weight_type "inverse" "inverse" or "exponential"
params None shared coefficient array [a₁,b₁,…,a_d,b_d,f] (see table)
max_abs_coord 1e4 upper coordinate bound
min_coord -1e4 lower coordinate bound (use 0 for e.g. time series)
outlier_ratio 0.0 fraction of the most borderline labels to flip, in [0, 1]
margin 0.10 required relative superiority of the winning class (w_top ≥ (1+margin)·w_second) for a point to be kept
random_state None RNG seed

Returns: (x, y)x is float64 (m, dim), y is int64 (m,), m == n_samples.

Behavioural guarantees

  • Anchors are maxima: each class's weight field peaks at its anchor.
  • Stratification: classes are balanced (counts differ by at most 1).
  • Margin: kept points beat the runner-up class by ≥ margin (default 10%), drawing samples from regions of strong class superiority.
  • Nearest neighbour (soft): because samples avoid the borderlands, each point's nearest neighbour is in the same class with high probability.
  • Outliers: the requested fraction of the most borderline points is relabelled to the runner-up class (sample size unchanged).
  • Monotonicity guard: aᵢ < 0 or bᵢ ≤ 0 raises ValueError.
  • Flat-field guard: if no candidate clears the margin (e.g. exponential with tiny bᵢ over a wide cube), a clear ValueError explains the cause.

Example

import numpy as np
from generate_test_data_for_wknn import generate

# Binary, inverse-distance weights, 2-D, reproducible
x, y = generate(
    n_classes=2,
    dim=2,
    n_samples=100,
    weight_type="inverse",
    params=np.array([2.0, 1.0, 3.0, 4.0, 1.0]),  # a1,b1,a2,b2,f (shared)
    max_abs_coord=100.0,
    min_coord=0.0,
    outlier_ratio=0.1,
    margin=0.10,
    random_state=42,
)
print(x.shape, y.shape, np.bincount(y))

Документация на русском

Библиотека предоставляет одну публичную функцию generate (также доступна как WknnDataGenerator.generate), которая строит размеченный набор (x, y) для проверки взвешенного k-NN.

Модель. Для каждого класса создаётся одна случайная опорная точка внутри куба [min_coord, max_abs_coord]^dim. Опорная точка — это максимум весового поля класса (и в выборку она не входит). Для точки p и класса c с опорной точкой A_c вес использует покоординатные расстояния xᵢ = |pᵢ − A_{c,i}|. Точка размечается классом с наибольшим весом и сохраняется только там, где этот класс превосходит второй как минимум на margin (по умолчанию 10%) — то есть выборка берётся из областей уверенного превосходства класса, а не с границы. Это обеспечивает, что ближайший сосед каждой точки с высокой вероятностью того же класса.

Точки генерируются и классифицируются итеративно, пока каждый класс не наберёт свою сбалансированную квоту (стратифицированное дозаполнение). Малые выборки работают: бинарный запрос на 2 объекта даёт ровно по 1 точке на класс.

Весовые функции и формат параметров

Веса используют покоординатные расстояния, поэтому params содержит 2·dim + 1 общих значений [a₁, b₁, …, a_d, b_d, f]одинаковых для всех классов. Оба типа требуют aᵢ ≥ 0 и bᵢ > 0.

weight_type Формула Длина params Ограничение
"inverse" w = Σᵢ aᵢ / xᵢ^bᵢ + f 2·dim + 1 aᵢ ≥ 0, bᵢ > 0
"exponential" w = Σᵢ aᵢ·exp(−bᵢ·xᵢ) + f 2·dim + 1 aᵢ ≥ 0, bᵢ > 0

Замечание про exponential: расстояния нормируются по ширине куба, поэтому выбирайте bᵢ порядка 1 (а не 0.01). Слишком малые bᵢ делают exp(−bᵢ·xᵢ) почти постоянным по кубу, ни один класс не преодолевает отступ, и генерация завершается понятной ошибкой.

Параметры

Имя По умолчанию Смысл
n_classes 2 число классов
dim 2 размерность точки
n_samples 30 число объектов (точно)
weight_type "inverse" "inverse" или "exponential"
params None общий массив коэффициентов [a₁,b₁,…,a_d,b_d,f]
max_abs_coord 1e4 верхняя граница координат
min_coord -1e4 нижняя граница (для временных рядов задайте 0)
outlier_ratio 0.0 доля наиболее пограничных меток для переворота, из [0, 1]
margin 0.10 требуемое относительное превосходство класса-победителя (w_top ≥ (1+margin)·w_second)
random_state None зерно генератора

Возвращает: (x, y) — массивы NumPy; m == n_samples.

Гарантии поведения

  • Опорные точки — максимумы: весовое поле класса достигает пика в его опоре.
  • Стратификация: классы сбалансированы (разница ≤ 1 объект).
  • Отступ (margin): сохранённые точки превосходят второй класс на ≥ margin (по умолчанию 10%), выборка берётся из областей уверенного превосходства.
  • Ближайший сосед (мягкое условие): так как выборка избегает границ, ближайший сосед каждой точки с высокой вероятностью того же класса.
  • Выбросы: заданная доля наиболее пограничных точек переразмечается в класс-«второе место» (размер выборки не меняется).
  • Проверка монотонности: aᵢ < 0 или bᵢ ≤ 0ValueError.
  • Защита от плоского поля: если ни одна точка не преодолевает отступ (например, exponential с крошечными bᵢ на широком кубе), возбуждается понятный ValueError.

Пример

import numpy as np
from generate_test_data_for_wknn import generate

x, y = generate(
    n_classes=3,
    dim=2,
    n_samples=90,
    weight_type="exponential",
    params=np.array([5.0, 1.0, 4.0, 1.5, 0.0]),  # a1,b1,a2,b2,f (shared)
    outlier_ratio=0.15,
    margin=0.10,
    random_state=7,
)
print(x.shape, y.shape, np.bincount(y))

License / Лицензия

MIT © Ferubko Andrey, Kazakov Oleg — Bryansk State Technological University of Engineering.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

generate_test_data_for_wknn-0.0.8.tar.gz (9.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

generate_test_data_for_wknn-0.0.8-py3-none-any.whl (10.6 kB view details)

Uploaded Python 3

File details

Details for the file generate_test_data_for_wknn-0.0.8.tar.gz.

File metadata

  • Download URL: generate_test_data_for_wknn-0.0.8.tar.gz
  • Upload date:
  • Size: 9.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for generate_test_data_for_wknn-0.0.8.tar.gz
Algorithm Hash digest
SHA256 c52897ce81390a074dd9c601bc18407f634e3d2273e3d56668f28c9e6afbf99d
MD5 5152a6b5cb2f5579660fa4579f597165
BLAKE2b-256 1021d4b4aab6c6929e8c9904d02d32da0591a0b14a047b0aa74af0cb66b8ecf2

See more details on using hashes here.

File details

Details for the file generate_test_data_for_wknn-0.0.8-py3-none-any.whl.

File metadata

  • Download URL: generate_test_data_for_wknn-0.0.8-py3-none-any.whl
  • Upload date:
  • Size: 10.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for generate_test_data_for_wknn-0.0.8-py3-none-any.whl
Algorithm Hash digest
SHA256 2c8d3a3176cd648a1c0a14b1e3b1aeab4a6cbb7159193b8906722754095ed6c4
MD5 27370692505fd1e9a2cae641b97fac12
BLAKE2b-256 a7ceaec81ed3b59fb1197b2c7e9cb67a76ba825866bfd4460c11e7c701877fd5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page