Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
T

torchnca

> 编程语言
Open source

A PyTorch implementation of Neighbourhood Components Analysis.

396 stars0 likes1 views
WebsiteGitHub

About

A PyTorch implementation of Neighbourhood Components Analysis.

torchnca

A PyTorch implementation of Neighbourhood Components Analysis by J. Goldberger, G. Hinton, S. Roweis, R. Salakhutdinov. NCA is a metric learning technique that learns a linear transformation of the dataset such that the expected leave-one-out performance of kNN in the transformed space is maximized.

For a more detailed explanation of NCA, check out the accompanying blog post.

Installation

You can install torchnca with pip:

bash
pip install torchnca

API

python
from torchnca import NCA

# instantiate torchnca object and initialize with
# an identity matrix
nca = NCA(dim=2, init="identity")

# fit an torchnca model to a dataset
# normalize the input data before
# running the optimization
nca.train(X, y, batch_size=64, normalize=True)

# apply the learned linear map to the data
X_nca = nca(X)

Dimensionality Reduction

We generate a 3-D dataset where the first 2 dimensions are concentric rings and the third dimension is Gaussian noise. We plot the result of PCA, LDA and NCA with 2 components.

Notice how PCA has failed to project out the noise, a result of a high noise variance in the third dimension. LDA also struggles to recover the concentric pattern since the classes themselves are not linearly separable.

kNN on MNIST

We compute the classification error, computation time and storage cost of two algorithms:

  • kNN (k = 5) on the raw 784 dimensional MNIST dataset
  • kNN (k = 5) on a learned 32 dimensional NCA projection of the MNIST dataset
Method NCA + kNN Raw kNN
Time 2.37s 155.25s
Storage 6.40 Mb 156.8 Mb
Error 3.27% 2.82%

Issues· 4 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Pythonnca-pythonneighbourhood-components-analysispythonpython3

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言