Spektral: Graph Neural Networks for TensorFlow and Keras

Jul 9, 2025

Introduction

Analyzing structured data where relationships are as important as the data itself often requires moving beyond traditional neural networks. For developers and researchers working within the TensorFlow ecosystem, Spektral is the primary library for implementing graph deep learning. With a design philosophy rooted in the Keras API, Spektral allows users to build complex Graph Neural Networks (GNNs) without sacrificing the simplicity of high-level model definition. It provides the essential building blocks—convolutional layers, pooling operators, and data loaders—to transform raw graph data into actionable insights.

What Is Spektral?

Spektral is a Python library for graph deep learning based on the Keras API and TensorFlow 2. It is designed to provide a simple yet flexible framework for creating graph neural networks (GNNs) that can handle data described by graphs, such as social networks, molecular structures, and citation networks.

Maintained as an open-source project under the MIT License, Spektral integrates seamlessly with the TensorFlow ecosystem, allowing developers to use familiar Keras-style model.fit() and model.compile() workflows. It standardizes the representation of graphs through specialized containers, making it easier to manage node features, adjacency matrices, and edge attributes across large datasets.

Why Spektral Matters

Traditional deep learning models, like Convolutional Neural Networks (CNNs), are designed for Euclidean data (like images or text). However, much of the real world is non-Euclidean. When you try to flatten a graph into a vector, you lose the structural context—the “who is connected to whom”—which is often the most valuable part of the signal. Spektral fills this gap by providing specialized layers that can perform convolutions directly on the graph structure.

For those already invested in the TensorFlow/Keras stack, Spektral is the most accessible entry point into GNNs. While other libraries exist, Spektral’s commitment to the Keras API means that the learning curve is significantly lower for anyone who has built a standard dense or convolutional network. This makes it an ideal tool for rapid prototyping and academic research where quick iteration is key.

The library has gained significant traction in the scientific community, particularly in cheminformatics and social network analysis, due to its ability to handle both node-level and graph-level predictions efficiently.

Key Features

Spektral provides a comprehensive suite of tools for the entire GNN pipeline, from data ingestion to model deployment.

Convolutional Layers

  • Graph Convolutional Networks (GCN): Implements the standard spectral convolution for semi-supervised node classification.
  • Graph Attention Networks (GAT): Uses attention mechanisms to assign different weights to different neighbors in a neighborhood.
  • GraphSAGE: An inductive framework that samples and aggregates features from a node’s local neighborhood.
  • Chebyshev Convolutions: Provides a way to perform convolutions in the spectral domain using Chebyshev polynomials.
  • Edge-Conditioned Convolutions (ECC): Allows the convolution operation to be conditioned on edge features, which is critical for molecular graphs.
  • Graph Isomorphism Networks (GIN): Designed to be as powerful as the Weisfeiler-Lehman graph isomorphism test.

Pooling and Readout Operators

  • MinCut Pooling: A method for hierarchical graph clustering to reduce the size of the graph while preserving structure.
  • DiffPool: A differentiable pooling layer that learns to cluster nodes into a coarser graph.
  • Top-K Pooling: Selects the most important nodes based on a learned projection vector.
  • Global Pooling: Provides standard readout functions like global sum, mean, or max pooling to generate a single graph-level embedding.

Data Handling and Utilities

  • Graph and Dataset Containers: Standardizes how graph data (adjacency matrices, node features, labels) is stored and manipulated.
  • Loader Class: Abstracts the process of creating batches of graphs, which is essential for training on large-scale datasets.
  • Transforms Module: Offers a variety of common graph operations, such as adding self-loops or normalizing the adjacency matrix.

How Spektral Compares

When choosing a GNN library, the decision usually comes down to the backend framework. Spektral is the premier choice for TensorFlow users, while PyTorch Geometric (PyG) and DGL are the dominant forces in the PyTorch ecosystem.

Feature Spektral PyTorch Geometric (PyG) Deep Graph Library (DGL)
Backend Framework TensorFlow / Keras PyTorch PyTorch / TF / MXNet
Ease of Use High (Keras API) Medium Medium
Learning Curve Low Moderate Moderate
Performance (Training Speed) Moderate High High
API Style High-level / Declarative Object-Oriented Message-Passing

The primary tradeoff with Spektral is performance. Because it adheres so closely to the Keras API, it can be slower in training speeds for some complex tasks compared to the highly optimized C++ backends of DGL or the specialized kernels of PyG. However, for most researchers and developers, the gain in development speed—the time it takes to go from an idea to a working model—is more valuable than the raw training epoch time.

If you are already using TensorFlow for the rest of your pipeline, Spektral is the logical choice. It avoids the need to switch frameworks, which simplifies deployment and integration with TensorFlow Serving or TFLite.

Getting Started: Installation

Spektral is compatible with Python 3.6 and above and is tested on Ubuntu, MacOS, and Windows.

Via PyPI

The fastest way to get started is via pip:

pip install spektral

From Source

If you need the latest development version or wish to contribute, install from the GitHub repository:

git clone https://github.com/danielegrattarola/spektral.git
cd spektral
python setup.py install

Google Colab

For those using Colab notebooks, simply run the following in a cell:

! pip install spektral

Prerequisites: Spektral requires TensorFlow 2.x. Ensure your environment is correctly configured with a GPU if you are working with large graphs.

How to Use Spektral

The basic workflow in Spektral involves three main steps: defining your graph data, choosing a GNN architecture, and training the model using the Keras API.

First, you wrap your data in a Graph object. A Graph object in Spektral contains the adjacency matrix (a), node features (x), and labels (y). If you have multiple graphs, you use a Dataset container to manage them.

