Training the pipeline

The train mode, gds.beta.pipeline.nodeClassification.train, is responsible for splitting data, feature extraction, model selection, training and storing a model for future use. Running this mode results in a classification model of type NodeClassification, which is then stored in the model catalog. The classification model can be applied to a possibly different graph which classifies nodes.

More precisely, the training proceeds as follows:

  1. Apply nodeLabels and relationshipType filters to the graph.

  2. Apply the node property steps, added according to Adding node properties, on the whole graph.

  3. Select node properties to be used as features, as specified in Adding features.

  4. Split the input graph into two parts: the train graph and the test graph. This is described in Configuring the node splits. These graphs are internally managed and exist only for the duration of the training.

  5. Split the nodes in the train graph using stratified k-fold cross-validation. The number of folds k can be configured as described in Configuring the node splits.

  6. Each model candidate defined in the parameter space is trained on each train set and evaluated on the respective validation set for every fold. The evaluation uses the specified primary metric.

  7. Choose the best performing model according to the highest average score for the primary metric.

  8. Retrain the winning model on the entire train graph.

  9. Evaluate the performance of the winning model on the whole train graph as well as the test graph.

  10. Retrain the winning model on the entire original graph.

  11. Register the winning model in the Model Catalog.

The above steps describe what the procedure does logically. The actual steps as well as their ordering in the implementation may differ.
A step can only use node properties that are already present in the input graph or produced by steps, which were added before.

1. Metrics

The Node Classification model in the Neo4j GDS library supports the following evaluation metrics:

  • Global metrics

    • F1_WEIGHTED

    • F1_MACRO

    • ACCURACY

    • OUT_OF_BAG_ERROR (only for RandomForest and only gives validation and test score)

  • Per-class metrics

    • F1(class=<number>) or F1(class=*)

    • PRECISION(class=<number>) or PRECISION(class=*)

    • RECALL(class=<number>) or RECALL(class=*)

    • ACCURACY(class=<number>) or ACCURACY(class=*)

The * is syntactic sugar for reporting the metric for each class in the graph. When using a per-class metric, the reported metrics contain keys like for example ACCURACY_class_1.

More than one metric can be specified during training but only the first specified — the primary one — is used for evaluation, the results of all are present in the train results. The primary metric may not be a * expansion due to the ambiguity of which of the expanded metrics should be the primary one.

The OUT_OF_BAG_ERROR is computed only for RandomForest models and is evaluated as the accuracy of majority voting, where for each example only the trees that did not use that example during training are considered. The proportion the train set used by each tree is controlled by the configuration parameter numberOfSamplesRatio. OUT_OF_BAG_ERROR is reported as a validation score when evaluated during the cross-validation phase. In the case when a random forest model wins, it is reported as a test score based on retraining the model on the entire train set.

2. Syntax

Run Node Classification in train mode on a named graph:
CALL gds.beta.pipeline.nodeClassification.train(
  graphName: String,
  configuration: Map
) YIELD
  trainMillis: Integer,
  modelInfo: Map,
  modelSelectionStats: Map,
  configuration: Map
Table 1. Parameters
Name Type Default Optional Description

graphName

String

n/a

no

The name of a graph stored in the catalog.

configuration

Map

{}

yes

Configuration for algorithm-specifics and/or graph filtering.

Table 2. Configuration
Name Type Default Optional Description

pipeline

String

n/a

no

The name of the pipeline to execute.

nodeLabels

List of String

['*']

yes

Filter the named graph using the given node labels.

relationshipTypes

List of String

['*']

yes

Filter the named graph using the given relationship types.

concurrency

Integer

4

yes

The number of concurrent threads used for running the algorithm.

targetProperty

String

n/a

no

The class of the node. Must be of type Integer.

metrics

List of String

n/a

no

Metrics used to evaluate the models.

randomSeed

Integer

n/a

yes

Seed for the random number generator used during training.

modelName

String

n/a

no

The name of the model to train, must not exist in the Model Catalog.

jobId

String

Generated internally

yes

An ID that can be provided to more easily track the training’s progress.

Table 3. Results
Name Type Description

trainMillis

Integer

Milliseconds used for training.

modelInfo

Map

