Skip to main content

GQNN: A Python Package for Quantum Neural Networks

Publish Python Package Status PyPI Downloads PyPI Downloads PyPI Downloads License: GPL v3 Python Contributions welcome Code style: black PRs Welcome GitHub last commit GitHub Repo stars

GQNN is a pioneering Python library designed for research and experimentation with Quantum Neural Networks (QNNs). By integrating principles of quantum computing with classical neural network architectures, GQNN enables researchers to explore hybrid models that leverage the computational advantages of quantum systems. This library was developed by GokulRaj S as part of his research on Customized Quantum Neural Networks.


Table of Contents

  1. Introduction
  2. Features
  3. Installation
  4. Getting Started
  5. Use Cases
  6. Documentation
  7. Requirements
  8. Contribution
  9. License
  10. Acknowledgements
  11. Contact

Introduction

Quantum Neural Networks (QNNs) are an emerging field of study combining the principles of quantum mechanics with artificial intelligence. The GQNN package offers a platform to implement and study hybrid quantum-classical neural networks, aiming to bridge the gap between theoretical quantum algorithms and practical machine learning applications.

This package allows you to:

  • Experiment with QNN architectures.
  • Train models on classical or quantum data.
  • Explore quantum-enhanced learning algorithms.
  • Conduct research in Quantum Machine Learning.

Features

  • Hybrid Neural Networks: Combines classical and quantum layers seamlessly.
  • Custom Quantum Circuits: Design and implement your own quantum gates and circuits.
  • Lightweight and Flexible: Built with Python, NumPy, and scikit-learn for simplicity and extensibility.
  • Scalable: Easily scale models for larger qubit configurations or datasets.
  • Research-Oriented: Ideal for academic and experimental use in quantum machine learning.

Installation

Prerequisites

  • Python 3.7 to 3.12 higher or lower version is not supported
  • Ensure pip is updated: pip install --upgrade pip

Installing GQNN

From PyPI

pip install GQNN

From Source

git clone https://github.com/gokulraj0906/GQNN.git
cd GQNN
pip install .

Getting Started

Basic Example

Classification model

import matplotlib
matplotlib.use("Agg")
matplotlib.use("TkAgg")

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

from GQNN.models.classification_model import (
    QuantumClassifier_EstimatorQNN_CPU,
    QuantumClassifier_SamplerQNN_CPU,
    VariationalQuantumClassifier_CPU
)

# Data prep
X, y = make_classification(
    n_samples=200, n_features=2, n_informative=2,
    n_redundant=0, n_clusters_per_class=1, random_state=42
)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=42
)
scaler = StandardScaler()
X_train, X_test = scaler.fit_transform(X_train), scaler.transform(X_test)

# Helper to run, evaluate, save, visualize
def run_model(model, name):
    print(f"\n🔹 Training {name}...")
    model.fit(X_train, y_train, verbose=True)
    acc = model.score(X_test, y_test)
    print(f"{name} Accuracy: {acc:.4f}")
    model.save_model(f"{name.lower()}.pkl")
    model.print_model(f"{name.lower()}_circuit.png")

# Run different models
run_model(
    QuantumClassifier_EstimatorQNN_CPU(num_qubits=2, batch_size=32, lr=0.001),
    "EstimatorQNN"
)

run_model(
    QuantumClassifier_SamplerQNN_CPU(num_inputs=2, output_shape=2, ansatz_reps=1, maxiter=50),
    "SamplerQNN"
)

run_model(
    VariationalQuantumClassifier_CPU(num_inputs=2, maxiter=30),
    "VariationalQNN"
)

Regression Example

import matplotlib
matplotlib.use("Agg")

from GQNN.models.regression_model import (
   QuantumRegressor_EstimatorQNN_CPU,
   QuantumRegressor_VQR_CPU
)
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# Generate regression data
X, y = make_regression(
   n_samples=150,
   n_features=3,
   n_informative=3,
   noise=3.0,
   random_state=42,
   bias=0.0
)

X_train, X_test, y_train, y_test = train_test_split(
   X, y, test_size=0.2, random_state=42
)

# Scaling
scaler_X = StandardScaler()
scaler_y = StandardScaler()
X_train_scaled = scaler_X.fit_transform(X_train)
X_test_scaled = scaler_X.transform(X_test)
y_train_scaled = scaler_y.fit_transform(y_train.reshape(-1, 1)).flatten()
y_test_scaled = scaler_y.transform(y_test.reshape(-1, 1)).flatten()

# Helper
def run_regressor(model, name):
   print(f"\n🔹 Training {name}...")
   model.fit(X_train_scaled, y_train_scaled, verbose=True)
   r2_train = model.score(X_train_scaled, y_train_scaled)
   r2_test = model.score(X_test_scaled, y_test_scaled)
   print(f"{name} R² Train: {r2_train:.4f}, R² Test: {r2_test:.4f}")
   model.save_model(f"{name.lower()}.pkl")
   model.print_model(f"{name.lower()}_circuit.png")

# Run models
run_regressor(
   QuantumRegressor_EstimatorQNN_CPU(num_qubits=3, maxiter=100),
   "EstimatorQNN_Regressor"
)

run_regressor(
   QuantumRegressor_VQR_CPU(num_qubits=3, maxiter=100),
   "VariationalQNN_Regressor"
)

QSVM Example (Classification + Regression)

"""
Comprehensive QSVM Testing: Classification and Regression
"""

