Skip to main content

**LaplacianNB** is a Python module developed at **Novartis AG** for Naive Bayes classifier for laplacian modified models based on scikit-learn Naive Bayes implementation.

Project description

LaplacianNB

Naive Bayes classifier for Laplacian-modified models
Efficient, scikit-learn compatible, and designed for binary/boolean data

PyPI Version PyPI Downloads Python Versions Code Quality Test Coverage Security Scan License pre-commit Ruff

LaplacianNB is a Python module developed at Novartis AG for a Naive Bayes classifier for Laplacian-modified models, based on the scikit-learn Naive Bayes implementation.

This classifier is ideal for binary/boolean data, using only the indices of positive bits for efficient prediction. The algorithm was first implemented in Pipeline Pilot and KNIME.

The package includes both a modern sklearn-compatible implementation (recommended) and a legacy version for backward compatibility.


Features

  • Modern sklearn-compatible implementation with full ecosystem integration
  • Optimized for binary/boolean data with fast prediction using indices of positive bits
  • RDKit fingerprint conversion utilities for molecular data
  • Support for sparse and dense data formats
  • Memory-efficient sparse matrix handling
  • Lightweight and easy to integrate

Installation

Stable Release

Install the latest stable release from PyPI:

pip install laplaciannb

Development Version

Get the latest features with development releases:

pip install --pre laplaciannb

From Source

For the latest development version:

git clone https://github.com/rdkit/laplaciannb.git
cd laplaciannb
pip install -e .

Quick Start

Recommended Usage (Modern sklearn-compatible API)

import numpy as np
from laplaciannb import LaplacianNB
from laplaciannb.fingerprint_utils import convert_fingerprints

# Convert fingerprint data to sklearn format
fingerprints = [
    {1, 5, 10, 15},      # Fingerprint as set of bit indices
    {2, 6, 11, 16},      # Each set represents active bits
    {1, 3, 7, 12}
]
X = convert_fingerprints(fingerprints, n_bits=20)
y = [0, 1, 0]

# Train and predict
clf = LaplacianNB(alpha=1.0)
clf.fit(X, y)
predictions = clf.predict(X)
probabilities = clf.predict_proba(X)

sklearn Ecosystem Integration

from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV, cross_val_score
from laplaciannb import LaplacianNB, FingerprintTransformer

# Create pipeline
pipeline = Pipeline([
    ('fingerprints', FingerprintTransformer(n_bits=2048)),
    ('classifier', LaplacianNB())
])

# Grid search
param_grid = {
    'classifier__alpha': [0.1, 1.0, 10.0],
    'fingerprints__output_format': ['csr', 'dense']
}
grid_search = GridSearchCV(pipeline, param_grid, cv=5)
grid_search.fit(fingerprints, y)

# Cross-validation
cv_scores = cross_val_score(pipeline, fingerprints, y, cv=5)

Legacy Usage (Deprecated)

⚠️ DEPRECATION NOTICE: The legacy API is deprecated and will be removed in a future release. Please migrate to the modern sklearn-compatible API above.

# For backward compatibility only - will show deprecation warnings
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)

from laplaciannb.legacy import LaplacianNB as LegacyLaplacianNB

# Legacy format (sets of bit indices)
X_sets = np.array([{1, 5, 10}, {2, 6, 11}, {1, 3, 7}], dtype=object)
y = [0, 1, 0]

clf = LegacyLaplacianNB(alpha=1.0)
clf.fit(X_sets, y)
predictions = clf.predict(X_sets)

Migration Guide

Migrating from legacy to modern implementation is easy:

  1. Update imports:

    # Before (deprecated)
    from laplaciannb.legacy import LaplacianNB
    
    # After (recommended)
    from laplaciannb import LaplacianNB
    from laplaciannb.fingerprint_utils import convert_fingerprints
    
  2. Convert input data:

    # Convert fingerprint sets to sklearn format
    X = convert_fingerprints(your_fingerprint_sets, n_bits=your_size)
    
  3. Same API for basic usage:

    clf = LaplacianNB(alpha=1.0)
    clf.fit(X, y)
    predictions = clf.predict(X)
    

📖 Detailed migration instructions: MIGRATION_GUIDE.md 📅 Deprecation timeline: DEPRECATION_TIMELINE.md


Basic Usage with LaplacianNB

import numpy as np
from laplaciannb import LaplacianNB

# Create sample data (sets of positive bit indices)
X = np.array([
    {1, 5, 10, 15},      # Sample 1: bits 1,5,10,15 are on
    {2, 6, 11, 16},      # Sample 2: bits 2,6,11,16 are on
    {1, 3, 7, 12},       # Sample 3: bits 1,3,7,12 are on
], dtype=object)
y = np.array([0, 1, 0])  # Class labels

# Train the classifier
clf = LaplacianNB()
clf.fit(X, y)