Information about the training and the winning model.

modelSelectionStats

Map

Statistics about evaluated metrics for all model candidates.

configuration

Map

Configuration used for the train procedure.

The modelInfo can also be retrieved at a later time by using the Model List Procedure. The modelInfo return field has the following algorithm-specific subfields:

Table 4. Fields of modelSelectionStats
Name Type Description

bestParameters

Map

The model parameters which performed best on average on validation folds according to the primary metric.

modelCandidates

List

List of maps, where each map contains information about one model candidate. This information includes the candidates parameters, training statistics and validation statistics.

bestTrial

Integer

The trial that produced the best model. The first trial has number 1.

Table 5. Fields of modelInfo
Name Type Description

modelName

String

The name of the trained model.

modelType

String

The type of the trained model.

classes

List of Integer

Sorted list of class ids which are the distinct values of targetProperty over the entire graph.

bestParameters

Map

The model parameters which performed best on average on validation folds according to the primary metric.

metrics

Map

Map from metric description to evaluated metrics for the winning model over the subsets of the data, see below.

trainingPipeline

Map

The pipeline used for the training.

The structure of modelInfo is:

{
    bestParameters: Map,        (1)
    trainingPipeline: Map       (2)
    classes: List of Integer,   (3)
    metrics: {                  (4)
        <METRIC_NAME>: {        (5)
            test: Float,        (6)
            outerTrain: Float,  (7)
            train: {           (8)
                avg: Float,
                max: Float,
                min: Float,
            },
            validation: {      (9)
                avg: Float,
                max: Float,
                min: Float,
                params: Map
            }
        }
    }
}
1 The best scoring model candidate configuration.
2 The pipeline used for the training.
3 Sorted list of class ids which are the distinct values of targetProperty over the entire graph.
4 The metrics map contains an entry for each metric description, and the corresponding results for that metric.
5 A metric name specified in the configuration of the procedure, e.g., F1_MACRO or RECALL(class=4).
6 Numeric value for the evaluation of the winning model on the test set.
7 Numeric value for the evaluation of the winning model on the outer train set.
8 The train entry summarizes the metric results over the train set.
9 The validation entry summarizes the metric results over the validation set.

In (6)-(8), if the metric is OUT_OF_BAG_ERROR, these statistics are not reported. The OUT_OF_BAG_ERROR is only reported in (9) as validation metric and only if the model is RandomForest.

In addition to the data the procedure yields, there’s a fair amount of information about the training that’s being sent to the Neo4j database’s logs as the procedure progresses.

For example, how well each model candidates perform is logged with info log level and thus end up the neo4j.log file of the database.

Some information is only logged with debug log level, and thus end up in the debug.log file of the database. An example of this is training method specific metadata - such as per epoch loss for logistic regression - during model candidate training (in the model selection phase). Please note that this particular data is not yielded by the procedure call.

3. Example

In this section we will show examples of running a Node Classification training pipeline on a concrete graph. The intention is to illustrate what the results look like and to provide a guide in how to make use of the model in a real setting. We will do this on a small graph of a handful of nodes representing houses. This is an example of Multi-class classification, the class node property distinct values determine the number of classes, in this case three (0, 1 and 2). The example graph looks like this:

node property pipeline graph
The following Cypher statement will create the example graph in the Neo4j database:
CREATE
  (:House {color: 'Gold', sizePerStory: [15.5, 23.6, 33.1], class: 0}),
  (:House {color: 'Red', sizePerStory: [15.5, 23.6, 100.0], class: 0}),
  (:House {color: 'Blue', sizePerStory: [11.3, 35.1, 22.0], class: 0}),
  (:House {color: 'Green', sizePerStory: [23.2, 55.1, 0.0], class: 1}),
  (:House {color: 'Gray', sizePerStory: [34.3, 24.0, 0.0],  class: 1}),
  (:House {color: 'Black', sizePerStory: [71.66, 55.0, 0.0], class: 1}),
  (:House {color: 'White', sizePerStory: [11.1, 111.0, 0.0], class: 1}),
  (:House {color: 'Teal', sizePerStory: [80.8, 0.0, 0.0], class: 2}),
  (:House {color: 'Beige', sizePerStory: [106.2, 0.0, 0.0], class: 2}),
  (:House {color: 'Magenta', sizePerStory: [99.9, 0.0, 0.0], class: 2}),
  (:House {color: 'Purple', sizePerStory: [56.5, 0.0, 0.0], class: 2}),
  (:UnknownHouse {color: 'Pink', sizePerStory: [23.2, 55.1, 56.1]}),
  (:UnknownHouse {color: 'Tan', sizePerStory: [22.32, 102.0, 0.0]}),
  (:UnknownHouse {color: 'Yellow', sizePerStory: [39.0, 0.0, 0.0]});

