Skip to content

Commit a1f110d

Browse files
committed
Add traffic prediction
1 parent f2a7600 commit a1f110d

File tree

4 files changed

+402
-2399
lines changed

4 files changed

+402
-2399
lines changed

GraphNeuralNetworks/docs/make_tutorials_literate.jl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,5 @@ Literate.markdown("src_tutorials/introductory_tutorials/graph_classification.jl"
1313

1414
Literate.markdown("src_tutorials/introductory_tutorials/temporal_graph_classification.jl",
1515
"src/tutorials/"; execute = true)
16+
17+
Literate.markdown("src_tutorials/introductory_tutorials/traffic_prediction.jl", "src/tutorials/"; execute = true)

GraphNeuralNetworks/docs/src/tutorials/traffic_prediction.md

Lines changed: 266 additions & 155 deletions
Large diffs are not rendered by default.
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
# # Traffic Prediction using recurrent Temporal Graph Convolutional Network
2+
3+
# 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.
4+
5+
# ## Import
6+
7+
# We start by importing the necessary libraries. We use `GraphNeuralNetworks.jl`, `Flux.jl` and `MLDatasets.jl`, among others.
8+
9+
using Flux, GraphNeuralNetworks
10+
using Flux.Losses: mae
11+
using MLDatasets: METRLA
12+
using Statistics, Plots
13+
14+
# ## Dataset: METR-LA
15+
16+
# 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 edges represent the distances between the sensors.
17+
18+
dataset_metrla = METRLA(; num_timesteps = 3)
19+
#
20+
g = dataset_metrla[1]
21+
22+
23+
# `edge_data` contains the weights of the edges of the graph and
24+
# `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.
25+
# 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.
26+
# Let's see some examples:
27+
28+
features = map(x -> permutedims(x,(1,3,2)), g.node_data.features)
29+
30+
size(features[1])
31+
32+
# The first dimension correspond to the two features (first line the speed value and the second line the time of the day), the second to the number of timestep `num_timesteps` and the third to the nodes.
33+
34+
targets = map(x -> permutedims(x,(1,3,2)), g.node_data.targets)
35+
36+
size(targets[1])
37+
38+
# In the case of the targets the first dimension is 1 because they store just the speed value.
39+
40+
features[1][:,:,1]
41+
42+
#
43+
features[2][:,:,1]
44+
45+
#
46+
targets[1][:,:,1]
47+
48+
#
49+
function plot_data(data,sensor)
50+
p = plot(legend=false, xlabel="Time (h)", ylabel="Normalized speed")
51+
plotdata = []
52+
for i in 1:3:length(data)
53+
push!(plotdata,data[i][1,:,sensor])
54+
end
55+
plotdata = reduce(vcat,plotdata)
56+
plot!(p, collect(1:length(data)), plotdata, color = :green, xticks =([i for i in 0:50:250], ["$(i)" for i in 0:4:24]))
57+
return p
58+
end
59+
60+
plot_data(features[1:288],1)
61+
62+
# Now let's construct the static graph, the `train_loader` and `data_loader`.
63+
64+
graph = GNNGraph(g.edge_index; edata = g.edge_data, g.num_nodes);
65+
66+
train_loader = zip(features[1:200], targets[1:200]);
67+
test_loader = zip(features[2001:2288], targets[2001:2288]);
68+
69+
# ## Model: T-GCN
70+
71+
# 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.
72+
73+
model = GNNChain(TGCN(2 => 100; add_self_loops = false), Dense(100, 1))
74+
75+
# ![](https://www.researchgate.net/profile/Haifeng-Li-3/publication/335353434/figure/fig4/AS:851870352437249@1580113127759/The-architecture-of-the-Gated-Recurrent-Unit-model.jpg)
76+
77+
# ## Training
78+
79+
# 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.
80+
81+
function train(graph, train_loader, model)
82+
83+
opt = Flux.setup(Adam(0.001), model)
84+
85+
for epoch in 1:100
86+
for (x, y) in train_loader
87+
x, y = (x, y)
88+
grads = Flux.gradient(model) do model
89+
= model(graph, x)
90+
Flux.mae(ŷ, y)
91+
end
92+
Flux.update!(opt, model, grads[1])
93+
end
94+
95+
if epoch % 10 == 0
96+
loss = mean([Flux.mae(model(graph,x), y) for (x, y) in train_loader])
97+
@show epoch, loss
98+
end
99+
end
100+
return model
101+
end
102+
103+
train(graph, train_loader, model)
104+
105+
#
106+
function plot_predicted_data(graph, features, targets, sensor)
107+
p = plot(xlabel="Time (h)", ylabel="Normalized speed")
108+
prediction = []
109+
grand_truth = []
110+
for i in 1:3:length(features)
111+
push!(grand_truth,targets[i][1,:,sensor])
112+
push!(prediction, model(graph, features[i])[1,:,sensor])
113+
end
114+
prediction = reduce(vcat,prediction)
115+
grand_truth = reduce(vcat, grand_truth)
116+
plot!(p, collect(1:length(features)), grand_truth, color = :blue, label = "Grand Truth", xticks =([i for i in 0:50:250], ["$(i)" for i in 0:4:24]))
117+
plot!(p, collect(1:length(features)), prediction, color = :red, label= "Prediction")
118+
return p
119+
end
120+
121+
plot_predicted_data(graph,features[301:588],targets[301:588], 1)
122+
123+
#
124+
accuracy(ŷ, y) = 1 - Statistics.norm(y-ŷ)/Statistics.norm(y)
125+
# Test accuracy:
126+
mean([accuracy(model(graph,x), y) for (x, y) in test_loader])
127+
128+
129+
# 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.
130+
131+
# ## Conclusion
132+
133+
# 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.
134+

0 commit comments

Comments
 (0)