library(igraph)
library(ggraph)
library(oddnet)
library(tsibble)
library(fable)
library(lubridate)16 Network and graph data
A network, or graph, consists of a set of nodes (also called vertices) and a set of edges connecting pairs of nodes. Networks arise whenever we record relationships between things: friendships on social media, citations between academic papers, co-voting patterns in parliaments, or messages exchanged within an organisation. Almost all real networks change over time, as new nodes and edges appear, old ones disappear, and the overall structure evolves. An anomaly in this setting might be a fault in an infrastructure network, a fraudulent transaction, a sudden burst of activity around a real-world event, or an unusual realignment in a voting network.
A network is written as \mathcal{G}, with n nodes labelled 1,\dots,n. In an undirected network, an edge simply records that two nodes are connected, so an edge between nodes i and j is the same as an edge between nodes j and i. In a directed network, each edge has a direction, running from one node to another, such as from the sender of a message to its receiver. A convenient way to store a network is as an n \times n adjacency matrix \bm{A}, where a_{ij} = 1 if there is an edge from node i to node j, and a_{ij} = 0 otherwise. The adjacency matrix of an undirected network is symmetric, while that of a directed network need not be. Sometimes more than one edge can join the same pair of nodes (for example, when each message sent is recorded as an edge), and then a_{ij} counts the number of edges from i to j. This chapter uses examples of both kinds of network: the US Senate co-voting networks are undirected, while the UCI message networks are directed.
Several kinds of anomaly can be of interest in a dynamic network: anomalous individual nodes, anomalous edges, anomalous subgraphs, or an anomalous network as a whole (Akoglu et al., 2015). Following the definition of an anomaly used throughout this book, in each case we are looking for something with very low probability of occurring relative to an appropriate reference group: a node compared to the rest of its network, or a whole network compared to the rest of a sequence. This chapter covers two of these problems. The simpler problem, finding anomalous nodes within a single network, comes first; it needs only the high-dimensional anomaly detection methods of Chapter 9. From Section 16.2 onwards, the chapter turns to anomalous networks within a longer sequence, which additionally requires the time series tools of Chapter 12.
Statistical methods have a long history of success in modelling temporal dependence, but they have been underused for network anomaly detection compared to purely graph-theoretic approaches (Ranshous et al., 2015). For the whole-network problem, this chapter describes oddnet, a method due to Kandanaarachchi & Hyndman (2022) that fuses network analysis with time series modelling; the R package oddnet implements the algorithm.
Before we begin, let’s load the packages we will need, and define a few functions for plotting.
Code
# Colours for the party-coloured network plots, matching the conventional
# US media scheme (Democrat = blue, Republican = red) rather than the book's
# default alphabetical discrete palette assignment.
party_palette <- c(
Democrat = "#0072B2",
Republican = "#B2182B",
common = "#009E73"
)
# Plot a network using a Fruchterman–Reingold layout, optionally coloured by
# a vertex grouping (e.g. political party).
network_plot <- function(
gr,
group = NULL,
palette = NULL,
title = NULL,
seed = 1967
) {
set.seed(seed)
if (!is.null(group)) {
gr <- set_vertex_attr(gr, "group", value = group)
p <- ggraph(gr, layout = "fr") +
geom_edge_link(edge_colour = "grey70", edge_width = 0.2) +
geom_node_point(aes(colour = group), size = 1.3)
if (!is.null(palette)) {
p <- p + scale_colour_manual(values = palette)
}
} else {
p <- ggraph(gr, layout = "fr") +
geom_edge_link(edge_colour = "grey70", edge_width = 0.2) +
geom_node_point(colour = "#0072B2", size = 1.3)
}
p +
theme_void() +
theme(legend.position = "none", plot.title = element_text(size = 11)) +
labs(title = title)
}
# Plot the oddnet surprisal probability of each network over time, with
# the alpha threshold shown as a dashed line.
prob_plot <- function(x, prob, alpha = 0.05, xlab = "") {
tibble(x = x, prob = prob) |>
ggplot(aes(x = x, y = prob)) +
geom_line() +
geom_point() +
geom_hline(yintercept = alpha, linetype = "dashed", colour = "#D55E00") +
labs(x = xlab, y = "Surprisal probability")
}16.1 Anomalous nodes within a network
Given a single network, which of its nodes behave unusually compared to the rest? Each node becomes an observation, and measures of its centrality and its role in the network’s community structure become its features — the same idea used throughout this book for other kinds of data, and no different in principle to the projections of Chapter 9. Because there is no time ordering among the nodes of a single network, we can go straight to dimension reduction and anomaly detection, without the time series modelling step used later in this chapter for sequences of networks.
The US Senate co-voting network, described by Lee et al. (2020), provides a natural setting to try this. Each node is a senator, and an edge connects two senators if they vote the same way (both yea or both nay) on at least 80% of the bills for which they were both present, across the 40th to 113th Congress (1867 to 2015). From the 84th Congress (1955–1957) onwards, the President is also included as a node, with the President’s announced positions on bills treated as votes. So each Congress gives an undirected network, with a_{ij} = a_{ji} = 1 if senators i and j co-vote at least 80% of the time, and a_{ij} = 0 otherwise. The weird package contains these data as two tibbles: us_senate_edges gives the co-voting edges for each Congress, and us_senate_members gives each senator’s name, state and party, with senators numbered from 1 within each Congress. The following code turns them into a list of adjacency matrices, one for each Congress, along with a matching list of party labels.
senate_congress <- sort(unique(us_senate_members$congress))
senate_party <- lapply(senate_congress, \(cg) {
us_senate_members |>
dplyr::filter(congress == cg) |>
dplyr::arrange(node) |>
dplyr::pull(party)
})
senate_networks <- lapply(seq_along(senate_congress), \(i) {
edges <- us_senate_edges |>
dplyr::filter(congress == senate_congress[i]) |>
dplyr::select(from, to)
gr <- graph_from_data_frame(
edges,
directed = FALSE,
vertices = data.frame(name = seq_along(senate_party[[i]]))
)
as.matrix(as_adjacency_matrix(gr))
})
congress100 <- which(senate_congress == 100)As an illustration, consider the 100th Congress (1987–1989). Figure 16.1 shows this network, coloured by party.
Code
senate_networks[[congress100]] |>
graph_from_adjacency_matrix(mode = "undirected") |>
network_plot(
group = senate_party[[congress100]],
palette = party_palette
)
For each senator (and the President), we compute six igraph features that describe their position in the co-voting network.
Degree is simply the number of edges attached to a node, d_i = \sum_{j} a_{ij} for an undirected network — here, the number of other senators a given senator co-votes with sufficiently often to share an edge. It is the most basic measure of how connected a node is, but it says nothing about where those connections lead.
Several of the remaining features depend on how far apart nodes are. A path from node j to node k is a sequence of edges leading from j to k, and the distance \delta_{jk} is the number of edges in the shortest such path (with \delta_{jk} = \infty if there is no path).
Betweenness centrality counts, for a given node, how many of the shortest paths between all other pairs of nodes pass through it. If \sigma_{jk} is the number of shortest paths between nodes j and k, and \sigma_{jk}(i) is the number of those that pass through node i, then the betweenness of node i in an undirected network is b_i = \sum_{\substack{j < k\\ j,k \ne i}} \frac{\sigma_{jk}(i)}{\sigma_{jk}}, where the sum is over pairs with at least one path between them. (For a directed network, the sum is over all ordered pairs (j,k).) A senator with high betweenness lies on many of the shortest routes connecting pairs of colleagues, so removing them from the network would make those colleague pairs much more distant from one another; such senators act as bridges between groups that would otherwise vote quite separately.
Closeness centrality is the inverse of the sum of the shortest-path distances from a node to every other node it can reach in the network, c_i = 1\big/\sum_{j} \delta_{ij}, where the sum is over the nodes j \ne i with \delta_{ij} < \infty. A senator with high closeness can reach any other senator’s voting bloc in relatively few steps, whereas a senator with low closeness is, on average, many steps removed from the rest of the chamber.
PageRank, originally developed by the founders of Google to rank web pages by importance, assigns each node a score based on the scores of the nodes linking to it, so a node is considered important if it is connected to other important nodes, not merely to many nodes. The PageRank scores p_1,\dots,p_n satisfy
p_i = \frac{1 - \gamma}{n} + \gamma \sum_{j} \frac{a_{ji}}{d_j} p_j,
where d_j is the number of edges leaving node j (its degree, for an undirected network), so each node shares its own score equally among the nodes it links to. The damping factor \gamma is usually set to 0.85 (the igraph default); the first term ensures that every node receives some score, even if nothing links to it. Nodes with no outgoing edges (such as isolated senators) have nowhere to send their score, so igraph spreads it evenly over all nodes. The equations are solved iteratively, and the scores sum to one. Applied here, a senator has high PageRank if they co-vote with other senators who are themselves well-connected, rather than simply co-voting with a large number of colleagues.
Coreness describes how deeply a node sits within the network’s most densely connected part. A node has coreness k if k is the largest value for which it belongs to a subgraph in which every node has degree at least k within that subgraph, found by repeatedly stripping away the nodes with the smallest remaining degree. Senators with high coreness sit within a tightly interconnected core of colleagues who mostly co-vote with each other.
Transitivity, also called the local clustering coefficient, measures what proportion of the pairs of a senator’s co-voting partners also co-vote with each other. Let \tau_i be the number of triangles containing node i; that is, the number of pairs of neighbours of i that are themselves connected. For an undirected network, \tau_i = \frac{1}{2}\sum_{j,k} a_{ij}a_{jk}a_{ki}, which is half the ith diagonal element of \bm{A}^3. Node i has \binom{d_i}{2} pairs of neighbours, so its transitivity is \ell_i = \tau_i\big/\binom{d_i}{2}. This is undefined for nodes with fewer than two neighbours, and we set it to zero for them. If a senator co-votes with both senator B and senator C, high transitivity means B and C are also likely to co-vote with one another, indicating that the senator sits within a tightly knit voting clique rather than bridging otherwise unconnected colleagues.
senate100_gr <- graph_from_adjacency_matrix(
senate_networks[[congress100]],
mode = "undirected"
)
senate_node_features <- tibble(
name = us_senate_members |>
filter(congress == 100) |>
arrange(node) |>
pull(name),
party = senate_party[[congress100]],
degree = degree(senate100_gr),
betweenness = betweenness(senate100_gr),
closeness = closeness(senate100_gr),
pagerank = page_rank(senate100_gr)$vector,
transitivity = transitivity(senate100_gr, type = "local", isolates = "zero"),
coreness = coreness(senate100_gr)
) |>
mutate(closeness = if_else(is.nan(closeness), 0, closeness))Closeness is undefined for senators with no co-voting partners at all, so we set it to zero for those 3 isolated senators. The features are measured on very different scales (betweenness runs into the thousands, while closeness is of the order of 0.001), so we first standardise each feature to have mean zero and unit variance, as in Chapter 9. Otherwise the principal components would be dominated by whichever features happen to have the largest variance. As elsewhere in this book, we then reduce these six features to two dimensions with robust PCA (Section 9.5), and apply the lookout algorithm (Section 7.5) via the surprisals_prob() function already used in Section 7.6.
senate_node_pca <- pcaPP::PCAproj(
senate_node_features |>
select(-name, -party) |>
mvscale(center = mean, scale = sd, cov = NULL),
k = 2,
scale = NULL,
center = NULL
)
senate_node_features <- senate_node_features |>
mutate(
prob = surprisals_prob(
as_tibble(senate_node_pca$scores),
loo = TRUE,
approximation = "gpd",
method = "lookout"
)
)
senate_node_features |>
arrange(prob) |>
select(name, party, degree, betweenness, prob) |>
head(5)# A tibble: 5 × 5
name party degree betweenness prob
<chr> <chr> <dbl> <dbl> <dbl>
1 ZORINSKY, Edward Democrat 49 2122. 0.0000310
2 ROTH, William Victor, Jr. Republican 0 0 0.0205
3 EVANS, Daniel Jackson Republican 0 0 0.0205
4 PROXMIRE, William Democrat 0 0 0.0205
5 MURKOWSKI, Frank Hughes Republican 25 861. 0.0339
Five senators fall below the \alpha = 0.05 threshold used throughout this chapter, and they are of two kinds. By far the most anomalous, with a surprisal probability of 0.00003, is Edward Zorinsky, a Democrat from Nebraska with the highest betweenness centrality in the chamber, sitting on far more shortest paths between colleagues than anyone else. Frank Murkowski, a Republican from Alaska with the second-highest betweenness, is also flagged. A senator with high betweenness is one whose voting pattern regularly links senators who otherwise vote in separate blocs. Zorinsky is a special case, though. He died in March 1987, two months into the Congress, and was replaced by David Karnes, so his edges are based only on the votes held before his death. He accounts for four of the eight edges between the two parties. One of these links him to Murkowski, and it is Murkowski’s only edge to a Democrat. Without Zorinsky, Murkowski’s betweenness falls from 861 to 268 and he is no longer flagged, so his anomaly is a by-product of Zorinsky’s. The remaining three flagged senators, William Roth and Daniel Evans (both Republicans) and William Proxmire (a Democrat), are isolated: they have no co-voting partners at all, so all their features except PageRank are zero.
Figure 16.2 shows the two-dimensional projection used for detection, with the flagged senators highlighted. They lie on the edges of the point cloud, although some unflagged senators are also far from the bulk of the chamber; lookout flags points in low-density regions, not simply those far from the centre.
Code
senate_node_scores <- as_tibble(senate_node_pca$scores) |>
mutate(
flagged = senate_node_features$prob < 0.05,
surname = stringr::str_to_title(sub(",.*", "", senate_node_features$name))
)
# One label per point, so the isolated senators share a label
senate_node_labels <- senate_node_scores |>
filter(flagged) |>
summarise(label = paste(surname, collapse = ", "), .by = c(Comp.1, Comp.2))
senate_node_scores |>
ggplot(aes(x = Comp.1, y = Comp.2, colour = flagged)) +
geom_point() +
ggrepel::geom_text_repel(
# Unflagged points get empty labels, so the labels avoid them too
data = bind_rows(
senate_node_labels,
senate_node_scores |> filter(!flagged) |> mutate(label = "")
),
aes(label = label),
colour = "#D55E00"
) +
scale_colour_manual(values = c(`FALSE` = "#0072B2", `TRUE` = "#D55E00")) +
guides(colour = "none") +
labs(x = "Component 1", y = "Component 2")
The 100th Congress was picked somewhat arbitrarily here, just to illustrate the method. But later in the chapter, in Section 16.3, we look for anomalies across the whole 74-Congress sequence rather than within a single one, and find that the 100th Congress is flagged there too, as the single most unusual network in the entire sequence. That result does not depend on Zorinsky: as shown in Section 16.3, removing him from the 100th Congress makes it even more anomalous as a whole network.
The same recipe — compute node features with igraph, reduce their dimension, and apply lookout — works for any single network, not just this one. We now turn to a different question: instead of looking for unusual nodes within one network, can we find an unusual network within a longer sequence?
16.2 Anomalous networks within a sequence
Suppose now that we observe a sequence of networks \mathcal{G}_1, \mathcal{G}_2, \dots over time. Unlike the node-level problem, finding an anomalous network in the sequence requires modelling the temporal dependence between networks, which oddnet builds up in three steps: mapping each network to a feature vector, modelling each feature series over time, and finally reducing dimension and detecting anomalies in the resulting residuals.
From networks to features
The obvious way to compare two networks is to look at them. But networks resist direct comparison much more than numerical data do: two networks with a very different number of edges can look superficially similar when drawn, while two networks that look very different might have almost identical numbers of nodes, edges, and connected components. So instead, we compute a vector of numerical summary features from each network, and compare networks via their features.
Let f be a function mapping a network \mathcal{G} to a vector of m features, \bm{x} = f(\mathcal{G}) \in \mathbb{R}^m. For this to be useful for anomaly detection, f needs to be rich enough that an anomalous network also produces an anomalous feature vector. A single feature, such as the number of edges, will catch some anomalies (a sudden change in overall connectivity) while missing others (a network in which the same number of edges is rewired to run through a single hub node). So oddnet computes m = 20 features from each network, covering size, density, centrality and community structure, using the igraph package (Csárdi & Nepusz, 2006). These are whole-network analogues of the node-level features used in Section 16.1.
To illustrate, we compute these features for the same 100th Congress network used in Section 16.1.
features_100 <- graph_from_adjacency_matrix(
senate_networks[[congress100]],
mode = "undirected"
) |>
compute_features()
tibble(
feature = names(features_100)[1:20],
value = as.numeric(features_100[1:20])
)# A tibble: 20 × 2
feature value
<chr> <dbl>
1 num_nodes 102
2 triangles_99 1118
3 degree_99 51.0
4 edges 1495
5 density 0.290
6 clustering_coef 0.907
7 assortativity 0.779
8 mean_distance 2.46
9 diameter 6
10 isolates 0.0294
11 connectivity 0
12 efficiency 0.516
13 num_clusters 4
14 cluster_size_99 96.1
15 close_overpoint8 0
16 betweenness_99 859.
17 pagerank_99 0.0157
18 cores_99 42
19 hubs_value 2169.
20 authority_value 2169.
These features fall into three broad groups.
Some are simple size and density measures: the number of nodes and edges, the density (the proportion of all possible edges that are actually present, given by \sum_{i<j} a_{ij}\big/\binom{n}{2} for an undirected network, or \sum_{i \ne j} a_{ij}\big/[n(n - 1)] for a directed network), and the proportion of isolated nodes with no edges at all.
Others are centrality measures, several of which we already defined at the node level in Section 16.1: degree, betweenness, closeness, PageRank and coreness. Two further centrality measures appear only here. A node’s hub score is high if it links to many good “authorities”, and a node’s authority score is high if it is linked to by many good hubs; the two scores are defined jointly, each reinforcing the other, in the same iterative spirit as PageRank. They were originally developed to distinguish web pages that provide a good list of links (hubs) from pages that are themselves worth linking to (authorities). Writing h_i for the hub score and q_i for the authority score of node i, these ideas become h_i \propto \sum_j a_{ij}q_j and q_i \propto \sum_j a_{ji}h_j. Substituting one into the other shows that the vector of hub scores is the leading eigenvector of \bm{A}\bm{A}^\intercal, and the vector of authority scores is the leading eigenvector of \bm{A}^\intercal\bm{A}. Degree, triangles, betweenness, PageRank and coreness each produce a whole distribution of values across the nodes of a network, so oddnet summarises each of them with a single number, the 99th percentile of that distribution, focusing on the most extreme nodes for each measure since anomaly detection is more concerned with unusual tails than with typical values. Closeness is summarised differently: oddnet records the proportion of nodes with closeness of at least 0.8. Since c_i = 1\big/\sum_j \delta_{ij}, and each distance is at least one, c_i \ge 0.8 only when node i can reach exactly one other node (such as either node of an isolated pair), so this feature is usually zero for a well-connected network. The hub and authority scores are summarised differently again, using the largest eigenvalue of \bm{A}\bm{A}^\intercal and of \bm{A}^\intercal\bm{A} respectively, a property of the network as a whole rather than of any individual node. For an undirected network, \bm{A} is symmetric, so both matrices are equal to \bm{A}^2, and these two features are identical.
The remaining features describe the overall structure of the network, rather than any individual node within it. The triangle count \tau_i was defined along with transitivity in Section 16.1; oddnet again uses the 99th percentile of \tau_1,\dots,\tau_n, alongside the network-wide clustering coefficient \sum_i \tau_i \big / \sum_i \binom{d_i}{2}, the proportion of all pairs of neighbours (across all nodes) that are themselves connected. Assortativity measures whether nodes tend to connect to other nodes with a similar degree to their own: a network is assortative if well-connected nodes mostly link to other well-connected nodes, and disassortative if well-connected nodes tend to link to poorly connected ones. The diameter is the largest distance \delta_{ij} between any two nodes in the network, and the mean distance is the average of \delta_{ij} over all pairs of nodes (in both cases ignoring pairs with no path between them, where \delta_{ij} = \infty); both describe how spread out the network is, in the same spirit as closeness centrality, but summarised across the whole network rather than computed for a single node. A network’s nodes need not all be reachable from one another: the number of connected components counts how many separate pieces the network breaks into, and oddnet also records the 99th percentile of the component sizes (which is close to, but not always equal to, the size of the largest component). Finally, vertex connectivity counts the minimum number of nodes that would need to be removed to disconnect the network, and global efficiency is the average of 1/\delta_{ij} over all pairs of nodes i \ne j (with 1/\infty = 0), so that networks with many short paths between nodes are more efficient than those relying on a few long ones.
Computing the total number of edges for every Congress in the sequence, and plotting it over time in Figure 16.3, does not make the 100th Congress obviously anomalous: it sits within a noisy, generally increasing trend in the number of co-voting edges across the whole 74-Congress sequence.
senate_edges_n <- sapply(senate_networks, \(m) {
gsize(graph_from_adjacency_matrix(m, mode = "undirected"))
})Code
tibble(congress = senate_congress, edges = senate_edges_n) |>
ggplot(aes(x = congress, y = edges)) +
geom_line() +
geom_point(
data = ~ dplyr::filter(.x, congress == 100),
colour = "#D55E00",
size = 2
) +
labs(x = "Congress", y = "Number of edges")
The 100th Congress’s raw edge count ranks only 14th out of 74 Congresses — not remotely the most extreme value in the sequence. Not every anomaly will show up as an obvious spike in a raw feature, especially once we allow for trend and seasonality in how a feature evolves over time. For that, we need to bring in the time series tools from Chapter 12.
Modelling temporal dependence
Because the networks \mathcal{G}_1, \mathcal{G}_2, \dots arrive in a sequence, so does each feature: x_{t,1}, x_{t,2}, \dots, x_{t,m} traces out m separate univariate time series, one per feature. This means we can bring the full machinery of time series anomaly detection to bear, rather than comparing raw feature values directly. In particular, we can fit an ARIMA model (Hyndman & Athanasopoulos, 2021, Ch. 9) to each feature series in turn, and work with the residuals e_{t,i} = x_{t,i} - \hat{x}_{t,i}, where \hat{x}_{t,i} is the value forecast from the history of that feature alone. If the ARIMA model has captured the trend and any seasonal pattern in the feature, the residuals should show no remaining temporal structure, so that an anomalous network shows up as an unusually large residual, regardless of whatever trend or seasonality it sits on top of.
To see why this matters, we fit an ARIMA model to the Senate edge-count series shown in Figure 16.3.
senate_edges_ts <- tsibble(
congress = senate_congress,
edges = senate_edges_n,
index = congress
)
senate_edges_fit <- senate_edges_ts |> model(arima = ARIMA(edges))
senate_edges_resid <- senate_edges_fit |> augment()Figure 16.4 shows the residuals from this model. The 100th Congress is now the single most extreme residual in the whole sequence, ranked 1st out of 74, compared to 14th for the raw edge count in Figure 16.3. The ARIMA model has removed the general upward trend in the series, leaving behind only what is unusual about each Congress.
Code
senate_edges_resid |>
ggplot(aes(x = congress, y = .innov)) +
geom_line() +
geom_point(
data = ~ dplyr::filter(.x, congress == 100),
colour = "#D55E00",
size = 2
) +
labs(x = "Congress", y = "Residual")
Applying this same idea to each of the m = 20 network features gives a residual vector \bm{e}_t = (e_{t,1}, \dots, e_{t,m})^\intercal for every network in the sequence, with the temporal dependence in each feature removed. An anomalous network should now correspond to an unusually large \bm{e}_t.
From residuals to anomalies
We now have a sequence of m-dimensional residual vectors, and need to decide which are anomalous. As discussed in Chapter 9, anomaly detection in high dimensions is hard: points are far apart, and errors in different features can be correlated with one another. oddnet addresses this in two steps.
First, the residuals are projected onto a two-dimensional subspace using a robust form of PCA. We already met the idea of robustifying PCA in Section 9.5: rather than finding the directions of maximum variance using every observation (which lets anomalies pull the projection towards themselves), a robust method down-weights unusual observations when estimating the projection directions. oddnet uses a different robust PCA method to the ROBPCA algorithm of Section 9.5, namely projection pursuit (implemented in pcaPP::PCAproj(), Filzmoser et al., 2026), but the underlying principle is the same. This is the same function we used to reduce the node-level features in Section 16.1.
Second, the two-dimensional projection is searched for anomalies using the lookout algorithm from Section 7.5, which computes leave-one-out kernel density surprisal probabilities. A network is flagged as anomalous if its surprisal probability, as estimated by lookout, falls below a threshold \alpha (\alpha = 0.05 is used throughout this chapter, following Kandanaarachchi & Hyndman (2022)).
The oddnet algorithm
Putting these pieces together, oddnet proceeds as follows.
Step 1: Compute features. Map each network \mathcal{G}_t to its feature vector \bm{x}_t = f(\mathcal{G}_t) \in \mathbb{R}^{m}, as described in “From networks to features” above. Any feature that is missing for every network, or that takes the same value for every network, carries no information about which networks are unusual, and is dropped.
Step 2: Model each feature series. Fit an ARIMA model to each of the remaining feature series in turn, and compute the residuals \bm{e}_t, as described in “Modelling temporal dependence” above.
Step 3: Reduce dimension. Standardise each residual series using a trimmed mean and a trimmed standard deviation, which ignore the 0.5% of values in each tail, so that the anomalies we are looking for do not distort the scaling. With fewer than 200 networks, as in both examples below, 0.5% of the values is less than one observation, so the trimmed mean is just the ordinary mean, while the trimmed standard deviation still leaves out the largest and smallest squared deviations. Then project the standardised residual vectors onto two dimensions using robust PCA.
Step 4: Detect anomalies. Apply the lookout algorithm to the two-dimensional projection, giving a surprisal probability for each network.
This is implemented in the anomalous_networks() function, which takes a list of adjacency matrices and returns the estimated surprisal probabilities. Because these are computed from the residuals of the time series models, they are conditional on the history of each feature: a network is flagged when it is surprising given the networks that preceded it, which is why Kandanaarachchi & Hyndman (2022) call them conditional probabilities. We now apply it to the full sequence of Senate co-voting networks.
16.3 Example: US Senate co-voting networks
We already used one Congress from this data set, the 100th, to find anomalous individual senators in Section 16.1. Now we ask a different question of the full 74-Congress sequence: is any single Congress, as a whole network, unusual compared to the rest?
Figure 16.5 shows the co-voting network for four Congresses, coloured by party. The 40th Congress is very sparse: most senators are isolated, and the largest connected group is small and mixes the two parties. In the later Congresses shown, each party forms its own bloc, but the links between the blocs vary: there are none at all in the 64th Congress and only a handful in the 113th, while in the 89th a few Republicans co-vote with many Democrats.
Code
senate_gr <- function(i) {
senate_networks[[i]] |>
graph_from_adjacency_matrix(mode = "undirected") |>
network_plot(
group = senate_party[[i]],
palette = party_palette,
title = paste(scales::ordinal(senate_congress[i]), "Congress")
)
}
patchwork::wrap_plots(
senate_gr(1),
senate_gr(25),
senate_gr(50),
senate_gr(74),
nrow = 1
)
Applying anomalous_networks() to the full sequence:
senate_result <- anomalous_networks(senate_networks, mode = "undirected")
senate_probs <- tibble(
congress = senate_congress,
prob = senate_result$outlier_probability
)
senate_probs |> dplyr::arrange(prob) |> head()# A tibble: 6 × 2
congress prob
<int> <dbl>
1 100 0.000804
2 43 0.0144
3 95 0.0353
4 54 0.0359
5 67 0.0447
6 40 0.0698
Figure 16.6 shows the surprisal probability of every Congress.
Code
prob_plot(senate_congress, senate_result$outlier_probability, xlab = "Congress")
As anticipated in Section 16.1, the 100th Congress (1987–1989) stands out as by far the most anomalous, with a surprisal probability of 0.0008. Compared with its neighbours, this Congress had many more co-voting edges (Figure 16.3), and a few edges between the parties where the 99th and 101st Congresses had none. Half of these cross-party edges involve Zorinsky, whose short term was discussed in Section 16.1; the others link the Republican Lowell Weicker to three Democrats, and the Republican Robert Stafford to the Democrat Brock Adams. Removing Zorinsky from the 100th Congress makes it even more anomalous, with a surprisal probability of 0.0002, so the result is not an artefact of his short term. The 100th Congress is also the top anomaly in the Laplacian-based analysis of Huang et al. (2020), but their sequence is a different Senate network, based on bill co-sponsorship rather than co-voting and covering only the 97th to 108th Congresses. Of the five Congresses below the \alpha = 0.05 threshold, the next most anomalous is the 43rd Congress (1873–1875), with a surprisal probability of 0.0144. This Congress sat during the Panic of 1873, a severe economic depression that was known as “the Great Depression” until the 1929 crash claimed the name — a period of considerable political instability that plausibly disrupted the usual voting coalitions.
16.4 Example: UCI message network
Our second example is a directed network, at a much finer time granularity, from an entirely different domain. Panzarasa et al. (2009) recorded private messages sent between students on an online platform at the University of California, Irvine, from April to October 2004. A directed edge runs from sender to receiver each time a message is sent, and the data are available in the tnet package (Opsahl, 2026).
uci_messages <- tnet::OnlineSocialNetwork.n1899.lnet |>
mutate(date = as_date(as_datetime(t)))
# Remove self-loops (rows where sender and receiver are the same student)
n_selfloops <- sum(uci_messages$i == uci_messages$j)
uci_messages <- uci_messages |> dplyr::filter(i != j)
uci_dates <- unique(uci_messages$date)
uci_networks <- lapply(uci_dates, \(d) {
edges <- uci_messages |> dplyr::filter(date == d) |> dplyr::select(i, j)
as.matrix(as_adjacency_matrix(graph_from_data_frame(edges)))
})The data also contain 1,899 rows in which the sender and receiver are the same student, one for each student in the data set; these are not messages between students, so we have removed them. This gives 193 daily networks, one for each day on which at least one message was sent (numbered in that order as day 1, day 2, and so on), ranging in size from a handful of active students on the first few days to several hundred during May, after which activity gradually tails off. Figure 16.7 shows three of these daily networks, illustrating how sparse activity in the first few days (day 3) contrasts with much busier days (days 22 and 42).
Code
uci_gr <- function(i) {
network_plot(
graph_from_adjacency_matrix(uci_networks[[i]]),
title = paste("Day", i)
)
}
patchwork::wrap_plots(uci_gr(3), uci_gr(22), uci_gr(42), nrow = 1)
Because the daily networks vary hugely in size, some features (the clustering coefficient and the assortativity) are undefined on the smallest, sparsest days. We set these missing features to zero before running oddnet. The proportion of isolated nodes is zero on every day, because students only appear in a daily network if they sent or received a message that day, and the vertex connectivity is also zero on every day. So oddnet drops these two features, leaving 18.
uci_result <- anomalous_networks(uci_networks, na_action = "zero")Warning in sqrt(diag(best$var.coef)): NaNs produced
uci_flagged <- uci_dates[uci_result$outliers$Outliers]
uci_flagged [1] "2004-04-19" "2004-04-24" "2004-05-03" "2004-05-13" "2004-05-22" "2004-05-28"
[7] "2004-05-29" "2004-06-15" "2004-06-27" "2004-09-24" "2004-10-09" "2004-10-26"
Figure 16.8 shows the surprisal probability of every day.
Code
prob_plot(uci_dates, uci_result$outlier_probability, xlab = "Date")
Unlike the Senate network, which drifts slowly over decades, this network is driven by the rhythm of the academic calendar. The two most anomalous days are 19 April and 28 May. On 19 April, only the third day on which any messages were sent, the network suddenly grew from 2 to 16 students, early in the platform’s initial rapid growth phase identified by Panzarasa et al. (2009). Of the other ten flagged days, 22 and 29 May are close to 28 May, near the end of that growth phase, while 15 June fell during the Spring final examinations and 24 September was the first day of Fall instruction. The Senate and UCI examples illustrate quite different anomaly patterns: single Congresses that depart from a structure drifting slowly over decades, against short bursts of activity tied to a fixed calendar.
16.5 Summary
The key idea in this chapter is the same one used for time series in Section 12.3: networks are hard to compare directly, so we summarise each node, or each whole network, by a vector of numerical features, and then use the anomaly detection methods of earlier chapters on those features.
To find anomalous nodes within a single network, each node is described by measures such as its degree, betweenness, closeness, PageRank, coreness and transitivity. After standardising these features, they can be reduced to a few dimensions with robust PCA, and then any of the methods of earlier chapters, such as lookout, can be applied. Anomalous nodes may be unusually central, such as nodes that bridge otherwise separate groups, or unusually isolated.
To find anomalous networks within a sequence, oddnet computes 20 features for each network, removes the temporal dependence in each feature series using ARIMA models, and then applies robust PCA and lookout to the residuals. Modelling the temporal dependence matters: a network may not stand out in its raw features, but be clearly anomalous once trends and other temporal structure have been removed.
As with the time series features of Section 12.3, the choice of features determines which anomalies can be found. A change in a network that does not affect any of the features will not be detected; for example, if a Democrat and a Republican swapped all their co-voting partners, the network would be politically very unusual, but it would have exactly the same structure as before, so every one of the whole-network features would be unchanged. In terms of the adjacency matrix, swapping two nodes replaces \bm{A} by \bm{P}\bm{A}\bm{P}^\intercal, where \bm{P} is the permutation matrix that swaps the corresponding rows, and every feature computed by oddnet is unaffected by such permutations. Anomalous edges and anomalous subgraphs have not been considered in this chapter.
Further reading
Kolaczyk (2009) gives a thorough introduction to the statistical analysis of network data. Akoglu et al. (2015) survey anomaly detection methods for graphs, while Ranshous et al. (2015) focus on dynamic networks, covering anomalous nodes, edges, subgraphs and whole networks. An extension of oddnet that uses extreme value theory to model the feature residuals is described by Kandanaarachchi et al. (2024).