With the graph in Neo4j we can now project it into the graph catalog to prepare it for the pipeline execution. We do this using a native projection targeting the House and UnknownHouse labels. We will also project the sizeOfStory property to use as a model feature, and the class property to use as a target feature.

In the examples below we will use named graphs and native projections as the norm. However, Cypher projections can also be used.

The following statement will project a graph using a native projection and store it in the graph catalog under the name 'myGraph'.
CALL gds.graph.project('myGraph', {
    House: { properties: ['sizePerStory', 'class'] },
    UnknownHouse: { properties: 'sizePerStory' }
  },
  '*'
)

3.1. Memory Estimation

First off, we will estimate the cost of running the algorithm using the estimate procedure. This can be done with any execution mode. We will use the train mode in this example. Estimating the algorithm is useful to understand the memory impact that running the algorithm on your graph will have. When you later actually run the algorithm in one of the execution modes the system will perform an estimation. If the estimation shows that there is a very high probability of the execution going over its memory limitations, the execution is prohibited. To read more about this, see Automatic estimation and execution blocking.

For more details on estimate in general, see Memory Estimation.

The following will estimate the memory requirements for running the algorithm in train mode:
CALL gds.beta.pipeline.nodeClassification.train.estimate('myGraph', {
  pipeline: 'pipe',
  nodeLabels: ['House'],
  modelName: 'nc-model',
  targetProperty: 'class',
  randomSeed: 2,
  metrics: [ 'F1_WEIGHTED' ]
})
YIELD requiredMemory
Table 6. Results
requiredMemory

"[1264 KiB ... 1338 KiB]"

If a node property step does not have an estimation implemented, the step will be ignored in the estimation.

3.2. Train

In the following examples we will demonstrate running the Node Classification training pipeline on this graph. We will train a model to predict the class in which a house belongs, based on its sizePerStory property.

The following will train a model using a pipeline:
CALL gds.beta.pipeline.nodeClassification.train('myGraph', {
  pipeline: 'pipe',
  nodeLabels: ['House'],
  modelName: 'nc-pipeline-model',
  targetProperty: 'class',
  randomSeed: 42,
  metrics: ['F1_WEIGHTED', 'OUT_OF_BAG_ERROR']
}) YIELD modelInfo, modelSelectionStats
RETURN
  modelInfo.bestParameters AS winningModel,
  modelInfo.metrics.F1_WEIGHTED.train.avg AS avgTrainScore,
  modelInfo.metrics.F1_WEIGHTED.outerTrain AS outerTrainScore,
  modelInfo.metrics.F1_WEIGHTED.test AS testScore,
  [cand IN modelSelectionStats.modelCandidates | cand.metrics.F1_WEIGHTED.validation.avg] AS validationScores
Table 7. Results
winningModel avgTrainScore outerTrainScore testScore validationScores

{maxEpochs=100, minEpochs=1, penalty=0.0, patience=1, methodName=LogisticRegression, batchSize=100, tolerance=0.001, learningRate=0.001}

0.999999989939394

0.9999999912121211

0.999999985

[0.4909090835454547, 0.07272727163636365, 0.4909090835454547, 0.4909090835454547, 0.4909090835454547]

Here we can observe that the model candidate with penalty 0.0625 performed the best in the training phase, with an F1_WEIGHTED score nearing 1 over the train graph as well as on the test graph. This indicates that the model reacted very well to the train graph, and was able to generalize fairly well to unseen data. Notice that this is just a toy example on a very small graph. In order to achieve a higher test score, we may need to use better features, a larger graph, or different model configuration.