<jupyter_start><jupyter_text>Stellargraph example: directed CORA citation network with directed GraphSAGE and Neo4J.This example shows the application of *directed* GraphSAGE to a *directed* graph, where the in-node and out-node neighbourhoods are separately sampled and have different weights.Subgraphs are sampled directly from Neo4J, which eliminate the need to store the whole graph structure in NetworkX. Node features, however, still need to be loaded in memory. Run the master version of this notebook:<jupyter_code># install StellarGraph if running on Google Colab
import sys
if 'google.colab' in sys.modules:
  %pip install -q stellargraph[demos]
# verify that we're using the correct version of StellarGraph for this notebook
import stellargraph as sg

try:
    sg.utils.validate_notebook_version("1.0.0b")
except AttributeError:
    raise ValueError(
        f"This notebook requires StellarGraph version 1.0.0b, but a different version {sg.__version__} is installed.  Please see <https://github.com/stellargraph/stellargraph/issues/1172>."
    ) from None
import pandas as pd
import numpy as np
import os

import stellargraph as sg
from stellargraph.connector.neo4j import Neo4JDirectedGraphSAGENodeGenerator
from stellargraph.layer import DirectedGraphSAGE

from tensorflow.keras import layers, optimizers, losses, metrics, Model
from sklearn import preprocessing, feature_extraction, model_selection

import time
%matplotlib inline<jupyter_output><empty_output><jupyter_text>Loading the CORA data from Neo4JIt is assumed that the cora dataset has already been loaded into Neo4J. [This notebook](./load-cora-into-neo4j.ipynb) demonstrates how to load cora dataset into Neo4J.It is still required to load the node features into memory. We use ```py2neo```, which provides tools to connect to Neo4J databases from Python applications. ```py2neo``` documentation could be found [here](https://py2neo.org/v4/).<jupyter_code>import py2neo

default_host = os.environ.get("STELLARGRAPH_NEO4J_HOST")

# Create the Neo4J Graph database object; the arguments can be edited to specify location and authentication
neo4j_graphdb = py2neo.Graph(host=default_host, port=None, user=None, password=None)
def get_node_data_from_neo4j(neo4j_graphdb):
    fetch_node_query = "MATCH (node) RETURN id(node), properties(node)"
    # run the query
    node_records = neo4j_graphdb.run(fetch_node_query)
    # convert the node records into pandas dataframe
    return pd.DataFrame(node_records).rename(columns={0: "id", 1: "attr"})


start = time.time()
node_data = get_node_data_from_neo4j(neo4j_graphdb)
end = time.time()

print(f"{end - start:.2f} s: Loaded node data from neo4j database to memory")<jupyter_output>7.74 s: Loaded node data from neo4j database to memory<jupyter_text>Extract the node features which will be consumed by GraphSAGE.<jupyter_code>node_data = node_data.set_index("id")
attribute_df = node_data["attr"].apply(pd.Series)
node_data = attribute_df.drop(labels=["ID"], axis=1)
node_features = pd.DataFrame(node_data["features"].values.tolist(), index=node_data.index)
node_features.head(5)<jupyter_output><empty_output><jupyter_text>We aim to train a graph-ML model that will predict the "subject" attribute on the nodes. These subjects are one of 7 categories:<jupyter_code>labels = np.array(node_data["subject"])
set(labels)<jupyter_output><empty_output><jupyter_text>Splitting the data For machine learning we want to take a subset of the nodes for training, and use the rest for testing. We'll use scikit-learn again to do this.<jupyter_code>train_data, test_data = model_selection.train_test_split(
    node_data, train_size=0.1, test_size=None, stratify=node_data["subject"]
)<jupyter_output><empty_output><jupyter_text>Converting to numeric arrays For our categorical target, we will use one-hot vectors that will be fed into a soft-max Keras layer during training.<jupyter_code>target_encoding = feature_extraction.DictVectorizer(sparse=False)

train_targets = target_encoding.fit_transform(train_data[["subject"]].to_dict("records"))
test_targets = target_encoding.transform(test_data[["subject"]].to_dict("records"))<jupyter_output><empty_output><jupyter_text>Creating the GraphSAGE model in Keras Now create a *directed* StellarGraph object storing the node data. Since the subgraph is sampled directly from Neo4J, we only need to retain the node features and do not need to store any edges.<jupyter_code>G = sg.StellarDiGraph(nodes={"paper": node_features}, edges={})
print(G.info())<jupyter_output>StellarDiGraph: Directed multigraph
 Nodes: 2708, Edges: 0

 Node types:
  paper: [2708]
    Features: float32 vector, length 1433
    Edge types: none

 Edge types:<jupyter_text>To feed data from the graph to the Keras model we need a data generator that feeds data from the graph to the model. The generators are specialized to the model and the learning task so we choose the `Neo4JDirectedGraphSAGENodeGenerator` as we are predicting node attributes with a `DirectedGraphSAGE` model, sampling directly from Neo4J database.We need two other parameters, the `batch_size` to use for training and the number of nodes to sample at each level of the model. Here we choose a two-level model with 10 nodes sampled in the first layer (5 in-nodes and 5 out-nodes), and 4 in the second layer (2 in-nodes and 2 out-nodes).<jupyter_code>batch_size = 50
