Skip to main content

Spectral Clustering Using Deep Neural Networks

Project description

SpectralNet

SpectralNet is a Python package that performs spectral clustering with deep neural networks.

This package is based on the following paper - SpectralNet

Installation

From PyPI

pip install spectralnet

From source (with pixi)

pixi is the recommended way to set up a fully reproducible development environment after cloning the repo.

# 1. Install pixi (once, system-wide)
curl -fsSL https://pixi.sh/install.sh | sh

# 2. Clone and enter the repo
git clone https://github.com/shaham-lab/SpectralNet.git
cd SpectralNet

# 3. Install all dependencies (conda + PyPI) into an isolated environment
pixi install

# 4. Run the test suite to verify everything works
pixi run test

After pixi install you can prefix any command with pixi run to execute it inside the managed environment, or activate the environment with:

pixi shell

Usage

Clustering — small datasets (in-memory tensor)

For datasets that fit in RAM, pass a torch.Tensor directly:

from spectralnet import SpectralNet

spectralnet = SpectralNet(n_clusters=10)
spectralnet.fit(X)                          # X: torch.Tensor of shape (N, ...)
cluster_assignments = spectralnet.predict(X)

To measure ACC and NMI when labels are available:

from spectralnet import SpectralNet, Metrics

spectralnet = SpectralNet(n_clusters=2)
spectralnet.fit(X, y)                       # y: integer label tensor
cluster_assignments = spectralnet.predict(X)

y_np = y.detach().cpu().numpy()
acc_score = Metrics.acc_score(cluster_assignments, y_np, n_clusters=2)
nmi_score = Metrics.nmi_score(cluster_assignments, y_np)
print(f"ACC: {acc_score:.3f}  NMI: {nmi_score:.3f}")

Clustering — large datasets (streaming from disk)

For datasets too large to hold in RAM (e.g. millions of images on disk), define a torch.utils.data.Dataset that loads one sample at a time and pass it to fit(). Nothing large ever lives in memory at once — every trainer pulls mini-batches through its own DataLoader internally.

from torch.utils.data import Dataset, DataLoader
from spectralnet import SpectralNet
from PIL import Image
import torchvision.transforms as T
import os

class ImageFolderDataset(Dataset):
    def __init__(self, root):
        self.paths = [
            os.path.join(root, f) for f in os.listdir(root) if f.endswith(".jpg")
        ]
        self.transform = T.Compose([T.Resize(64), T.ToTensor(), T.Normalize(0.5, 0.5)])

    def __len__(self):
        return len(self.paths)

    def __getitem__(self, idx):
        return self.transform(Image.open(self.paths[idx]).convert("RGB"))

dataset = ImageFolderDataset("/path/to/images")

spectralnet = SpectralNet(
    n_clusters=10,
    should_use_ae=True,              # compress images before clustering
    ae_hiddens=[2048, 512, 64, 10],
    spectral_hiddens=[512, 512, 10],
)
spectralnet.fit(dataset)

# predict() also accepts a DataLoader for large test sets
test_loader = DataLoader(dataset, batch_size=512, shuffle=False)
cluster_assignments = spectralnet.predict(test_loader)

Note on Siamese training with large datasets: the Siamese network builds exact k-NN pairs, which requires loading all features into memory. For very large datasets either disable it (should_use_siamese=False), enable approximate neighbours (siamese_use_approx=True), or pass a representative subset as the Dataset.

Running examples

cd examples
python3 cluster_twomoons.py
python3 cluster_mnist.py

Citation


@inproceedings{shaham2018,
author = {Uri Shaham and Kelly Stanton and Henri Li and Boaz Nadler and Ronen Basri and Yuval Kluger},
title = {SpectralNet: Spectral Clustering Using Deep Neural Networks},
booktitle = {Proc. ICLR 2018},
year = {2018}
}

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

spectralnet-1.0.1.tar.gz (27.6 kB view details)

Uploaded Source

Built Distribution

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

spectralnet-1.0.1-py3-none-any.whl (33.1 kB view details)

Uploaded Python 3

File details

Details for the file spectralnet-1.0.1.tar.gz.

File metadata

  • Download URL: spectralnet-1.0.1.tar.gz
  • Upload date:
  • Size: 27.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for spectralnet-1.0.1.tar.gz
Algorithm Hash digest
SHA256 b728bf2452a7a17e19efb876a2834920678ce84602035d0b5bb1c76e0d08b2ad
MD5 d98230a0be89786134b59bfd5a126d5f
BLAKE2b-256 8deef2b31e2f413028440e468e723cf09634517379ca763f379bcd0f73c7da1b

See more details on using hashes here.

Provenance

The following attestation bundles were made for spectralnet-1.0.1.tar.gz:

Publisher: release.yml on shaham-lab/SpectralNet

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file spectralnet-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: spectralnet-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 33.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for spectralnet-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 15524370bcf6d42c04617769c988bd9a20f161563a3f777a0d4fa354504bbd7a
MD5 6f0315f210b1fca098d29fb3717ce55c
BLAKE2b-256 14fc7fde43d40042977733c8586adac62cef81e723d01d7f0c9f91981b0c474a

See more details on using hashes here.

Provenance

The following attestation bundles were made for spectralnet-1.0.1-py3-none-any.whl:

Publisher: release.yml on shaham-lab/SpectralNet

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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