<jupyter_start><jupyter_text>Node classification with GraphSAGE Run the latest release of this notebook: Import stellargraph:<jupyter_code># install StellarGraph if running on Google Colab
import sys
if 'google.colab' in sys.modules:
  %pip install -q stellargraph[demos]==1.3.0b
# verify that we're using the correct version of StellarGraph for this notebook
import stellargraph as sg

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

import stellargraph as sg
from stellargraph.mapper import GraphSAGENodeGenerator
from stellargraph.layer import GraphSAGE

from tensorflow.keras import layers, optimizers, losses, metrics, Model
from sklearn import preprocessing, feature_extraction, model_selection
from stellargraph import datasets
from IPython.display import display, HTML
import matplotlib.pyplot as plt
%matplotlib inline<jupyter_output><empty_output><jupyter_text>Loading the CORA network (See [the "Loading from Pandas" demo](../basics/loading-pandas.ipynb) for details on how data can be loaded.)<jupyter_code>dataset = datasets.Cora()
display(HTML(dataset.description))
G, node_subjects = dataset.load()
print(G.info())<jupyter_output>StellarGraph: Undirected multigraph
 Nodes: 2708, Edges: 5429

 Node types:
  paper: [2708]
    Edge types: paper-cites->paper

 Edge types:
    paper-cites->paper: [5429]<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>set(node_subjects)<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_subjects, test_subjects = model_selection.train_test_split(
    node_subjects, train_size=0.1, test_size=None, stratify=node_subjects
)<jupyter_output><empty_output><jupyter_text>Note using stratified sampling gives the following counts:<jupyter_code>from collections import Counter

Counter(train_subjects)<jupyter_output><empty_output><jupyter_text>The training set has class imbalance that might need to be compensated, e.g., via using a weighted cross-entropy loss in model training, with class weights inversely proportional to class support. However, we will ignore the class imbalance in this example, for simplicity.  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. To do this conversion ...<jupyter_code>target_encoding = preprocessing.LabelBinarizer()

train_targets = target_encoding.fit_transform(train_subjects)
test_targets = target_encoding.transform(test_subjects)<jupyter_output><empty_output><jupyter_text>We now do the same for the node attributes we want to use to predict the subject. These are the feature vectors that the Keras model will use as input. The CORA dataset contains attributes 'w_x' that correspond to words found in that publication. If a word occurs more than once in a publication the relevant attribute will be set to one, otherwise it will be zero.  Creating the GraphSAGE model in Keras 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 `GraphSAGENodeGenerator` as we are predicting node attributes with a GraphSAGE model.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, and 5 in the second.<jupyter_code>batch_size = 50
num_samples = [10, 5]<jupyter_output><empty_output><jupyter_text>A `GraphSAGENodeGenerator` object is required to send the node features in sampled subgraphs to Keras<jupyter_code>generator = GraphSAGENodeGenerator(G, batch_size, num_samples)<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_subjects.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. * The `bias` and `dropout` are internal parameters of the model.<jupyter_code>graphsage_model = GraphSAGE(
    layer_sizes=[32, 32], generator=generator, bias=True, 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_subjects.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.6601
	acc: 0.8228<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_subjects.index
all_mapper = generator.flow(all_nodes)
all_predictions = model.predict(all_mapper)<jupyter_output><empty_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 specification 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>df = pd.DataFrame({"Predicted": node_predictions, "True": node_subjects})
df.head(10)<jupyter_output><empty_output><jupyter_text>Create a NetworkX graph to save it as GraphML, e.g. for visualisation in [Gephi](https://gephi.org). This adds the predictions to the graph before saving too.<jupyter_code>Gnx = G.to_networkx(feature_attr=None)
for nid, pred, true in zip(df.index, df["Predicted"], df["True"]):
    Gnx.nodes[nid]["subject"] = true
    Gnx.nodes[nid]["PREDICTED_subject"] = pred.split("=")[-1]<jupyter_output><empty_output><jupyter_text>Also add `isTrain` and `isCorrect` node attributes:<jupyter_code>for nid in train_subjects.index:
    Gnx.nodes[nid]["isTrain"] = True

for nid in test_subjects.index:
    Gnx.nodes[nid]["isTrain"] = False
for nid in Gnx.nodes():
    Gnx.nodes[nid]["isCorrect"] = (
        Gnx.nodes[nid]["subject"] == Gnx.nodes[nid]["PREDICTED_subject"]
    )<jupyter_output><empty_output><jupyter_text>Save in GraphML format<jupyter_code>pred_fname = "pred_n={}.graphml".format(num_samples)
nx.write_graphml(Gnx, os.path.join(dataset.data_directory, pred_fname))<jupyter_output><empty_output><jupyter_text>Node embeddingsEvaluate node embeddings as activations of the output of GraphSAGE layer stack, and visualise them, coloring nodes by their subject label.The GraphSAGE embeddings are the output of the GraphSAGE layers, namely the `x_out` variable. Let's create a new model with the same inputs as we used previously `x_inp` but now the output is the embeddings rather than the predicted class. Additionally note that the weights trained previously are kept in the new model.<jupyter_code>embedding_model = Model(inputs=x_inp, outputs=x_out)
emb = embedding_model.predict(all_mapper)
emb.shape<jupyter_output><empty_output><jupyter_text>Project the embeddings to 2d using either TSNE or PCA transform, and visualise, coloring nodes by their subject label<jupyter_code>from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
import pandas as pd
import numpy as np
X = emb
y = np.argmax(target_encoding.transform(node_subjects), axis=1)
if X.shape[1] > 2:
    transform = TSNE  # PCA

    trans = transform(n_components=2)
    emb_transformed = pd.DataFrame(trans.fit_transform(X), index=node_subjects.index)
    emb_transformed["label"] = y
else:
    emb_transformed = pd.DataFrame(X, index=node_subjects.index)
    emb_transformed = emb_transformed.rename(columns={"0": 0, "1": 1})
    emb_transformed["label"] = y
alpha = 0.7

fig, ax = plt.subplots(figsize=(7, 7))
ax.scatter(
    emb_transformed[0],
    emb_transformed[1],
    c=emb_transformed["label"].astype("category"),
    cmap="jet",
    alpha=alpha,
)
ax.set(aspect="equal", xlabel="$X_1$", ylabel="$X_2$")
plt.title(
    "{} visualization of GraphSAGE embeddings for cora dataset".format(transform.__name__)
)
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08595057595746776, 'fraction_numerical': 0.008762429851334056, 'mean_word_length': 6.235042735042735, 'pattern_counts': {'":': 4, '<': 88, '<?xml version=': 0, '>': 91, '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': '22', 'dir': 'jupyter-structured-clean-dedup', 'id': '68147', 'license': 'Apache-2.0', 'n_tokens_mistral': 3222, 'n_tokens_neox': 3080, 'n_words': 1025, 'path': 'demos/node-classification/graphsage-node-classification.ipynb', 'repo_name': 'youph/stellargraph', 'size': '10157'}