in_samples = [5, 2]
out_samples = [5, 2]<jupyter_output><empty_output><jupyter_text>A `Neo4JDirectedGraphSAGENodeGenerator` object is required to send the node features in sampled subgraphs to Keras.<jupyter_code>generator = Neo4JDirectedGraphSAGENodeGenerator(
    G, batch_size, in_samples, out_samples, neo4j_graphdb=neo4j_graphdb
)<jupyter_output><empty_output><jupyter_text>Using the `generator.flow()` method, we can create iterators over nodes that should be used to train, validate, or evaluate the model. For training we use only the training nodes returned from our splitter and the target values. The `shuffle=True` argument is given to the `flow` method to improve training.<jupyter_code>train_gen = generator.flow(train_data.index, train_targets, shuffle=True)<jupyter_output><empty_output><jupyter_text>Now we can specify our machine learning model, we need a few more parameters for this: * the `layer_sizes` is a list of hidden feature sizes of each layer in the model. In this example we use 32-dimensional hidden node features at each layer, which corresponds to 12 weights for each head node, 10 for each in-node and 10 for each out-node. * The `bias` and `dropout` are internal parameters of the model.<jupyter_code>graphsage_model = DirectedGraphSAGE(
    layer_sizes=[32, 32], generator=generator, bias=False, dropout=0.5,
)<jupyter_output><empty_output><jupyter_text>Now we create a model to predict the 7 categories using Keras softmax layers.<jupyter_code>x_inp, x_out = graphsage_model.in_out_tensors()
prediction = layers.Dense(units=train_targets.shape[1], activation="softmax")(x_out)<jupyter_output><empty_output><jupyter_text>Training the model Now let's create the actual Keras model with the graph inputs `x_inp` provided by the `graph_model` and outputs being the predictions from the softmax layer<jupyter_code>model = Model(inputs=x_inp, outputs=prediction)
model.compile(
    optimizer=optimizers.Adam(lr=0.005),
    loss=losses.categorical_crossentropy,
    metrics=["acc"],
)<jupyter_output><empty_output><jupyter_text>Train the model, keeping track of its loss and accuracy on the training set, and its generalisation performance on the test set (we need to create another generator over the test data for this)<jupyter_code>test_gen = generator.flow(test_data.index, test_targets)
history = model.fit(
    train_gen, epochs=20, validation_data=test_gen, verbose=2, shuffle=False
)
sg.utils.plot_history(history)<jupyter_output><empty_output><jupyter_text>Now we have trained the model we can evaluate on the test set.<jupyter_code>test_metrics = model.evaluate(test_gen)
print("\nTest Set Metrics:")
for name, val in zip(model.metrics_names, test_metrics):
    print("\t{}: {:0.4f}".format(name, val))<jupyter_output>['...']

Test Set Metrics:
	loss: 0.8150
	acc: 0.7826<jupyter_text>Making predictions with the model Now let's get the predictions themselves for all nodes using another node iterator:<jupyter_code>all_nodes = node_data.index
all_mapper = generator.flow(all_nodes)
all_predictions = model.predict(all_mapper)<jupyter_output><jupyter_text>These predictions will be the output of the softmax layer, so to get final categories we'll use the `inverse_transform` method of our target attribute specifcation to turn these values back to the original categories<jupyter_code>node_predictions = target_encoding.inverse_transform(all_predictions)<jupyter_output><empty_output><jupyter_text>Let's have a look at a few:<jupyter_code>results = pd.DataFrame(node_predictions, index=all_nodes).idxmax(axis=1)
df = pd.DataFrame({"Predicted": results, "True": node_data["subject"]})
df.head(10)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08334255672385169, 'fraction_numerical': 0.013171001660210293, 'mean_word_length': 6.42481511914544, 'pattern_counts': {'":': 3, '<': 70, '<?xml version=': 0, '>': 70, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '18', 'dir': 'jupyter-structured-clean-dedup', 'id': '49855', 'license': 'Apache-2.0', 'n_tokens_mistral': 2864, 'n_tokens_neox': 2728, 'n_words': 928, 'path': 'demos/connector/neo4j/directed-graphsage-on-cora-neo4j-example.ipynb', 'repo_name': 'LarsNeR/stellargraph', 'size': '9035'}