from GQNN.models.qsvm import QSVC_CPU, QSVR_CPU
from sklearn.datasets import make_classification, make_regression
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import (
   accuracy_score, confusion_matrix, r2_score,
   mean_squared_error, mean_absolute_error
)
import numpy as np

def run_qsvc():
   X, y = make_classification(
       n_samples=80, n_features=2, n_informative=2,
       n_redundant=0, random_state=42
   )
   X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
   scaler = StandardScaler()
   X_train_scaled, X_test_scaled = scaler.fit_transform(X_train), scaler.transform(X_test)

   model = QSVC_CPU(num_qubits=2, feature_map_reps=2)
   model.fit(X_train_scaled, y_train, verbose=True)
   y_pred = model.predict(X_test_scaled)

   acc = accuracy_score(y_test, y_pred)
   cm = confusion_matrix(y_test, y_pred)
   print(f"\nQSVC Accuracy: {acc:.4f}")
   print("Confusion Matrix:\n", cm)
   model.save_model("qsvc_model.pkl")
   model.print_model("qsvc_circuit.png")

def run_qsvr():
   X, y = make_regression(n_samples=80, n_features=2, noise=10.0, random_state=42)
   X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
   scaler = StandardScaler()
   X_train_scaled, X_test_scaled = scaler.fit_transform(X_train), scaler.transform(X_test)

   model = QSVR_CPU(num_qubits=2, feature_map_reps=2, epsilon=0.1)
   model.fit(X_train_scaled, y_train, verbose=True)
   y_pred = model.predict(X_test_scaled)

   r2 = r2_score(y_test, y_pred)
   mse, mae = mean_squared_error(y_test, y_pred), mean_absolute_error(y_test, y_pred)
   print(f"\nQSVR R²: {r2:.4f}, MSE: {mse:.4f}, MAE: {mae:.4f}")
   model.save_model("qsvr_model.pkl")
   model.print_model("qsvr_circuit.png")

if __name__ == "__main__":
   run_qsvc()
   run_qsvr()

Advanced Usage

For more advanced configurations, such as custom quantum gates or layers, refer to the Documentation.


Use Cases

GQNN can be used for:

  1. Research and Development: Experiment with quantum-enhanced machine learning algorithms.
  2. Education: Learn and teach quantum computing principles via QNNs.
  3. Prototyping: Develop proof-of-concept models for quantum computing applications.
  4. Hybrid Systems: Integrate classical and quantum systems for real-world data processing.

Documentation

Comprehensive documentation is available to help you get started with GQNN, including tutorials, API references, and implementation guides.


Requirements

The following dependencies are required to use GQNN:

  • Python >= 3.7
  • NumPy
  • Pandas
  • scikit-learn
  • Qiskit
  • Qiskit-machine-learning
  • Qiskit_ibm_runtime
  • matplotlib
  • ipython
  • pylatexenc

For Linux Users

pip install GQNN[linux]

Optional:

  • Quantum simulation tools (e.g., Qiskit or Cirq) for advanced quantum operations.

Install required dependencies using:

pip install GQNN

Contribution

We welcome contributions to make GQNN better! Here's how you can contribute:

  1. Fork the Repository: Click the "Fork" button on the GitHub page.
  2. Clone Your Fork:
    git clone https://github.com/gokulraj0906/GQNN.git
    
  3. Create a New Branch:
    git checkout -b feature-name
    
  4. Make Your Changes: Implement your feature or bug fix.
  5. Push Changes:
    git push origin feature-name
    
  6. Submit a Pull Request: Open a pull request with a detailed description of your changes.

License

GQNN is licensed under the GPL-3.0 License. See the LICENSE file for full details.


Acknowledgements

  • This package is a result of research work by GokulRaj S.
  • Special thanks to the open-source community and the developers of foundational quantum computing tools.
  • Inspired by emerging trends in Quantum Machine Learning.

Contact

For queries, feedback, or collaboration opportunities, please reach out:

Author: GokulRaj S
Email: gokulsenthil0906@gmail.com
GitHub: gokulraj0906
LinkedIn: Gokul Raj


Happy Quantum Computing! 🚀

Metadata

Release files for GQNN 1.6.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for GQNN 1.6.0
File Size Uploaded
gqnn-1.6.0.tar.gz 48.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for GQNN 1.6.0
File Interpreter ABI Platform
gqnn-1.6.0-py3-none-any.whl Python 3 none any Details

Total release size: 98.1 kB

Release files / gqnn-1.6.0.tar.gz

Download URL gqnn-1.6.0.tar.gz
Size 48.4 kB
Tags Source
SHA-256 checksum
How to use checksums
8fabf7e67ef815d7f19f77ad556bb69fbbd8b340f90c81a9e0614f9003e517e3
BLAKE2b-256 checksum
How to use checksums
5910674ee7a9b7c038043f80bd5d86b50cb49c2f05a401c3d747aa66139ff019
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.7

Release files / gqnn-1.6.0-py3-none-any.whl

Download URL gqnn-1.6.0-py3-none-any.whl
Size 49.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3ada974939aada022da08c2e92a89d14771b499af2ea1d5f42b289829aa69707
BLAKE2b-256 checksum
How to use checksums
e3a3e809e90a69a5511d47b1c1db43e4ebcd1b309fb1338da6f85eefd1d7d8e8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.7

Release history Release notifications | RSS feed

This release

1.6.0 This release

2 release files

1.5.5

2 release files

1.5.0

2 release files

1.4.4

2 release files

1.4.1

2 release files

1.3.4

2 release files

1.2.1

2 release files

1.1.1

2 release files

1.0.1

2 release files

1.0.0

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page