parzen_window
English
parzen_window is a Python library implementing the Parzen window method for
classification, built on top of numpy and scikit-learn (BaseEstimator,
ClassifierMixin).
Features
- Five kernel shapes:
gaussian,epanechnikov,quartic,triangular,rectangular. - Adaptive bandwidth — each training point can get its own kernel width,
derived from the distance to its
k-th nearest neighbor, instead of a single fixedhfor the whole dataset (a variable-kernel / "balloon" estimator). This is the library's scientific contribution over plain fixed-bandwidth Parzen window implementations: it widens the kernel in sparse regions and narrows it in dense ones automatically. - Incremental learning —
partial_fit()extends the model with a new batch of data without discarding what it already learned. - Dataset compaction —
compact()reduces memory usage by removing training points that are deep inside their own class's territory (found via convex-neighborhood analysis: a point is dropped only if all its nearest neighbors share its label and it is far from the nearest point of a different class). This shrinks the stored dataset with minimal impact on the decision boundary. - Thread-safe compaction with a call scheduler — while
compact()is running, the training data is locked for writes.predict()andpartial_fit()calls from other threads do not fail during this time: they are queued and executed automatically as soon as compaction finishes. .npzpersistence —save()/load()for backups and moving a model between machines.- Fully compatible with
pickle/joblib.
Installation
pip install parzen_window
Quick start
from parzen_window import ParzenWindowClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
model = ParzenWindowClassifier(h=1.0, kernel="quartic")
model.fit(X_train, y_train)
predictions = model.predict(X_test)
probabilities = model.predict_proba(X_test)
Incremental learning:
model = ParzenWindowClassifier(h=0.5, kernel="gaussian")
model.fit(X_batch_1, y_batch_1)
model.partial_fit(X_batch_2, y_batch_2) # extends, does not discard X_batch_1
Adaptive bandwidth:
model = ParzenWindowClassifier(
h=1.0, kernel="gaussian", adaptive_bandwidth=True, bandwidth_neighbors=5
)
model.fit(X_train, y_train)
Compacting a large dataset to cut memory usage by ~25%:
removed = model.compact(0.25) # returns the number of points actually removed
Backups:
model.save("model.npz")
restored = ParzenWindowClassifier.load("model.npz")
Development
The project uses uv for dependency management.
uv sync --dev # install dependencies
uv run ruff check . # lint
uv run ruff format . # format
uv build # build sdist + wheel
Русский
parzen_window — библиотека на Python, реализующая метод Парзеновского окна
для классификации, построенная поверх numpy и scikit-learn
(BaseEstimator, ClassifierMixin).
Возможности
- Пять видов ядер:
gaussian,epanechnikov,quartic,triangular,rectangular. - Адаптивная ширина окна — каждая точка обучающей выборки может получить
собственную ширину ядра, вычисленную по расстоянию до её
k-го ближайшего соседа, вместо единого фиксированногоhна весь датасет (вариант variable-kernel / "balloon"-оценки). Это научная новизна библиотеки по сравнению с обычными реализациями Парзеновского окна с фиксированной шириной: окно автоматически расширяется в разреженных областях и сужается в плотных. - Дообучение —
partial_fit()расширяет модель новым батчем данных, не теряя уже накопленное. - Разрядка датасета —
compact()уменьшает потребление памяти, удаляя точки обучающей выборки, которые лежат глубоко на территории своего класса (метод анализа выпуклых окрестностей: точка удаляется, только если все её ближайшие соседи имеют ту же метку класса и она далека от ближайшей точки другого класса). Это сокращает хранимый датасет с минимальным влиянием на границу между классами. - Потокобезопасная разрядка с планировщиком вызовов — пока выполняется
compact(), обучающие данные заблокированы для записи. Вызовыpredict()иpartial_fit()из других потоков в это время не падают: они встают в очередь и выполняются автоматически сразу после завершения разрядки. - Сохранение в
.npz—save()/load()для бэкапов и переноса модели между устройствами. - Полная совместимость с
pickle/joblib.
Установка
pip install parzen_window
Быстрый старт
from parzen_window import ParzenWindowClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
model = ParzenWindowClassifier(h=1.0, kernel="quartic")
model.fit(X_train, y_train)
predictions = model.predict(X_test)
probabilities = model.predict_proba(X_test)
Дообучение:
model = ParzenWindowClassifier(h=0.5, kernel="gaussian")
model.fit(X_batch_1, y_batch_1)
model.partial_fit(X_batch_2, y_batch_2) # расширяет, не теряя X_batch_1
Адаптивная ширина окна:
model = ParzenWindowClassifier(
h=1.0, kernel="gaussian", adaptive_bandwidth=True, bandwidth_neighbors=5
)
model.fit(X_train, y_train)
Разрядка большого датасета, чтобы сократить потребление памяти примерно на 25%:
removed = model.compact(0.25) # возвращает число реально удалённых точек
Бэкапы:
model.save("model.npz")
restored = ParzenWindowClassifier.load("model.npz")
Разработка
Проект использует uv для управления зависимостями.
uv sync --dev # установить зависимости
uv run ruff check . # линтер
uv run ruff format . # форматирование
uv build # сборка sdist + wheel
Release files for parzen_window 0.0.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| parzen_window-0.0.2.tar.gz | 63.3 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| parzen_window-0.0.2-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 75.0 kB
Release files / parzen_window-0.0.2.tar.gz
| Download URL | parzen_window-0.0.2.tar.gz |
|---|---|
| Size | 63.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a28126c95026ce2a12a01b791f9554615a0d6213c15c02f1464e49a76284b612
|
|
BLAKE2b-256 checksum How to use checksums |
00512721a26653d6f3383602d17cf3533824bc41ee406fcfa1592d34fb35f9f0
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is 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}
|
Release files / parzen_window-0.0.2-py3-none-any.whl
| Download URL | parzen_window-0.0.2-py3-none-any.whl |
|---|---|
| Size | 11.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
3726a16ac80d21c12b6277539d5eefa4561f1a8db5cbb9bc69f824fc865d877d
|
|
BLAKE2b-256 checksum How to use checksums |
0e4cbe071e24a17b7643a0a011b31016c5df1fac28d671b54ef8fb6ba6301c20
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is 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}
|