Skip to main content

Neural Weight Fields: incremental learning with built-in uncertainty. Charge, Field, metrics, FAISS index, calibrators.

Project description

nwf-core

PyPI version Python 3.9+ Tests License: MIT

What is NWF?

Neural Weight Fields (NWF) is a principled approach to representing data and knowledge in machine learning. Instead of point embeddings, each object is encoded as a semantic charge (z, Σ):

  • z — position vector in latent space (semantic core)
  • Σ — diagonal covariance matrix expressing model uncertainty about the object

This pair induces a semantic potential — a function decaying with distance. A collection of charges forms a semantic field — a continuous measure of data density in latent space.

Why NWF?

  • Incremental learning without catastrophic forgetting — add new classes by simply adding new charges to the index; no retraining, no knowledge erasure
  • Built-in uncertainty — covariance Σ enables calibrated confidence estimates and out-of-distribution (OOD) detection
  • Scalability — charges can be indexed with FAISS, HNSW (planned) for millions of objects

Installation

pip install nwf-core
# With FAISS: pip install nwf-core[faiss]
# With VAE (torch): pip install nwf-core[torch]
# All: pip install nwf-core[all]

Components

Charge

Base data structure: center z and diagonal covariance sigma.

  • to_dict() / from_dict() — JSON serialization
  • to_vector() — concatenated [z, log(sigma)] for indexing
  • whiten(mean, std) — transform to whitened space
  • clip_sigma(min_val) — ensure minimum sigma values

Field

Container for charges with labels and ids.

  • add(charges, labels, ids) — add charges
  • remove(ids) — remove by id
  • search(query, k) — k-nearest search (symmetric Mahalanobis)
  • save(path) / load(path) — persist to disk
  • __iter__ — iterate over (charge, label, id)
  • __getitem__(idx) — get charge by index

Metrics

  • mahalanobis_symmetric(z1, sigma1, z2, sigma2) — symmetric Mahalanobis distance
  • euclidean(z1, z2) — L2 distance
  • cosine(z1, z2) — cosine distance

Potential (OOD detection)

  • potential(r, charges) — semantic potential at point r; higher = in-distribution
  • potential_batch(r, z_all, sigma_all) — batch version for multiple queries

Indices

  • BruteForceIndex — exact search for small datasets; supports l2, cosine; batch search
  • FAISSIndex — FAISS-backed; metrics l2, cosine, ip; optional two-stage Mahalanobis reranking; save/load

Calibrators

  • AgreementRatio — fraction of k-nearest neighbors agreeing with prediction (no training)
  • PlattScaler — logistic regression for probability calibration

Encoders (optional, requires torch)

  • VAEEncoder — MLP VAE for flat vectors; outputs (z, sigma)

Quick start

import numpy as np
from nwf import Charge, Field, mahalanobis_symmetric

# Create charges
c1 = Charge(z=np.array([0.0, 0.0]), sigma=np.array([0.1, 0.1]))
c2 = Charge(z=np.array([1.0, 1.0]), sigma=np.array([0.1, 0.1]))

# Build field and search
field = Field()
field.add([c1, c2], labels=[0, 1])
distances, indices, labels = field.search(c1, k=2)

See documentation and nwf-vision for examples.


Development

pip install -e ".[dev,docs]"
pre-commit install
make lint
make format
make html

Links

License

MIT


nwf-core (Русский)

Что такое NWF?

Neural Weight Fields (Нейровесовые поля) — подход к представлению данных в машинном обучении. Каждый объект кодируется семантическим зарядом (z, Σ):

  • z — вектор положения в латентном пространстве (семантическое ядро)
  • Σ — диагональная ковариационная матрица (неопределённость модели)

Совокупность зарядов создаёт семантическое поле — непрерывную меру плотности данных.

Преимущества NWF

  • Инкрементальность — добавление новых классов без переобучения и забывания
  • Встроенная неопределённость — калибровка уверенности и OOD-детекция
  • Масштабируемость — индексация через FAISS для миллионов объектов

Установка

pip install nwf-core
# С FAISS: pip install nwf-core[faiss]
# С VAE: pip install nwf-core[torch]

Компоненты

  • Charge — заряд (z, sigma), сериализация, whiten, clip_sigma
  • Field — контейнер зарядов, add/remove/search, save/load
  • Метрики — mahalanobis_symmetric, euclidean, cosine
  • Потенциал — potential, potential_batch для OOD-детекции
  • Индексы — BruteForceIndex, FAISSIndex (l2, cosine, ip; rerank по Махаланобису)
  • Калибраторы — AgreementRatio, PlattScaler
  • VAEEncoder — MLP VAE (опционально)

Лицензия

MIT

Project details


Download files

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

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

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

nwf_core-0.2.3-py3-none-any.whl (16.3 kB view details)

Uploaded Python 3

File details

Details for the file nwf_core-0.2.3-py3-none-any.whl.

File metadata

  • Download URL: nwf_core-0.2.3-py3-none-any.whl
  • Upload date:
  • Size: 16.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.9

File hashes

Hashes for nwf_core-0.2.3-py3-none-any.whl
Algorithm Hash digest
SHA256 99f1db96a9fa209cdee3dd85314f31e494e6247937a5070fc119539693cad4c1
MD5 09a2ee5ee993f7510fa2a9cdecf83375
BLAKE2b-256 ff47b79ba3f36c4e64486d34ae35dd6c6537ee7466529b1e305f58b33370d188

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