Next, you define your model. Because Spektral layers are Keras layers, you can use the Functional API or the Sequential API. You pass the node features and the adjacency matrix as a list of inputs to the convolutional layers.

Finally, you train the model using model.fit(). If you are using a Loader, Spektral handles the batching of graphs automatically, which prevents memory overflow when dealing with large datasets.

Code Examples

Below are examples of how to implement a simple GNN using Spektral, based on the library’s official documentation and examples.

Simple GCN Model

This example shows how to create a basic Graph Convolutional Network for node classification.

from spektral.layers import GCNConv
from spektral.models import GeneralGNN

class MyGNN(GeneralGNN):
    def __init__(self):
        super().__init__()
        self.conv1 = GCNConv(16, activation='relu')
        self.conv2 = GCNConv(2)

    def call(self, inputs):
        x, a = inputs
        x = self.conv1([x, a])
        x = self.conv2([x, a])
        return x

In this model, the GCNConv layer takes a list containing the node features x and the adjacency matrix a. The output is a new set of node embeddings that incorporate the structural information of the graph.

Custom Dataset Implementation

To use your own data, you inherit from the Dataset class and implement the read() method.

from spektral.data import Dataset, Graph

class MyCustomDataset(Dataset):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def read(self):
        # Load your data here
        # Return a list of Graph objects
        return [Graph(x=node_features, a=adj_matrix, y=labels)]

This allows Spektral to integrate your raw data into its standardized Loader and Graph containers, ensuring compatibility with the rest of the library.

Real-World Use Cases

Spektral is particularly effective in domains where the data is naturally represented as a graph and the structural relationships are critical for prediction.

  • Cheminformatics: Predicting the properties of a molecule. In this case, atoms are nodes and chemical bonds are edges. Spektral’s ECCConv (Edge-Conditioned Convolution) is used to handle the different types of bonds between atoms.
  • Social Network Analysis: Classifying users based on their interactions. For example, a company might use a GNN to identify potential churn risk by analyzing the connection patterns of a user and their neighbors in a social graph.
  • Traffic Forecasting: Modeling the flow of traffic on a road network. Road intersections are nodes and the roads connecting them are nodes. By using a spatio-temporal GNN, developers can predict congestion features based on the historical flow of neighboring road segments.
  • Citation Network Analysis: Categorizing technical papers based on their citations. This is a classic benchmark task where Spektral is used to classify the node (paper) into a specific research field based on its content and the citations it receives.

Contributing to Spektral

Spektral is an open-source project and contributions from the community are welcome. Because it is built on TensorFlow, contributors should be familiar with Keras and TensorFlow 2.x.

To contribute, you can report bugs by opening an issue on GitHub. If you have a new feature request, you can use the GitHub Discussions forum to propose the la idea. For those wishing to submit code, follow the standard GitHub flow: fork the repository, create a feature branch, and submit a pull request. The project maintains a CONTRIBUTING.md file that outlines the specific coding standards and submission guidelines.

Community and Support

Spektral’s community is primarily centered around GitHub. You can find the rest of the project’s resources here:

  • GitHub Repository: The main hub for source code, issue tracking, and version history.
  • GitHub Discussions: The official channel for asking questions, collaborating with the developer community, and discussing new features.
  • Official Documentation: A comprehensive guide and set of tutorials available at the project’s website, which includes a detailed API reference.
  • Examples Gallery: A collection of node-level and graph-level prediction templates that can be used as a starting point for projects.

Conclusion

Spektral is the ideal choice for developers who want to harness the power of Graph Neural Networks without leaving the TensorFlow/Keras ecosystem. By providing a high-level, user-friendly API that mirrors the Keras experience, it removes the majority of the friction associated with implementing GNNs.

While it may not be the fastest library in terms of raw training speed, its strength lies in its accessibility and rapid prototyping capabilities. If your goal is to move from a conceptual graph model to a working implementation in a few hours rather than a few days, Spektral is the right tool.

Star the repo, try the quickstart, and join the community to start building your first graph neural network today.

What is Spektral and what problem does it solve?

Spektral is a Python library for graph deep learning based on Keras and TensorFlow 2. It solves the problem of analyzing non-Euclidean data by providing specialized convolutional and pooling layers that can operate directly on graph structures, allowing for the same ease of use as standard Keras models.

How do I install Spektral?

You can install Spektral via PyPI using pip install spektral, or from source by cloning the GitHub repository and running python setup.py install. It requires TensorFlow 2.x to be installed in your environment.

How does Spektral compare to PyTorch Geometric?

The main difference is the backend framework: Spektral is built for TensorFlow/Keras, whereas PyTorch Geometric is built for PyTorch. While PyG often has a wider variety of message-passing methods and faster training speeds, Spektral offers a more declarative, high-level API that is easier for beginners to learn.

Can I use Spektral for molecular property prediction?

Spektral is highly effective for predicting molecular properties where atoms are nodes and bonds are edges, leveraging specialized layers like ECCConv (Edge-Conditioned Convolutions) and various pooling operators.

What is the difference between node-level and graph-level prediction?

Node-level prediction involves predicting a label for each individual node in a graph (e.g., classifying a user in a social network), while graph-level prediction involves aggregating the entire graph into a single embedding to predict a label for the whole graph (e.g., classifying a molecule as toxic or non-toxic).

Does Spektral support sparse matrices?

Yes, Spektral is designed to handle sparse adjacency matrices using the COOrdinate format, which is the most efficient way to represent large graphs in TensorFlow to avoid memory overflow.

Is Spektral open source?

Spektral is licensed under the MIT License, which allows for free use, modification, and distribution in both academic and research settings.