# Make predictions
predictions = clf.predict(X)
probabilities = clf.predict_proba(X)

RDKit Fingerprint Integration

from rdkit import Chem
from rdkit.Chem import AllChem
from laplaciannb import LaplacianNB, convert_fingerprints

# Generate molecular fingerprints
molecules = [Chem.MolFromSmiles(smi) for smi in ['CCO', 'CC', 'CCC']]
fingerprints = [AllChem.GetMorganFingerprintAsBitVect(mol, 2) for mol in molecules]

# Convert to sklearn-compatible format
X = convert_fingerprints(fingerprints, output_format='csr')
y = [0, 1, 0]

# Train classifier
clf = LaplacianNB()
clf.fit(X, y)

Advanced Fingerprint Conversion

from laplaciannb import RDKitFingerprintConverter

# Create converter with custom settings
converter = RDKitFingerprintConverter(
    n_bits=2048,
    output_format='auto',  # Automatically choose sparse/dense
    dtype=np.float32
)

# Convert fingerprints
X_dense = converter.to_dense(fingerprints)
X_sparse = converter.to_csr(fingerprints)

# Get statistics
stats = converter.get_statistics(fingerprints)
print(f"Sparsity: {stats['sparsity']:.2%}")
print(f"Average on-bits: {stats['avg_on_bits']:.1f}")

Development

Contributing

We welcome contributions! Please see our development setup:

# Clone the repository
git clone https://github.com/rdkit/laplaciannb.git
cd laplaciannb

# Install in development mode with test dependencies
pip install -e .[test]

# Install pre-commit hooks
pre-commit install

# Run tests
pytest tests/

# Run quality checks
pre-commit run --all-files

CI/CD Pipeline

  • Code Quality: Ruff linting and formatting
  • Testing: Multi-Python version testing with coverage
  • Security: Bandit security scanning
  • Auto-publishing: Development versions on merge to develop
  • Dependency Management: Dependabot for automated updates

Project Structure

laplaciannb/
├── src/laplaciannb/           # Main package
│   ├── LaplacianNB_new.py     # Modern implementation
│   ├── fingerprint_utils.py   # Conversion utilities
│   └── legacy/                # Deprecated legacy API
├── tests/                     # Test suite
├── .github/                   # CI/CD workflows
└── docs/                      # Documentation

Literature

Nidhi; Glick, M.; Davies, J. W.; Jenkins, J. L. Prediction of biological targets
for compounds using multiple-category Bayesian models trained on chemogenomics
databases. J. Chem. Inf. Model. 2006, 46, 1124– 1133,
https://doi.org/10.1021/ci060003g

Lam PY, Kutchukian P, Anand R, et al. Cyp1 inhibition prevents doxorubicin-induced cardiomyopathy
in a zebrafish heart-failure model. Chem Bio Chem. 2020:cbic.201900741.
https://doi.org/10.1002/cbic.201900741

Authors & Maintainers


Changelog

v0.7.0 (Latest)

  • Sklearn integration handling standard sklearn input allowing for full integration with sklearn framework
  • Enhanced deprecation strategy with comprehensive migration support
  • Legacy input detection in new version with helpful error messages
  • Dependabot configuration for automated dependency updates

v0.6.1

  • Fixes for scikit-learn 1.7, rdkit 2025+ compatibility
  • Move to uv build system

v0.6.0

  • Move to pdm build system

v0.5.0

  • Initial public release

License

This project is licensed under the BSD 3-Clause License. See the LICENSE file for details.

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

laplaciannb-0.7.0.dev202508181649.tar.gz (35.0 kB view details)

Uploaded Source

Built Distribution

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

laplaciannb-0.7.0.dev202508181649-py3-none-any.whl (19.4 kB view details)

Uploaded Python 3

File details

Details for the file laplaciannb-0.7.0.dev202508181649.tar.gz.

File metadata

File hashes

Hashes for laplaciannb-0.7.0.dev202508181649.tar.gz
Algorithm Hash digest
SHA256 6564b7a94a2844b939cd353450daf9187b6f0048819c3cdbe299851841ed1ca7
MD5 7b40fca487a97d9474f18f0abf495f2e
BLAKE2b-256 6042f14063b2f95ea5f16d444231c64314cbd849d9a25a9ff863c29aaca2be23

See more details on using hashes here.

File details

Details for the file laplaciannb-0.7.0.dev202508181649-py3-none-any.whl.

File metadata

File hashes

Hashes for laplaciannb-0.7.0.dev202508181649-py3-none-any.whl
Algorithm Hash digest
SHA256 24d0770b157db6fdddb601fea5a25282cb2f13152fe4908ef90ec7afdd8fb15a
MD5 46c7d5b52f5eba7c1758fcbbfe4f6103
BLAKE2b-256 63fd2ea70ed0a2dd6156360759d470a2bacae1e4766313adc32b15c35def833b

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