### Setup imports, dataset, and hyperparameters for benchmarking Source: https://github.com/akensert/molgraph/blob/main/examples/GNN-Benchmarking.ipynb Setup for benchmarking: suppress TensorFlow logging, import MolGraph layers and chemistry, TensorFlow/Keras, define the GNN layer type (GATConv), load a dataset (lipophilicity) and its config, and set hyperparameters. The commented kernel initializer line is optional. ```python import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' from pathlib import Path from molgraph import layers from molgraph import chemistry import tensorflow as tf from tensorflow import keras ``` ```python GNNConv = layers.GATConv ``` ```python dataset_name = 'lipophilicity' dataset_config = getattr(chemistry.benchmark.configs, dataset_name) dataset = chemistry.datasets.get(dataset_name) ``` ```python PATH = Path('./') NUM_EPOCHS = 300 BATCH_SIZE = 32 LR_INITIAL = 1e-4 LR_END = 1e-6 LR_PATIENCE = 10 LR_DECAY = 0.1 GNN_KWARGS = { 'units': 128, 'normalization': 'batch_norm', # 'kernel_initializer': keras.initializers.TruncatedNormal(stddev=0.005), } DNN_KWARGS = { 'units': 1024, 'activation': 'relu' } ``` -------------------------------- ### Build MolGraph documentation with pip and make Source: https://github.com/akensert/molgraph/blob/main/docs/README.md Install the documentation requirements and build the HTML documentation. The output can be viewed at build/html/index.html. ```bash pip install -r requirements make html open build/html/index.html ``` -------------------------------- ### Install MolGraph with pip Source: https://github.com/akensert/molgraph/blob/main/examples/GNN-Benchmarking.ipynb Install MolGraph. The first command installs the CPU version; the second adds GPU support. TensorFlow, Keras, and Pandas are installed automatically. ```shell pip install molgraph ``` ```shell pip install molgraph[gpu] ``` -------------------------------- ### Install MolGraph for CPU via pip Source: https://github.com/akensert/molgraph/blob/main/docs/source/get_started/installation.rst Install the CPU version of MolGraph using pip. This is the standard installation for users without GPU support. ```bash pip install molgraph ``` -------------------------------- ### Install MolGraph for GPU via pip Source: https://github.com/akensert/molgraph/blob/main/docs/source/get_started/installation.rst Install the GPU version of MolGraph using pip. This includes additional dependencies for GPU acceleration. ```bash pip install molgraph[gpu] ``` -------------------------------- ### First MolGraph program: build and train a GNN model Source: https://github.com/akensert/molgraph/blob/main/docs/source/get_started/installation.rst Complete example showing how to use MolGraph with TensorFlow/Keras. It loads the ESOL dataset, featurizes molecules, builds a GNN model with GATConv layers, trains it, evaluates it, and computes gradient activation maps. ```python from tensorflow import keras from molgraph import chemistry from molgraph import layers from molgraph import models # Obtain dataset, specifically ESOL esol = chemistry.datasets.get('esol') # Define molecular graph encoder atom_encoder = chemistry.Featurizer([ chemistry.features.Symbol(), chemistry.features.Hybridization(), # ... ]) bond_encoder = chemistry.Featurizer([ chemistry.features.BondType(), # ... ]) encoder = chemistry.MolecularGraphEncoder(atom_encoder, bond_encoder) # Obtain features and associated labels x_train = encoder(esol['train']['x']) y_train = esol['train']['y'] x_test = encoder(esol['test']['x']) y_test = esol['test']['y'] # Build model via Keras API gnn_model = keras.Sequential([ layers.GATConv(units=32, name='gat_conv_1'), layers.GATConv(units=32, name='gat_conv_2'), layers.Readout(), keras.layers.Dense(units=1024, activation='relu'), keras.layers.Dense(units=y_train.shape[-1]) ]) # Compile, fit and evaluate gnn_model.compile(optimizer='adam', loss='mae') gnn_model.fit(x_train, y_train, epochs=50) scores = gnn_model.evaluate(x_test, y_test) # Compute gradient activation maps gam_model = models.GradientActivationMapping(gnn_model) maps = gam_model(x_train.separate()) ``` -------------------------------- ### Import molgraph chemistry and dependencies Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/walk_through/02_molecules.ipynb Imports the molgraph chemistry module, TensorFlow, and matplotlib for the examples in this notebook. ```python from molgraph import chemistry import tensorflow as tf import matplotlib.pyplot as plt ``` -------------------------------- ### Proteomics brief example with PeptideModel and PeptideSaliency Source: https://github.com/akensert/molgraph/blob/main/molgraph/applications/proteomics/README.md Shows the core workflow for building a peptide graph encoder, model, and saliency calculator. Requires atom and bond featurizers with their symbol sets. Note that saliency values include super nodes only when `super_nodes=True`. ```python from molgraph import chemistry from molgraph.applications import proteomics atom_encoder = chemistry.Featurizer([ chemistry.features.Symbol({'C', 'N', 'O', 'S', 'P'}, oov_size=1) ]) bond_encoder = chemistry.Featurizer([ chemistry.features.BondType({'AROMATIC', 'TRIPLE', 'DOUBLE', 'SINGLE'}, oov_size=1), ]) encoder = proteomics.PeptideGraphEncoder(atom_encoder, bond_encoder, super_nodes=True) # Example input: peptide_graph = encoder(['CYIQNCPLG']) # Create model (keras.Sequential instance) model = proteomics.PeptideModel(config=None, spec=peptide_graph.spec) # Predict input prediction = model(peptide_graph) # generate more inputs ... # train model on inputs ... saliency = proteomics.PeptideSaliency(model) # Will include saliency values of super nodes if `super_nodes=True` saliency_values = saliency(peptide_graph.separate()) ``` -------------------------------- ### Build a Graph Neural Network with Keras Sequential API Source: https://github.com/akensert/molgraph/blob/main/README.md Constructs a minimal GNN model using Keras' Sequential API with MolGraph's GraphTensor and layers. The example defines a graph with two nodes and one edge, then passes it through a GNNInput layer. Requires TensorFlow and Keras imports from molgraph. ```python from molgraph import GraphTensor from molgraph import layers from tensorflow import keras g = GraphTensor(node_feature=[[4.], [2.]], edge_src=[0], edge_dst=[1]) model = keras.Sequential([ layers.GNNInput(type_spec=g.spec), ]) ``` -------------------------------- ### Import libraries and set path Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/tutorials/06_benchmark-DTNN-QM7.ipynb Imports required libraries and adds the project root to the Python path for the benchmark tutorial. ```python import sys sys.path.append('../../../../') import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import keras from molgraph.chemistry.benchmark import configs from molgraph.chemistry.benchmark import tf_records from molgraph.chemistry import datasets ``` -------------------------------- ### Import MolGraph, Keras, TensorFlow, and Pandas Source: https://github.com/akensert/molgraph/blob/main/examples/QSAR-GNN-Tutorial.ipynb Import the necessary libraries for the tutorial: MolGraph's chemistry, layers, and losses modules, plus Keras, TensorFlow, and Pandas. ```python from molgraph import chemistry from molgraph import layers from molgraph import losses import keras import tensorflow as tf import pandas as pd ``` -------------------------------- ### Import required libraries and modules Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/tutorials/05_benchmark-GAT-ESOL.ipynb Sets up the Python environment by adding the project path to sys.path and importing necessary libraries including pandas, numpy, matplotlib, tensorflow, and molgraph modules for benchmarking, datasets, losses, and metrics. ```python import sys sys.path.append('../../../../') import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import keras from molgraph.chemistry.benchmark import configs from molgraph.chemistry.benchmark import tf_records from molgraph.chemistry import datasets from molgraph.losses import masked_losses from molgraph.metrics import masked_metrics ``` -------------------------------- ### Compile, train, and evaluate MyModel Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/walk_through/03_layers_and_models.ipynb Compiles the model with 'adam' optimizer, 'mse' loss, and 'mae' metric, then fits it on training data for 30 epochs with verbose output. Finally evaluates on test data and prints the MSE and MAE values. ```python my_model.compile('adam', 'mse', ['mae']) my_model.fit(x_train, y_train, epochs=30, verbose=2) mse, mae = my_model.evaluate(x_test, y_test) print(f"{mse = :.3f}\n{mae = :.3f}") ``` ```text Output: Epoch 1/30 25/25 - 4s - loss: 6.9835 - mae: 2.0324 - 4s/epoch - 154ms/step Epoch 2/30 25/25 - 0s - loss: 3.5191 - mae: 1.4901 - 130ms/epoch - 5ms/step Epoch 3/30 25/25 - 0s - loss: 3.0028 - mae: 1.3773 - 127ms/epoch - 5ms/step Epoch 4/30 25/25 - 0s - loss: 3.0950 - mae: 1.4046 - 127ms/epoch - 5ms/step Epoch 5/30 25/25 - 0s - loss: 3.0432 - mae: 1.3907 - 124ms/epoch - 5ms/step Epoch 6/30 25/25 - 0s - loss: 2.8056 - mae: 1.3432 - 134ms/epoch - 5ms/step Epoch 7/30 25/25 - 0s - loss: 2.4625 - mae: 1.2536 - 135ms/epoch - 5ms/step Epoch 8/30 25/25 - 0s - loss: 2.3279 - mae: 1.2204 - 134ms/epoch - 5ms/step Epoch 9/30 25/25 - 0s - loss: 2.0883 - mae: 1.1648 - 165ms/epoch - 7ms/step Epoch 10/30 25/25 - 0s - loss: 1.7619 - mae: 1.0528 - 214ms/epoch - 9ms/step Epoch 11/30 25/25 - 0s - loss: 1.5656 - mae: 0.9921 - 185ms/epoch - 7ms/step Epoch 12/30 25/25 - 0s - loss: 1.5067 - mae: 0.9590 - 163ms/epoch - 7ms/step Epoch 13/30 25/25 - 0s - loss: 1.3769 - mae: 0.9156 - 154ms/epoch - 6ms/step Epoch 14/30 25/25 - 0s - loss: 1.3757 - mae: 0.9190 - 125ms/epoch - 5ms/step Epoch 15/30 25/25 - 0s - loss: 1.2272 - mae: 0.8522 - 131ms/epoch - 5ms/step Epoch 16/30 25/25 - 0s - loss: 1.3874 - mae: 0.9079 - 127ms/epoch - 5ms/step Epoch 17/30 25/25 - 0s - loss: 1.2847 - mae: 0.8731 - 129ms/epoch - 5ms/step Epoch 18/30 25/25 - 0s - loss: 1.0207 - mae: 0.7711 - 126ms/epoch - 5ms/step Epoch 19/30 25/25 - 0s - loss: 0.9642 - mae: 0.7421 - 125ms/epoch - 5ms/step Epoch 20/30 25/25 - 0s - loss: 1.0932 - mae: 0.8059 - 128ms/epoch - 5ms/step Epoch 21/30 25/25 - 0s - loss: 1.3735 - mae: 0.8976 - 126ms/epoch - 5ms/step Epoch 22/30 25/25 - 0s - loss: 0.9599 - mae: 0.7704 - 124ms/epoch - 5ms/step Epoch 23/30 25/25 - 0s - loss: 0.9566 - mae: 0.7487 - 122ms/epoch - 5ms/step Epoch 24/30 25/25 - 0s - loss: 1.0032 - mae: 0.7642 - 127ms/epoch - 5ms/step Epoch 25/30 25/25 - 0s - loss: 1.1856 - mae: 0.8178 - 117ms/epoch - 5ms/step Epoch 26/30 25/25 - 0s - loss: 1.0833 - mae: 0.7991 - 125ms/epoch - 5ms/step Epoch 27/30 25/25 - 0s - loss: 0.9256 - mae: 0.7378 - 124ms/epoch - 5ms/step Epoch 28/30 25/25 - 0s - loss: 0.8480 - mae: 0.6993 - 126ms/epoch - 5ms/step Epoch 29/30 25/25 - 0s - loss: 1.0073 - mae: 0.7551 - 125ms/epoch - 5ms/step Epoch 30/30 25/25 - 0s - loss: 0.8465 - mae: 0.6929 - 126ms/epoch - 5ms/step 11/11 [==============================] - 0s 3ms/step - loss: 0.7891 - mae: 0.6715 mse = 0.789 mae = 0.672 ``` -------------------------------- ### Extract atom and bond features with RDKit Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/walk_through/02_molecules.ipynb Uses the RDKit API to get the first atom and bond, then applies chemistry.features.Symbol and chemistry.features.BondType to extract their features. The output shows the symbol 'O' and bond type 'SINGLE'. ```python # Obtain RDKit atom and bond via the RDKit API atom = rdkit_mol.GetAtoms()[0] bond = rdkit_mol.GetBonds()[0] symbol_feature = chemistry.features.Symbol() bondtype_feature = chemistry.features.BondType() print('Symbol: ', symbol_feature(atom)) print('BondType:', bondtype_feature(bond)) ``` ```text Output: Symbol: O BondType: SINGLE ``` -------------------------------- ### Set up input pipelines from data using tf.data.Dataset Source: https://github.com/akensert/molgraph/blob/main/examples/QSAR-GNN-Tutorial.ipynb Creates TensorFlow datasets from graph tensors and labels, applying shuffling, batching, and prefetching for training, validation, and test sets. ```python train_data = (train_graph, y_train, m_train) val_data = (val_graph, y_val, m_val) test_data = (test_graph, y_test, m_test) train_ds = ( tf.data.Dataset.from_tensor_slices(train_data) .shuffle(1024) .batch(32) .prefetch(-1) ) val_ds = ( tf.data.Dataset.from_tensor_slices(val_data) .batch(32) .prefetch(-1) ) test_ds = ( tf.data.Dataset.from_tensor_slices(test_data) .batch(32) .prefetch(-1) ) ``` -------------------------------- ### Compile, fit, and evaluate sequential model Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/walk_through/03_layers_and_models.ipynb Compiles the model with 'adam' optimizer, 'mse' loss, and 'mae' metric, then fits for 30 epochs with verbose=2 and evaluates on test data, printing mse and mae. ```python sequential_model.compile('adam', 'mse', ['mae']) sequential_model.fit(x_train, y_train, epochs=30, verbose=2) mse, mae = sequential_model.evaluate(x_test, y_test) print(f"{mse = :.3f}\n{mae = :.3f}") ``` -------------------------------- ### Print GraphTensor components Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/walk_through/02_molecules.ipynb Prints the individual components of the GraphTensor returned by the encoder: node_feature, edge_feature, edge_dst, and edge_src. The output shows the exact tensor values and shapes for the three-molecule example, with node_feature shape (37, 3), edge_feature shape (76, 2), and edge indices shape (76,). ```python print('node_feature:', graph_tensor.node_feature, end='\n\n') print('edge_feature:', graph_tensor.edge_feature, end='\n\n') print('edge_dst:', graph_tensor.edge_dst, end='\n\n') print('edge_src:', graph_tensor.edge_src, end='\n\n') ``` ```text Output: node_feature: tf.Tensor( [[0. 0. 1.] [1. 0. 0.] [1. 0. 0.] [0. 0. 1.] [1. 0. 0.] [1. 0. 0.] [1. 0. 0.] [0. 0. 1.] [0. 0. 1.] [0. 1. 0.] [1. 0. 0.] [0. 1. 0.] [1. 0. 0.] [1. 0. 0.] [0. 1. 0.] [1. 0. 0.] [0. 1. 0.] [1. 0. 0.] [0. 1. 0.] [1. 0. 0.] [1. 0. 0.] [0. 0. 1.] [0. 0. 1.] [0. 1. 0.] [1. 0. 0.] [1. 0. 0.] [1. 0. 0.] [1. 0. 0.] [1. 0. 0.] [1. 0. 0.] [1. 0. 0.] [1. 0. 0.] [1. 0. 0.] [0. 0. 1.] [0. 0. 1.] [0. 1. 0.] [0. 0. 1.]], shape=(37, 3), dtype=float32) edge_feature: tf.Tensor( [[0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [1. 0.] [0. 1.] [1. 0.] [0. 1.] [0. 1.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 1.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [0. 1.] [1. 0.] [0. 1.] [1. 0.] [0. 1.] [0. 1.] [0. 1.]], shape=(76, 2), dtype=float32) edge_dst: tf.Tensor( [ 1 0 2 1 3 6 2 4 3 5 9 4 6 8 2 5 7 6 5 4 10 13 9 11 10 12 11 13 17 9 12 14 13 15 14 16 15 17 12 16 18 17 20 23 19 21 22 20 20 19 25 29 24 26 25 27 36 26 28 27 29 24 28 30 29 31 30 32 35 31 33 34 32 32 31 26], shape=(76,), dtype=int32) edge_src: tf.Tensor( [ 0 1 1 2 2 2 3 3 4 4 4 5 5 5 6 6 6 7 8 9 9 9 10 10 11 11 12 12 12 13 13 13 14 14 15 15 16 16 17 17 17 18 19 19 20 20 20 21 22 23 24 24 25 25 26 26 26 27 27 28 28 29 29 29 30 30 31 31 31 32 32 32 33 34 35 36], shape=(76,), dtype=int32) ``` -------------------------------- ### Benchmark models on dataset: write/load TF records, build, train, evaluate Source: https://github.com/akensert/molgraph/blob/main/examples/GNN-Benchmarking.ipynb Complete workflow for benchmarking a GNN model: writes and loads TF records for each dataset subset, builds a sequential model with preprocessing and GNN layers, then trains and evaluates it. Includes data shuffling, batching, and callbacks for learning rate reduction and early stopping. ```python # Write and load tf records: data = {} for subset_name, subset in dataset.items(): path = PATH / f'cache/tf_records/{dataset_name}/{subset_name}/' with record_writer(path) as writer: writer.write(subset, encoder) keys = list(subset.keys()) keys.remove('index') data[subset_name] = record_loader( path=path, extract_tuple=keys, shuffle_tf_records=True if subset_name == 'train' else False) if subset_name == 'train': data[subset_name] = data[subset_name].shuffle(4096) data[subset_name] = data[subset_name].batch(BATCH_SIZE).prefetch(-1) # Build model: node_preprocessing = layers.NodeMinMaxScaling( feature_range=(0, 1), threshold=True) edge_preprocessing = layers.EdgeMinMaxScaling( feature_range=(0, 1), threshold=True) node_preprocessing.adapt(data['train'].map(lambda x, *args: x)) edge_preprocessing.adapt(data['train'].map(lambda x, *args: x)) model = tf.keras.Sequential([ layers.GNNInput(type_spec=data['train'].element_spec[0]), node_preprocessing, edge_preprocessing, layers.LaplacianPositionalEncoding(), GNNConv(**GNN_KWARGS), GNNConv(**GNN_KWARGS), GNNConv(**GNN_KWARGS), layers.Readout(), keras.layers.Dense(**DNN_KWARGS), keras.layers.Dense(**DNN_KWARGS), keras.layers.Dense( units=dataset_config['num_tasks'], activation='sigmoid' if dataset_config['task_type'] == 'classification' else 'linear' ) ]) # Train and evaluate model: optimizer = keras.optimizers.Adam(LR_INITIAL) loss = keras.losses.deserialize(dataset_config['loss']) metrics = [keras.metrics.deserialize(dataset_config['metric'])] callbacks_list = [ keras.callbacks.ReduceLROnPlateau( monitor='val_' + metrics[0].name, factor=LR_DECAY, patience=LR_PATIENCE, min_lr=LR_END, mode='min' if not metrics[0].name.endswith('auc') else 'max', ), keras.callbacks.EarlyStopping( monitor='val_' + metrics[0].name, patience=LR_PATIENCE * 2, mode='min' if not metrics[0].name.endswith('auc') else 'max', restore_best_weights=True, ) ] model.compile(optimizer, loss, metrics) history = model.fit( data['train'], validation_data=data['validation'], epochs=NUM_EPOCHS, callbacks=callbacks_list, verbose=2) result = model.evaluate(data['test'], verbose=2) ``` -------------------------------- ### Download and load ESOL dataset Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/walk_through/03_layers_and_models.ipynb Downloads the ESOL dataset from a URL and loads it into a pandas DataFrame, then displays the first three rows. ```python path = tf.keras.utils.get_file( fname='ESOL.csv', origin='http://deepchem.io.s3-website-us-west-1.amazonaws.com/datasets/ESOL.csv', ) df = pd.read_csv(path) df.head(3) ``` -------------------------------- ### Visualize activation maps on molecule with vis.visualize_maps Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/walk_through/04_activation_maps.ipynb Imports the visualization module and visualizes the activation maps on molecule 42 from the dataset with the corresponding maps from the gradient activation mapping. The result is a PIL image object of 360x360 pixels. ```python from molgraph.chemistry import vis vis.visualize_maps(molecule=x[42], maps=gam[42]) ``` ```text Result: ``` -------------------------------- ### Build and train GAT model with preprocessing and callbacks Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/tutorials/05_benchmark-GAT-ESOL.ipynb Constructs a Sequential model with MinMaxScaling preprocessing layers, LaplacianPositionalEncoding, three GATConv layers with batch normalization, a Readout layer, and dense layers. Compiles with Adam optimizer and MAE loss, then trains for 100 epochs with ReduceLROnPlateau and EarlyStopping callbacks. Finally evaluates on the test set and prints the score. ```python from molgraph.layers import GATConv from molgraph.layers import LaplacianPositionalEncoding from molgraph.layers import Readout from molgraph.layers import MinMaxScaling node_preprocessing = MinMaxScaling( feature='node_feature', feature_range=(0, 1), threshold=True) edge_preprocessing = MinMaxScaling( feature='edge_feature', feature_range=(0, 1), threshold=True) node_preprocessing.adapt(train_ds.map(lambda x, *args: x)) edge_preprocessing.adapt(train_ds.map(lambda x, *args: x)) model = tf.keras.Sequential([ keras.layers.Input(type_spec=type_spec), node_preprocessing, edge_preprocessing, LaplacianPositionalEncoding(), GATConv(normalization='batch_norm'), GATConv(normalization='batch_norm'), GATConv(normalization='batch_norm'), Readout(), keras.layers.Dense(1024, 'relu'), keras.layers.Dense(1024, 'relu'), keras.layers.Dense(y_train.shape[-1]) ]) optimizer = keras.optimizers.Adam(1e-4) loss = keras.losses.MeanAbsoluteError(name='mae') callbacks = [ keras.callbacks.ReduceLROnPlateau( monitor=f'val_loss', factor=0.1, patience=10, min_lr=1e-6, mode='min', ), keras.callbacks.EarlyStopping( monitor=f'val_loss', patience=20, mode='min', restore_best_weights=True, ) ] model.compile(optimizer, loss) history = model.fit( train_ds, callbacks=callbacks, validation_data=val_ds, epochs=100, verbose=2, ) score = model.evaluate(test_ds) print(score) ``` -------------------------------- ### Create TensorFlow datasets for training and testing Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/walk_through/03_layers_and_models.ipynb Prepares training and test datasets using tf.data.Dataset.from_tensor_slices. The training dataset is shuffled with a buffer size of 800 and batched with a batch size of 32; the test dataset is batched with the same size but not shuffled. ```python ds_train = tf.data.Dataset.from_tensor_slices((x_train, y_train)) ds_train = ds_train.shuffle(800).batch(32) ds_test = tf.data.Dataset.from_tensor_slices((x_test, y_test)) ds_test = ds_test.batch(32) ``` -------------------------------- ### Configure Featurizer and MolecularGraphEncoder3D Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/tutorials/06_benchmark-DTNN-QM7.ipynb Creates a Featurizer with a list of atomic features and a MolecularGraphEncoder3D configured for the QM7 dataset, using pre-encoded conformers and Coulomb matrix edges. ```python from molgraph.chemistry import features from molgraph.chemistry import Featurizer from molgraph.chemistry import MolecularGraphEncoder3D atom_encoder = Featurizer([ features.Symbol(), features.Hybridization(), features.FormalCharge(), features.TotalNumHs(), features.TotalValence(), features.NumRadicalElectrons(), features.Degree(), features.ChiralCenter(), features.Aromatic(), features.Ring(), features.Hetero(), features.HydrogenDonor(), features.HydrogenAcceptor(), features.CIPCode(), features.ChiralCenter(), features.RingSize(), features.Ring(), features.CrippenLogPContribution(), features.CrippenMolarRefractivityContribution(), features.TPSAContribution(), features.LabuteASAContribution(), features.GasteigerCharge(), ]) encoder = MolecularGraphEncoder3D( atom_encoder, conformer_generator=None, # qm7 encodes conformers edge_radius=None, # max radius coulomb=True, ) ``` -------------------------------- ### Hetero Source: https://github.com/akensert/molgraph/blob/main/docs/source/api/chemistry.rst Documentation for the Hetero feature. ```APIDOC ## Hetero ### Description Feature for hetero atoms. Inherits from `Feature` and is callable via `__call__`. ### Method `__call__` ### Parameters - **input** (object) - Required - Input to be processed. ### Returns - Hetero feature value. ``` -------------------------------- ### Compile and fit GNN model with Keras-style API Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/walk_through/04_activation_maps.ipynb Compiles the GNN model with the Adam optimizer and mean squared error loss, tracking MAE, then fits it for 50 epochs. The output shows decreasing loss and MAE over training. ```python sequential_model.compile('adam', 'mse', ['mae']) sequential_model.fit(x_data, y, epochs=50, verbose=2); ``` ```text Epoch 1/50 36/36 - 3s - loss: 4.2682 - mae: 1.6230 - 3s/epoch - 84ms/step Epoch 2/50 36/36 - 0s - loss: 3.3620 - mae: 1.4817 - 179ms/epoch - 5ms/step ... Epoch 50/50 36/36 - 0s - loss: 1.2962 - mae: 0.8538 - 179ms/epoch - 5ms/step ``` -------------------------------- ### Train, validate, and evaluate QSAR model Source: https://github.com/akensert/molgraph/blob/main/examples/QSAR-GNN-Tutorial.ipynb Sets up callbacks for learning rate reduction and early stopping based on val_auc, optionally adds TensorBoard logging, then fits the model on train_ds with validation_data and 100 epochs. Finally evaluates on test_ds and unpacks BCE loss and AUC score. ```python callbacks = [ keras.callbacks.ReduceLROnPlateau( monitor="val_auc", patience=10, mode="max" ), keras.callbacks.EarlyStopping( monitor="val_auc", patience=20, mode="max", restore_best_weights=True ), ] # May slow down training time callbacks += [ keras.callbacks.TensorBoard( log_dir="./logs", histogram_freq=1) ] qsar_model.fit( train_ds, callbacks=callbacks, validation_data=val_ds, epochs=100, ) bce_loss, auc_score = qsar_model.evaluate(test_ds) ``` -------------------------------- ### Training and evaluation output Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/walk_through/03_layers_and_models.ipynb Shows the training progress over 30 epochs, with loss and MAE decreasing, and the final evaluation metrics: MSE = 0.645 and MAE = 0.604. ```text Epoch 1/30 25/25 - 4s - loss: 2.0662 - mae: 1.1023 - 4s/epoch - 169ms/step Epoch 2/30 25/25 - 0s - loss: 0.9658 - mae: 0.7642 - 146ms/epoch - 6ms/step Epoch 3/30 25/25 - 0s - loss: 0.7833 - mae: 0.6706 - 193ms/epoch - 8ms/step Epoch 4/30 25/25 - 0s - loss: 0.8129 - mae: 0.6789 - 224ms/epoch - 9ms/step Epoch 5/30 25/25 - 0s - loss: 0.7564 - mae: 0.6587 - 160ms/epoch - 6ms/step Epoch 6/30 25/25 - 0s - loss: 0.6944 - mae: 0.6358 - 167ms/epoch - 7ms/step Epoch 7/30 25/25 - 0s - loss: 0.7331 - mae: 0.6370 - 152ms/epoch - 6ms/step Epoch 8/30 25/25 - 0s - loss: 0.7645 - mae: 0.6606 - 156ms/epoch - 6ms/step Epoch 9/30 25/25 - 0s - loss: 0.7225 - mae: 0.6401 - 176ms/epoch - 7ms/step Epoch 10/30 25/25 - 0s - loss: 0.6720 - mae: 0.6212 - 176ms/epoch - 7ms/step Epoch 11/30 25/25 - 0s - loss: 0.6687 - mae: 0.6162 - 140ms/epoch - 6ms/step Epoch 12/30 25/25 - 0s - loss: 0.7627 - mae: 0.6656 - 139ms/epoch - 6ms/step Epoch 13/30 25/25 - 0s - loss: 0.8233 - mae: 0.6914 - 184ms/epoch - 7ms/step Epoch 14/30 25/25 - 0s - loss: 0.6556 - mae: 0.6026 - 136ms/epoch - 5ms/step Epoch 15/30 25/25 - 0s - loss: 0.7744 - mae: 0.6573 - 184ms/epoch - 7ms/step Epoch 16/30 25/25 - 0s - loss: 0.8383 - mae: 0.6919 - 139ms/epoch - 6ms/step Epoch 17/30 25/25 - 0s - loss: 0.7492 - mae: 0.6450 - 137ms/epoch - 5ms/step Epoch 18/30 25/25 - 0s - loss: 0.5925 - mae: 0.5758 - 139ms/epoch - 6ms/step Epoch 19/30 25/25 - 0s - loss: 0.5963 - mae: 0.5831 - 153ms/epoch - 6ms/step Epoch 20/30 25/25 - 0s - loss: 0.6683 - mae: 0.6151 - 133ms/epoch - 5ms/step Epoch 21/30 25/25 - 0s - loss: 0.7187 - mae: 0.6552 - 136ms/epoch - 5ms/step Epoch 22/30 25/25 - 0s - loss: 0.6949 - mae: 0.6189 - 137ms/epoch - 5ms/step Epoch 23/30 25/25 - 0s - loss: 0.6306 - mae: 0.5957 - 134ms/epoch - 5ms/step Epoch 24/30 25/25 - 0s - loss: 0.5399 - mae: 0.5503 - 142ms/epoch - 6ms/step Epoch 25/30 25/25 - 0s - loss: 0.5650 - mae: 0.5578 - 137ms/epoch - 5ms/step Epoch 26/30 25/25 - 0s - loss: 0.6170 - mae: 0.5973 - 143ms/epoch - 6ms/step Epoch 27/30 25/25 - 0s - loss: 0.5971 - mae: 0.5838 - 136ms/epoch - 5ms/step Epoch 28/30 25/25 - 0s - loss: 0.5966 - mae: 0.5822 - 133ms/epoch - 5ms/step Epoch 29/30 25/25 - 0s - loss: 0.5543 - mae: 0.5507 - 132ms/epoch - 5ms/step Epoch 30/30 25/25 - 0s - loss: 0.6288 - mae: 0.5837 - 139ms/epoch - 6ms/step 11/11 [==============================] - 0s 2ms/step - loss: 0.6447 - mae: 0.6042 mse = 0.645 mae = 0.604 ``` -------------------------------- ### Configure BondType feature arguments Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/walk_through/02_molecules.ipynb Shows the default BondType feature and a custom one with a restricted allowable_set, oov_size=1, and ordinal=False. The output displays the feature configurations. ```python print(chemistry.features.BondType()) print(chemistry.features.BondType(allowable_set=['SINGLE', 'DOUBLE'], oov_size=1, ordinal=False)) ``` ```text Output: BondType(allowable_set={'DOUBLE', 'TRIPLE', 'AROMATIC', 'SINGLE'}, ordinal=False, oov_size=0) BondType(allowable_set=['SINGLE', 'DOUBLE'], ordinal=False, oov_size=1) ``` -------------------------------- ### Compile, train, and evaluate sequential model Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/walk_through/03_layers_and_models.ipynb Compiles the sequential_model with the Adam optimizer, mean squared error loss, and mean absolute error metric. Trains for 30 epochs on the training dataset with verbose output, then evaluates on the test data and prints the MSE and MAE. ```python sequential_model.compile('adam', 'mse', ['mae']) sequential_model.fit(ds_train, epochs=30, verbose=2) mse, mae = sequential_model.evaluate(x_test, y_test) print(f"{mse = :.3f}\n{mae = :.3f}") ``` -------------------------------- ### CIPCode Source: https://github.com/akensert/molgraph/blob/main/docs/source/api/chemistry.rst Documentation for the CIPCode feature. ```APIDOC ## CIPCode ### Description Feature for CIP code. Inherits from `Feature` and is callable via `__call__`. ### Method `__call__` ### Parameters - **input** (object) - Required - Input to be processed. ### Returns - CIP code feature value. ``` -------------------------------- ### RingSize Source: https://github.com/akensert/molgraph/blob/main/docs/source/api/chemistry.rst Documentation for the RingSize feature. ```APIDOC ## RingSize ### Description Feature for ring size. Inherits from `Feature` and is callable via `__call__`. ### Method `__call__` ### Parameters - **input** (object) - Required - Input to be processed. ### Returns - Ring size feature value. ``` -------------------------------- ### Import libraries for MPNN benchmark Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/tutorials/07_benchmark-MPNN-Tox21.ipynb Imports required libraries including molgraph modules for chemistry, benchmarks, and losses, as well as TensorFlow and pandas. ```python import sys sys.path.append('../../../../') import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import keras from molgraph.chemistry.benchmark import configs from molgraph.chemistry.benchmark import tf_records from molgraph.chemistry import datasets from molgraph.losses import MaskedBinaryCrossentropy ``` -------------------------------- ### Create TensorFlow datasets for training, validation, and testing Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/tutorials/05_benchmark-GAT-ESOL.ipynb Builds tf.data.Dataset objects from the encoded tensors. The training dataset is shuffled with a buffer size of 1024 and batched with size 32, while validation and test datasets are batched without shuffling. All use prefetch for performance. ```python train_ds = ( tf.data.Dataset.from_tensor_slices((x_train, y_train)) .shuffle(1024) .batch(32) .prefetch(-1) ) val_ds = ( tf.data.Dataset.from_tensor_slices((x_val, y_val)) .batch(32) .prefetch(-1) ) test_ds = ( tf.data.Dataset.from_tensor_slices((x_test, y_test)) .batch(32) .prefetch(-1) ) ``` -------------------------------- ### GradientActivationMapping Source: https://github.com/akensert/molgraph/blob/main/docs/source/api/models.rst Interpretability model for gradient activation mapping. Users can call the build method and the __call__ special method. ```APIDOC ## GradientActivationMapping ### Description Interpretability model for gradient activation mapping. ### Class `molgraph.models.GradientActivationMapping(tensorflow.Module)` ### Methods - `build` - `__call__` ``` -------------------------------- ### ConformerGenerator Source: https://github.com/akensert/molgraph/blob/main/docs/source/api/chemistry.rst Documentation for the ConformerGenerator class, which generates conformers. ```APIDOC ## ConformerGenerator ### Description Generates conformers for molecular graphs. Provides methods for available embedding and force field methods, and is callable via `__call__`. ### Methods - `available_embedding_methods` - Returns available embedding methods. - `available_force_field_methods` - Returns available force field methods. - `__call__` - Generates conformers. ### Parameters - **input** (object) - Required - Input for conformer generation. ### Returns - Generated conformers. ``` -------------------------------- ### Run doctests on a specific API reference file with sphinx-build Source: https://github.com/akensert/molgraph/blob/main/docs/README.md Run doctests on the specified API reference file (e.g., layers.rst). Replace 'layers.rst' with another file like 'models.rst' to test its docstrings. ```bash sphinx-build -M doctest "source" "build" source/api/layers.rst ``` -------------------------------- ### DatasetFactory Source: https://github.com/akensert/molgraph/blob/main/docs/source/api/chemistry.rst Documentation for the DatasetFactory class. ```APIDOC ## DatasetFactory ### Description Factory for creating benchmark datasets. ### Methods - `get` - Retrieves a dataset. - `get_config` - Gets configuration. - `registered_datasets` - Lists registered datasets. ### Parameters - **name** (str) - Required - Name of the dataset. - **config** (dict) - Optional - Configuration for the dataset. ### Returns - Dataset object. ``` -------------------------------- ### Import GNN layers from molgraph Source: https://github.com/akensert/molgraph/blob/main/docs/source/examples/walk_through/03_layers_and_models.ipynb Imports the layers module from molgraph to access GNN layers. ```python from molgraph import layers ```