Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ Manifest.toml
.vscode
LocalPreferences.toml
.DS_Store
docs/src/democards/gridtheme.css
test.jl
docs/build
GNNGraphs/docs/build
Expand All @@ -17,7 +16,8 @@ GNNLux/docs/build
GraphNeuralNetworks/docs/build
GraphNeuralNetworks/docs/src/GNNGraphs
GraphNeuralNetworks/docs/src/GNNlib
# Copied from GraphNeuralNetworks/docs by GNNLux/docs/make.jl
GNNLux/docs/src/tutorials/*/assets
tutorials/docs/build
docs/src/tutorials # generated by DemoCards from docs/tutorials/
prova.jl
pyg.ipynb
1 change: 1 addition & 0 deletions GNNLux/docs/Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ MLDatasets = "eb30cadb-4394-5ae3-aed4-317e484a6458"
MLUtils = "f1d291b0-491e-4a28-83b9-f70985020b54"
OneHotArrays = "0b1bfda6-eb8a-41d2-88d8-f5af5cad476f"
Optimisers = "3bd65402-5787-11e9-1adc-39752487f4e2"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
TSne = "24678dba-d5e9-5843-a4c6-250288b04835"
Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f"

Expand Down
24 changes: 18 additions & 6 deletions GNNLux/docs/make.jl
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,18 @@ cp(joinpath(@__DIR__, "../../GNNGraphs/docs/src"),
cp(joinpath(@__DIR__, "../../GNNlib/docs/src"),
joinpath(@__DIR__, "src/GNNlib"), force=true)

# Copy the tutorial images from the GNN docs, whose tutorials share them. Also removed at the end
const TUTORIAL_SECTIONS = ["beginner_tutorials", "intermediate_tutorials"]
for section in TUTORIAL_SECTIONS
cp(joinpath(@__DIR__, "../../GraphNeuralNetworks/docs/src/tutorials", section, "assets"),
joinpath(@__DIR__, "src/tutorials", section, "assets"), force=true)
end

makedocs(;
modules = [GNNLux, GNNGraphs, GNNlib],
plugins = [interlinks],
format = Documenter.HTML(; mathengine,
prettyurls = get(ENV, "CI", nothing) == "true",
assets = [],
size_threshold=nothing,
size_threshold_warn=2000000),
sitename = "GNNLux.jl",
Expand All @@ -53,10 +59,13 @@ makedocs(;
],

"Tutorials" => [
"Introductory tutorials" => [
"Hands on" => "tutorials/gnn_intro.md",
"Node Classification" => "tutorials/node_classification.md",
"Graph Classification" => "tutorials/graph_classification.md",
"Beginner tutorials" => [
"Hands on" => "tutorials/beginner_tutorials/gnn_intro.md",
"Node Classification" => "tutorials/beginner_tutorials/node_classification.md",
"Graph Classification" => "tutorials/beginner_tutorials/graph_classification.md",
],
"Intermediate tutorials" => [
"Traffic Prediction" => "tutorials/intermediate_tutorials/traffic_prediction.md",
],
],

Expand Down Expand Up @@ -85,9 +94,12 @@ makedocs(;
# "Developer guide" => "dev.md",
],
)

rm(joinpath(@__DIR__, "src/GNNGraphs"), force=true, recursive=true)
rm(joinpath(@__DIR__, "src/GNNlib"), force=true, recursive=true)
for section in TUTORIAL_SECTIONS
rm(joinpath(@__DIR__, "src/tutorials", section, "assets"), force=true, recursive=true)
end

deploydocs(
repo = "github.com/JuliaGraphs/GraphNeuralNetworks.jl",
Expand Down
15 changes: 12 additions & 3 deletions GNNLux/docs/make_tutorials.jl
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
using Literate

Literate.markdown("src_tutorials/gnn_intro.jl", "src/tutorials/"; execute = true)
# Run this script from `GNNLux/docs` with
# julia --project=. make_tutorials.jl
function tutorial(name, section)
Literate.markdown(joinpath("src_tutorials", "$name.jl"), joinpath("src", "tutorials", section);
execute = true)
end

Literate.markdown("src_tutorials/graph_classification.jl", "src/tutorials/"; execute = true)
tutorial("gnn_intro", "beginner_tutorials")

Literate.markdown("src_tutorials/node_classification.jl", "src/tutorials/"; execute = true)
tutorial("graph_classification", "beginner_tutorials")

tutorial("node_classification", "beginner_tutorials")

tutorial("traffic_prediction", "intermediate_tutorials")
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
```@meta
EditURL = "../../../src_tutorials/gnn_intro.jl"
```

# Hands-on introduction to Graph Neural Networks

*This Pluto notebook is a Julia adaptation of the Pytorch Geometric tutorials that can be found [here](https://pytorch-geometric.readthedocs.io/en/latest/notes/colabs.html).*

![cover](assets/cover_gnn_intro.png)

Recently, deep learning on graphs has emerged to be one of the hottest research fields in the deep learning community.
Here, **Graph Neural Networks (GNNs)** aim to generalize classical deep learning concepts to irregular structured data (in contrast to images or texts) and to enable neural networks to reason about objects and their relations.

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
```@meta
EditURL = "../../../src_tutorials/graph_classification.jl"
```

# Graph Classification with Graph Neural Networks

*This tutorial is a Julia adaptation of the Pytorch Geometric tutorial that can be found [here](https://pytorch-geometric.readthedocs.io/en/latest/notes/colabs.html).*

![cover](assets/cover_graph_classification.png)

In this tutorial session we will have a closer look at how to apply **Graph Neural Networks (GNNs) to the task of graph classification**.
Graph classification refers to the problem of classifying entire graphs (in contrast to nodes), given a **dataset of graphs**, based on some structural graph properties and possibly on some input node features.
Here, we want to embed entire graphs, and we want to embed those graphs in such a way so that they are linearly separable given a task at hand.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
```@meta
EditURL = "../../../src_tutorials/node_classification.jl"
```

# Node Classification with Graph Neural Networks

![](assets/cover_node_classification.svg)

In this tutorial, we will be learning how to use Graph Neural Networks (GNNs) for node classification. Given the ground-truth labels of only a small subset of nodes, we want to infer the labels for all the remaining nodes (transductive learning).

## Import
Expand Down
914 changes: 914 additions & 0 deletions GNNLux/docs/src/tutorials/intermediate_tutorials/traffic_prediction.md

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions GNNLux/docs/src_tutorials/gnn_intro.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
#
# *This tutorial is a Julia adaptation of one of the [Pytorch Geometric tutorials](https://pytorch-geometric.readthedocs.io/en/latest/notes/colabs.html).*
#
# ![cover](assets/cover_gnn_intro.png)
#
# Recently, deep learning on graphs has emerged to be one of the hottest research fields in the deep learning community.
# Here, **Graph Neural Networks (GNNs)** aim to generalize classical deep learning concepts to irregular structured data (in contrast to images or texts) and to enable neural networks to reason about objects and their relations.
#
Expand Down
2 changes: 2 additions & 0 deletions GNNLux/docs/src_tutorials/graph_classification.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

# *This tutorial is a Julia adaptation of the Pytorch Geometric tutorial that can be found [here](https://pytorch-geometric.readthedocs.io/en/latest/notes/colabs.html).*

# ![cover](assets/cover_graph_classification.png)

# In this tutorial session we will have a closer look at how to apply **Graph Neural Networks (GNNs) to the task of graph classification**.
# Graph classification refers to the problem of classifying entire graphs (in contrast to nodes), given a **dataset of graphs**, based on some structural graph properties and possibly on some input node features.
# Here, we want to embed entire graphs, and we want to embed those graphs in such a way so that they are linearly separable given a task at hand.
Expand Down
2 changes: 2 additions & 0 deletions GNNLux/docs/src_tutorials/node_classification.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# # Node Classification with Graph Neural Networks

# ![](assets/cover_node_classification.svg)

# In this tutorial, we will be learning how to use Graph Neural Networks (GNNs) for node classification. Given the ground-truth labels of only a small subset of nodes, we want to infer the labels for all the remaining nodes (transductive learning).


Expand Down
146 changes: 146 additions & 0 deletions GNNLux/docs/src_tutorials/traffic_prediction.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
# # Traffic Prediction using Recurrent Temporal GNN

# ![](assets/cover_traffic.gif)

# In this tutorial, we will learn how to use a recurrent Temporal Graph Convolutional Network (TGCN) to predict traffic in a spatio-temporal setting. Traffic forecasting is the problem of predicting future traffic trends on a road network given historical traffic data, such as, in our case, traffic speed and time of day.

# ## Import

# We start by importing the necessary libraries. We use `GNNLux.jl`, `Lux.jl` and `MLDatasets.jl`, among others.

using Lux, GNNLux
using MLDatasets: METRLA
using Statistics, Plots, Random
using Zygote, Optimisers

const mae = MAELoss()

ENV["DATADEPS_ALWAYS_ACCEPT"] = "true" # don't ask for dataset download confirmation
rng = Random.seed!(42); # for reproducibility

# ## Dataset: METR-LA

# We use the `METR-LA` dataset from the paper [Diffusion Convolutional Recurrent Neural Network: Data-driven Traffic Forecasting](https://arxiv.org/pdf/1707.01926.pdf), which contains traffic data from loop detectors in the highway of Los Angeles County. The dataset contains traffic speed data from March 1, 2012 to June 30, 2012. The data is collected every 5 minutes, resulting in 12 observations per hour, from 207 sensors. Each sensor is a node in the graph, and the edge weights are the distances between the sensor locations.

dataset_metrla = METRLA(; num_timesteps = 3)
#
g = dataset_metrla[1]

# `edge_data` contains the weights of the edges of the graph and
# `node_data` contains a node feature vector and a target vector. The latter vectors contain batches of dimension `num_timesteps`, which means that they contain vectors with the node features and targets of `num_timesteps` time steps. Two consecutive batches are shifted by one-time step.
# The node features are the traffic speed of the sensors and the time of the day, and the targets are the traffic speed of the sensors in the next time step.
# Let's see some examples:

features = map(x -> permutedims(x,(1,3,2)), g.node_data.features)

size(features[1])

# The first dimension corresponds to the two features (the first line the speed value and the second line the time of day), the second to the number of time steps `num_timesteps` and the third to the nodes.

targets = map(x -> permutedims(x,(1,3,2)), g.node_data.targets)

size(targets[1])

# In the case of the targets the first dimension is 1 because they store just the speed value.

features[1][:,:,1]
#
features[2][:,:,1]
#
targets[1][:,:,1]
#
function plot_data(data,sensor)
p = plot(legend=false, xlabel="Time (h)", ylabel="Normalized speed")
plotdata = []
for i in 1:3:length(data)
push!(plotdata,data[i][1,:,sensor])
end
plotdata = reduce(vcat,plotdata)
plot!(p, collect(1:length(data)), plotdata, color = :green, xticks =([i for i in 0:50:250], ["$(i)" for i in 0:4:24]))
return p
end

plot_data(features[1:288],1) # Plot the speed of the first sensor for the first day

# Now let's construct the static graph, the `train_loader` and `data_loader`.

graph = GNNGraph(g.edge_index; edata = g.edge_data, g.num_nodes);

train_loader = zip(features[1:288], targets[1:288]); # train on 24 hours
test_loader = zip(features[289:577], targets[289:577]); # test on next 24 hours

# ## Model: T-GCN

# We use the T-GCN model from the paper [T-GCN: A Temporal Graph Convolutional Network for Traffic Prediction] (https://arxiv.org/pdf/1811.05320.pdf), which consists of a graph convolutional network (GCN) and a gated recurrent unit (GRU). The GCN is used to capture spatial features from the graph, and the GRU is used to capture temporal features from the feature time series.

model = GNNChain(TGCN(2 => 100; add_self_loops = false), Dense(100, 1))

# Let's look at the output of the model for the first batch of the training data.
# In Lux, the parameters and the state of the model are kept separate from the model itself, so we first initialize them.

ps, st = Lux.setup(rng, model);

ŷ, _ = model(graph, features[1], ps, st);
ŷ

# The output of the model is a tensor of size `(1, 3, 207)`, which corresponds to the dimension of the feature (in this case speed), the number of time steps, and the number of nodes in the graph, respectively. The model outputs the predicted traffic speed for each sensor at each time step.

# ![](https://www.researchgate.net/profile/Haifeng-Li-3/publication/335353434/figure/fig4/AS:851870352437249@1580113127759/The-architecture-of-the-Gated-Recurrent-Unit-model.jpg)

# ## Training

# We train the model for 100 epochs, using the Adam optimizer with a learning rate of 0.001. We use the mean absolute error (MAE) as the loss function.

function loss_function(model, ps, st, (graph, x, y))
ŷ, st = model(graph, x, ps, st)
return mae(ŷ, y), st, (;)
end

function train(graph, train_loader, model, ps, st)

train_state = Lux.Training.TrainState(model, ps, st, Adam(0.001))

for epoch in 1:100
for (x, y) in train_loader
_, _, _, train_state = Lux.Training.single_train_step!(AutoZygote(), loss_function, (graph, x, y), train_state)
end

if epoch % 10 == 0
ps, st = train_state.parameters, train_state.states
loss = mean([mae(model(graph, x, ps, st)[1], y) for (x, y) in train_loader])
@show epoch, loss
end
end
return train_state.parameters, train_state.states
end

ps, st = train(graph, train_loader, model, ps, st);
#
function plot_predicted_data(graph, features, targets, sensor)
p = plot(xlabel="Time (h)", ylabel="Normalized speed")
prediction = []
ground_truth = []
for i in 1:3:length(features)
push!(ground_truth,targets[i][1,:,sensor])
push!(prediction, model(graph, features[i], ps, st)[1][1,:,sensor])
end
prediction = reduce(vcat,prediction)
ground_truth = reduce(vcat, ground_truth)
plot!(p, collect(1:length(prediction)), prediction, color = :red, label= "Prediction")
plot!(p, collect(1:length(ground_truth)), ground_truth, color = :blue, label = "Ground Truth", xticks = ([i for i in 0:50:250], ["$(i)" for i in 0:4:20]))
return p
end

plot_predicted_data(graph,features[289:577],targets[289:577], 1)
#
accuracy(ŷ, y) = 1 - Statistics.norm(y-ŷ)/Statistics.norm(y)

# Test accuracy:

mean([accuracy(model(graph, x, ps, st)[1], y) for (x, y) in test_loader])

# The accuracy is not very good but can be improved by training using more data. We used a small subset of the dataset for this tutorial because of the computational cost of training the model. From the plot of the predictions, we can see that the model is able to capture the general trend of the traffic speed, but it is not able to capture the peaks of the traffic.

# ## Conclusion

# In this tutorial, we learned how to use a recurrent temporal graph convolutional network to predict traffic in a spatio-temporal setting. We used the TGCN model, which consists of a graph convolutional network (GCN) and a gated recurrent unit (GRU). We then trained the model for 100 epochs on a small subset of the METR-LA dataset. The accuracy of the model is not very good, but it can be improved by training on more data.
1 change: 1 addition & 0 deletions GNNLux/test/Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,6 @@ Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f"
GNNLux = {path = ".."}

[compat]
LuxTestUtils = "2.3.2"
NNlib = "0.9.38"
StableRNGs = "1.0.4"
1 change: 0 additions & 1 deletion GraphNeuralNetworks/docs/Project.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
[deps]
CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0"
DemoCards = "311a05b2-6137-4a5a-b473-18580a3d38b5"
Documenter = "e30172f5-a6a5-5a46-863b-614d45cd2de4"
DocumenterInterLinks = "d12716ef-a0f6-4df4-a9f1-a5a34e75c656"
DocumenterMermaid = "a078cd44-4d9c-4618-b545-3ab9d77f9177"
Expand Down
22 changes: 10 additions & 12 deletions GraphNeuralNetworks/docs/make.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Documenter
using DemoCards: DemoCards
using GraphNeuralNetworks
using Flux, GNNGraphs, GNNlib, Graphs
using DocumenterInterLinks
Expand Down Expand Up @@ -35,21 +34,21 @@ cp(joinpath(@__DIR__, "../../GNNlib/docs/src"),
joinpath(@__DIR__, "src/GNNlib"), force=true)


## DEMO CARDS AUTOMATICALLY DETECTS TUTORIALS FROM FOLDER STRUCTURE
tutorials, tutorials_postprocess_cb, tutorials_assets = DemoCards.makedemos(joinpath(@__DIR__, "tutorials"))
## UNCOMMENT TO DISABLE TUTORIALS AND SPEED UP DOCS BUILDING
# tutorials, tutorials_postprocess_cb, tutorials_assets =
# "Tutorials" => "index.md", () -> nothing, nothing

assets = []
isnothing(tutorials_assets) || push!(assets, tutorials_assets)

tutorials = "Tutorials" => [
"Beginner tutorials" => [
"Hands on" => "tutorials/beginner_tutorials/gnn_intro.md",
"Node Classification" => "tutorials/beginner_tutorials/node_classification.md",
"Graph Classification" => "tutorials/beginner_tutorials/graph_classification.md",
],
"Intermediate tutorials" => [
"Traffic Prediction" => "tutorials/intermediate_tutorials/traffic_prediction.md",
],
]
makedocs(;
modules = [GraphNeuralNetworks, GNNGraphs, GNNlib],
plugins = [interlinks],
format = Documenter.HTML(; mathengine,
prettyurls = get(ENV, "CI", nothing) == "true",
assets,
size_threshold=nothing,
size_threshold_warn=2000000,
example_size_threshold=2000000),
Expand Down Expand Up @@ -93,7 +92,6 @@ makedocs(;
],
)

tutorials_postprocess_cb()
for (name, reason) in SyntheticDatasets.REPLACED
@warn "Could not load the $name dataset, so its tutorial was built with synthetic data" reason
end
Expand Down
23 changes: 2 additions & 21 deletions GraphNeuralNetworks/docs/src/dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,25 +116,6 @@ julia> @load "perf_pr_20210803_mymachine.jld2"
julia> compare(dfpr, dfmaster)
```

## Caching tutorials
## Tutorials

Tutorials in GraphNeuralNetworks.jl are written in Pluto and rendered using [DemoCards.jl](https://github.com/JuliaDocs/DemoCards.jl) and [PlutoStaticHTML.jl](https://github.com/rikhuijzer/PlutoStaticHTML.jl). Rendering a Pluto notebook is time and resource-consuming, especially in a CI environment. So we use the [caching functionality](https://huijzer.xyz/PlutoStaticHTML.jl/dev/#Caching) provided by PlutoStaticHTML.jl to reduce CI time.

If you are contributing a new tutorial or making changes to the existing notebook, generate the docs locally before committing/pushing. For caching to work, the cache environment(your local) and the documenter CI should have the same Julia version (e.g. "v1.9.1", also the patch number must match). So use the [documenter CI Julia version](https://github.com/JuliaGraphs/GraphNeuralNetworks.jl/blob/master/.github/workflows/docs.yml#L17) for generating docs locally.

```console
julia --version # check julia version before generating docs
julia --project=docs docs/make.jl
```

Note: Use [juliaup](https://github.com/JuliaLang/juliaup) for easy switching of Julia versions.

During the doc generation process, DemoCards.jl stores the cache notebooks in docs/pluto_output. So add any changes made in this folder in your git commit. Remember that every file in this folder is machine-generated and should not be edited manually.

```
git add docs/pluto_output # add generated cache
```

Check the [documenter CI logs](https://github.com/JuliaGraphs/GraphNeuralNetworks.jl/actions/workflows/docs.yml) to ensure that it used the local cache:

![](https://user-images.githubusercontent.com/55111154/210061301-c84b7274-9e66-46fd-b272-d45b1c681d00.png)
The tutorials are Markdown pages in `docs/src/tutorials/<section>/`, with their images in an `assets/` folder next to them. Their code is in `@example` blocks, so it runs during the docs build. To add a tutorial, add its page there and list it under "Tutorials" in the `pages` of `docs/make.jl`.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loading
Loading