Sparse matrices for large graphs and their computational cost
Environment
Python 3.14.6, NumPy 2.4.6, SciPy 1.18.1, NetworkX 3.7, Matplotlib 3.11.2 (Jupyter Notebook).
This article is a rewrite of a post from around 2021, with calculations performed in the environment described above.
Book: Graph Theory and Practice
Chapter: Graph basics and matrix representations
Overview
An adjacency matrix has entries even where no edge exists. With many vertices and few neighbors per vertex, storing every entry stores mostly zeros. This article introduces sparse matrices, which omit those zeros.
We inspect COO, CSR, and CSC using a small undirected graph and derive storage requirements and matrix–vector multiplication costs. We then construct a 100,000-vertex graph in SciPy, measure execution times, and examine how matrix products can increase the number of nonzero entries.
Setup
Run cells in order. Round values to three significant figures only for display.
Check the environment, import libraries, and configure plots
import platform
import sys
from pathlib import Path
from pprint import pprint
from timeit import repeat
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import font_manager
from matplotlib.colors import ListedColormap
from matplotlib.patches import Rectangle
from matplotlib.ticker import FuncFormatter, MaxNLocator
from matplotlib_inline.backend_inline import set_matplotlib_formats
import networkx as nx
import numpy as np
import scipy
from scipy.sparse import coo_array, csr_array
from IPython.display import Math, SVG, display
%matplotlib inline
set_matplotlib_formats('svg')
# 表示だけを有効数字3桁にそろえ、計算中の値は丸めない。
def sig3(value):
return format(float(value), '#.3g').removesuffix('.')
np.set_printoptions(formatter={'float_kind': sig3}, linewidth=100)
# 利用可能な日本語フォントを選ぶ。SVGには文字の輪郭を埋め込む。
font_names = {font.name for font in font_manager.fontManager.ttflist}
for candidate in ['Hiragino Sans', 'Noto Sans CJK JP', 'IPAexGothic', 'YuGothic']:
if candidate in font_names:
plt.rcParams['font.family'] = candidate
break
plt.rcParams.update({
'font.size': 11,
'axes.spines.top': False,
'axes.spines.right': False,
'axes.unicode_minus': False,
'svg.fonttype': 'path',
'svg.hashsalt': 'graph-theory-103',
})
# 通常のNotebook起動と、リポジトリ直下からの実行に対応する。
notebook_dir = Path.cwd()
if (notebook_dir / 'pyproject.toml').is_file():
notebook_dir = notebook_dir / 'series/graph-theory/103'
figure_dir = notebook_dir / '103_nb_files'
figure_dir.mkdir(parents=True, exist_ok=True)
def save_figure(fig, filename):
path = figure_dir / filename
fig.savefig(path, format='svg', bbox_inches='tight', metadata={'Date': None})
plt.close(fig)
display(SVG(filename=str(path)))
def matrix_tex(values):
# 本記事の整数行列・整数ベクトルをLaTeXの行列に変換する。
rows = np.atleast_2d(values)
body = r' \\\\ '.join(' & '.join(str(int(v)) for v in row) for row in rows)
return r'\begin{bmatrix}' + body + r'\end{bmatrix}'
print('環境名: wa-src(3.14.6)')
print(f'Python: {platform.python_version()}')
print(f'OS: {platform.system()} / {platform.machine()}')
print(f'NumPy: {np.__version__}, SciPy: {scipy.__version__}')
print(f'Matplotlib: {matplotlib.__version__}, NetworkX: {nx.__version__}')
print(f'画像ディレクトリ: {figure_dir.name}')
assert sys.version_info[:3] == (3, 14, 6), '指定のPython環境で実行すること'
環境名: wa-src(3.14.6)
Python: 3.14.6
OS: Darwin / arm64
NumPy: 2.4.6, SciPy: 1.18.1
Matplotlib: 3.11.2, NetworkX: 3.7
画像ディレクトリ: 103_nb_files
1. Vertices, edges, and nonzero entries
Let $V$ and $E$ be the vertex and edge sets, with $n=|V|$ vertices and $m=|E|$ edges. Following Python, number vertices from $0$ through $n-1$. First consider an unweighted, undirected graph without self-loops or parallel edges.
Define the entries of the adjacency matrix $\mathbf{A}\in\mathbb{R}^{n\times n}$ as follows.
$$ A_{ij}=\begin{cases} 1 & \{i,j\}\in E,\\ 0 & \{i,j\}\notin E. \end{cases} $$
Each edge $\{i,j\}$ appears in both $A_{ij}$ and $A_{ji}$. Let $q$ be the nonzero count, $i$ a vertex, $d_i$ its degree, and $\bar d$ the average degree. Then
$$ q=\sum_{i=0}^{n-1}d_i=2m,\qquad \bar d=\frac{2m}{n},\qquad q=n\bar d. $$
Among all $n^2$ entries, define matrix density as the nonzero fraction $\rho=q/n^2$. This differs from graph density $2m/[n(n-1)]$, which excludes self-loops. For fixed average degree, $q=O(n)$ and $\rho=\bar d/n$ decreases as the vertex count grows. In a directed graph with one entry per edge, $q=m$.
A six-vertex example
Use edges $\{0,1\},\{0,3\},\{1,2\},\{1,3\},\{3,4\}$. Vertex 5 is isolated, and $n=6$, $m=5$, and $q=10$. Figure 1 shows the graph on the left and its adjacency matrix on the right.
n = 6
edges = np.array([(0, 1), (0, 3), (1, 2), (1, 3), (3, 4)], dtype=np.int32)
# 無向辺は両方向に登録する。密な行列を経由せずCOOを作成する。
rows = np.concatenate([edges[:, 0], edges[:, 1]])
cols = np.concatenate([edges[:, 1], edges[:, 0]])
values = np.ones(len(rows), dtype=np.float64)
A_coo = coo_array((values, (rows, cols)), shape=(n, n))
A = A_coo.tocsr()
A.sum_duplicates()
A.eliminate_zeros()
A.sort_indices()
# 全要素の表示のため、この6×6行列だけを密行列にする。
A_dense = A.toarray()
pprint(A_dense)
display(Math(r'\mathbf{A}=' + matrix_tex(A_dense)))
G = nx.Graph()
G.add_nodes_from(range(n))
G.add_edges_from(edges.tolist())
positions = {0: (0, 1), 1: (1, 1), 2: (2, 1), 3: (0, 0), 4: (1, 0), 5: (2, 0)}
fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout='constrained')
nx.draw_networkx(
G, pos=positions, ax=axes[0], node_size=850,
node_color=['#c8def0'] * 5 + ['#f5d7a5'], edgecolors='#466278',
width=2, font_size=12,
)
axes[0].set_title('図1a 無向グラフ(頂点5は孤立点)')
axes[0].set_axis_off()
axes[0].margins(x=0.200, y=0.250)
axes[1].imshow(A_dense, cmap=ListedColormap(['#f3f5f7', '#3979a5']), vmin=0, vmax=1)
for i in range(n):
for j in range(n):
axes[1].text(j, i, str(int(A_dense[i, j])), ha='center', va='center',
color='white' if A_dense[i, j] else '#697581')
axes[1].set(xticks=range(n), yticks=range(n), xlabel='列 j', ylabel='行 i',
title=r'図1b 隣接行列 $\mathbf{A}$')
save_figure(fig, '01_graph_and_adjacency.svg')
array([[0.00, 1.00, 0.00, 1.00, 0.00, 0.00],
[1.00, 0.00, 1.00, 1.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00, 0.00],
[1.00, 1.00, 0.00, 0.00, 1.00, 0.00],
[0.00, 0.00, 0.00, 1.00, 0.00, 0.00],
[0.00, 0.00, 0.00, 0.00, 0.00, 0.00]])
$$ \displaystyle \mathbf{A}=\begin{bmatrix}0 & 1 & 0 & 1 & 0 & 0 \\ 1 & 0 & 1 & 1 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 \\ 1 & 1 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0\end{bmatrix} $$
2. What COO, CSR, and CSC store
COO, the coordinate format, stores equally sized arrays of row indices row, column indices col, and values data. The preceding code builds COO directly from an edge list. Explicit shape=(n, n) retains the isolated vertex at the end.
CSR groups values by row and stores row boundaries in indptr. indices contains column indices and data contains values. For row $i$, the array positions $p$ satisfy the following condition.
$$ \operatorname{indptr}[i]\le p<\operatorname{indptr}[i+1],\qquad A_{i,\operatorname{indices}[p]}=\operatorname{data}[p]. $$
In Figure 2, entries in the same row share a color. Row 1 occupies indptr[1]:indptr[2], or 2:5, and its column indices are $0,2,3$. Row 5 occupies 10:10 and is empty. Checking this empty row helps explain how row pointers work.
print('COOの3配列')
pprint({'row': A_coo.row, 'col': A_coo.col, 'data': A_coo.data}, sort_dicts=False)
print('CSRの3配列')
pprint({'indptr': A.indptr, 'indices': A.indices, 'data': A.data}, sort_dicts=False)
row_index = 1
start, stop = A.indptr[row_index:row_index + 2]
print(f'第{row_index}行の列番号と値')
pprint({'columns': A.indices[start:stop], 'values': A.data[start:stop]})
assert np.array_equal(A.indptr, [0, 2, 5, 6, 9, 10, 10])
assert np.array_equal(np.diff(A.indptr), [2, 3, 1, 3, 1, 0])
colors = ['#c4dcef', '#f4d1ae', '#cbe5cb', '#ddd1eb', '#f0cbd0', '#e0e0e0']
row_of_entry = np.repeat(np.arange(n), np.diff(A.indptr))
fig, ax = plt.subplots(figsize=(11, 4), layout='constrained')
for label, array, y, color_ids in [
('indptr', A.indptr, 3, np.minimum(np.arange(n + 1), n - 1)),
('indices', A.indices, 1, row_of_entry),
('data', A.data, 0, row_of_entry),
]:
ax.text(-0.150, y + 0.350, label, ha='right', va='center', fontsize=12)
for k, value in enumerate(array):
ax.add_patch(Rectangle((k, y), 1, 0.700,
facecolor=colors[int(color_ids[k])], edgecolor='white'))
ax.text(k + 0.500, y + 0.350, str(int(value)), ha='center', va='center')
if label != 'data':
ax.text(k + 0.500, y + 0.850, str(k), ha='center', fontsize=9, color='#546473')
for i in range(n - 1):
start, stop = map(int, A.indptr[i:i + 2])
ax.plot([start + 0.0500, stop - 0.0500], [2.25, 2.25], color=colors[i], linewidth=7)
ax.text((start + stop) / 2, 2.45, f'行{i}: [{start}, {stop})', ha='center', fontsize=10)
ax.text(7.30, 3.35, '行5: [10, 10) → 空の行', fontsize=11)
ax.set(xlim=(-1.20, 10.2), ylim=(-0.200, 4.40), title='図2 CSRの配列と各行の範囲(上側の数字は配列位置)')
ax.set_axis_off()
save_figure(fig, '02_csr_storage.svg')
COOの3配列
{'row': array([0, 0, 1, 1, 3, 1, 3, 2, 3, 4], dtype=int32),
'col': array([1, 3, 2, 3, 4, 0, 0, 1, 1, 3], dtype=int32),
'data': array([1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00])}
CSRの3配列
{'indptr': array([ 0, 2, 5, 6, 9, 10, 10], dtype=int32),
'indices': array([1, 3, 0, 2, 3, 1, 0, 1, 4, 3], dtype=int32),
'data': array([1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00])}
第1行の列番号と値
{'columns': array([0, 2, 3], dtype=int32), 'values': array([1.00, 1.00, 1.00])}
CSC exchanges the roles of rows and columns in CSR: each column stores row indices and values. The table summarizes their uses. CSR suits row access and matrix–vector multiplication, but not column access or frequent insertion of new entries. SciPy CSR documentation
| Format | Main arrays or structure | Main use |
|---|---|---|
| COO | Row indices, column indices, values | Batch construction from edge lists |
| CSR | Row pointers, column indices, values | Row access and matrix–vector multiplication |
| CSC | Column pointers, row indices, values | Column access |
| LIL / DOK | Per-row lists / dictionaries keyed by coordinates | Individual insertions and changes during construction |
We use csr_array for calculations. For sparse arrays, @ is matrix multiplication and * is elementwise multiplication. SciPy sparse arrays
# CSCでは第3列に保存された行番号を取り出す。
A_csc = A.tocsc()
column_index = 3
start, stop = A_csc.indptr[column_index:column_index + 2]
pprint({'column': column_index, 'rows': A_csc.indices[start:stop],
'values': A_csc.data[start:stop]}, sort_dicts=False)
{'column': 3,
'rows': array([0, 1, 4], dtype=int32),
'values': array([1.00, 1.00, 1.00])}
Duplicates and explicit zeros
nnz counts stored entries, which need not equal the mathematical number of nonzeros. COO permits repeated coordinates, whose values are added when converted to CSR. Explicitly stored zeros also count toward nnz. SciPy COO documentation
In the next example, the stored count changes as $3\to2\to1$. Entering an edge twice in an unweighted simple graph creates a value of 2, so remove duplicate input edges. Below, we use $q=\mathrm{nnz}$ after combining duplicates and removing explicit zeros. If zero-weight edges have a special meaning, decide separately whether removing them is valid.
raw = coo_array(
(np.array([1, 1, 0], dtype=np.float64),
(np.array([0, 0, 1], dtype=np.int32), np.array([1, 1, 2], dtype=np.int32))),
shape=(3, 3),
)
counts = {'COOのnnz': int(raw.nnz)}
clean = raw.tocsr() # 同じ座標の値を加算する。
counts['CSR変換後のnnz'] = int(clean.nnz)
counts['実際の非ゼロ要素数'] = int(clean.count_nonzero())
clean.eliminate_zeros()
counts['ゼロ削除後のnnz'] = int(clean.nnz)
pprint(counts, sort_dicts=False)
pprint(clean.toarray())
assert list(counts.values()) == [3, 2, 1, 1]
{'COOのnnz': 3, 'CSR変換後のnnz': 2, '実際の非ゼロ要素数': 1, 'ゼロ削除後のnnz': 1}
array([[0.00, 2.00, 0.00],
[0.00, 0.00, 0.00],
[0.00, 0.00, 0.00]])
3. Derive memory requirements
Suppose each value occupies $b_v$ bytes and each index $b_i$ bytes. A dense matrix needs $n^2$ values. COO stores $q$ values, row indices, and column indices. CSR stores $q$ values and column indices, plus $n+1$ row pointers. The array storage is therefore
$$ \begin{aligned} M_{\mathrm{dense}}&=b_v n^2,\\ M_{\mathrm{COO}}&=b_v q+b_i q+b_i q=(b_v+2b_i)q,\\ M_{\mathrm{CSR}}&=b_v q+b_i q+b_i(n+1)\\ &=(b_v+b_i)q+b_i(n+1). \end{aligned} $$
A float64 value uses 8 bytes and an int32 index uses 4, giving $12q+4(n+1)$ bytes for CSR. This excludes Python object overhead, temporary construction and conversion arrays, the input edge list, and calculation vectors. Check the formula against summed nbytes in the small example.
def csr_nbytes(matrix):
# CSRを構成する3配列の容量のみを数える。
return matrix.data.nbytes + matrix.indices.nbytes + matrix.indptr.nbytes
sizes = {
'dense': A_dense.nbytes,
'COO': A_coo.data.nbytes + A_coo.row.nbytes + A_coo.col.nbytes,
'CSR': csr_nbytes(A),
}
pprint({'data型': str(A.data.dtype), 'indices型': str(A.indices.dtype),
'indptr型': str(A.indptr.dtype)})
pprint(sizes)
expected = (A.data.itemsize + A.indices.itemsize) * A.nnz + A.indptr.itemsize * (n + 1)
assert sizes['CSR'] == expected == 148
{'data型': 'float64', 'indices型': 'int32', 'indptr型': 'int32'}
{'COO': 160, 'CSR': 148, 'dense': 288}
One million vertices with average degree 10
With $n=10^6$ and $\bar d=10$, we have $m=n\bar d/2=5\times10^6$ and $q=n\bar d=10^7$. Substitute these into the formulas above.
$$ \begin{aligned} M_{\mathrm{dense}} &=8(10^6)^2=8\times10^{12}\ \mathrm{B}=8.00\ \mathrm{TB},\\ M_{\mathrm{CSR}} &=12\times10^7+4(10^6+1)\\ &=120000000+4000004\\ &=124000004\ \mathrm{B}\approx124\ \mathrm{MB}. \end{aligned} $$
Here $1\ \mathrm{MB}=10^6\ \mathrm{B}$ and $1\ \mathrm{TB}=10^{12}\ \mathrm{B}$. With int64 indices, the same graph requires $16q+8(n+1)$ bytes, about $168\ \mathrm{MB}$. Index types depend partly on the supplied arrays, so inspect the actual dtype. Use 64-bit indices if vertex indices or cumulative stored-entry counts exceed the 32-bit integer range.
Sparse storage is not always smaller. With 8-byte values and 4-byte indices, CSR is smaller than a dense matrix when
$$ \begin{aligned} 12q+4(n+1)&<8n^2,\\ 12q&<8n^2-4(n+1),\\ \rho=\frac{q}{n^2}&<\frac{2}{3}-\frac{n+1}{3n^2}. \end{aligned} $$
For sufficiently large $n$, the threshold is about $0.667$. This is a storage threshold, not a speed threshold. Figure 3 uses the formulas; no huge dense matrix is allocated.
vertex_counts = np.unique(np.geomspace(100, 10**6, 100).astype(np.int64))
nonzeros = 10 * vertex_counts # 平均次数10を固定する。
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout='constrained')
axes[0].loglog(vertex_counts, 8 * vertex_counts**2 / 10**6,
label='密行列', color='#b75538', linewidth=2)
axes[0].loglog(vertex_counts, 16 * nonzeros / 10**6,
label='COO / int32', color='#8a6aaf', linestyle='--')
axes[0].loglog(vertex_counts, (12 * nonzeros + 4 * (vertex_counts + 1)) / 10**6,
label='CSR / int32', color='#2878a6', linewidth=2)
axes[0].loglog(vertex_counts, (16 * nonzeros + 8 * (vertex_counts + 1)) / 10**6,
label='CSR / int64', color='#4b8a5b', linestyle=':')
axes[0].set(xlabel='頂点数 n', ylabel='配列本体の容量 [MB]', title='図3a 平均次数10での容量')
axes[0].legend(fontsize=9)
axes[0].grid(True, which='major', alpha=0.250)
fixed_n = 10_000
rho = np.linspace(0.00100, 1, 300)
for index_bytes, color in [(4, '#2878a6'), (8, '#4b8a5b')]:
ratio = ((8 + index_bytes) * rho * fixed_n**2 + index_bytes * (fixed_n + 1)) / (8 * fixed_n**2)
axes[1].plot(rho, ratio, label=f'CSR / int{8 * index_bytes}', color=color, linewidth=2)
axes[1].axhline(1, color='#b75538', linestyle='--', label='密行列と同じ容量')
axes[1].set(xlabel=r'行列の密度 $\rho$', ylabel='CSR容量 / 密行列容量',
xlim=(0, 1), ylim=(0, 2.10), title='図3b 密度による容量比(n=10000)')
axes[1].xaxis.set_major_formatter(FuncFormatter(lambda x, _: sig3(x)))
axes[1].yaxis.set_major_formatter(FuncFormatter(lambda x, _: sig3(x)))
axes[1].legend(fontsize=9)
axes[1].grid(True, alpha=0.250)
save_figure(fig, '03_memory_scaling.svg')
4. Matrix–vector multiplication cost
If $\mathbf{x}$ contains values at vertices, $\mathbf{y}=\mathbf{A}\mathbf{x}$ sums neighbor values at each vertex. Define $N(i)=\{j:A_{ij}\ne0\}$ to omit multiplication by zeros:
$$ y_i=\sum_{j=0}^{n-1}A_{ij}x_j =\sum_{j\in N(i)}A_{ij}x_j. $$
Assign $\mathbf{x}=(1,2,3,4,5,6)^{\mathsf T}$ to the preceding graph. The remaining calculations in each row are
$$ \begin{aligned} y_0&=1\cdot2+1\cdot4=6,\\ y_1&=1\cdot1+1\cdot3+1\cdot4=8,\\ y_2&=1\cdot2=2,\\ y_3&=1\cdot1+1\cdot2+1\cdot5=8,\\ y_4&=1\cdot4=4,\\ y_5&=0. \end{aligned} $$
For row $i$, CSR processes only its $d_i$ entries. Scanning rows and initializing the output vector cost $O(n)$; processing stored entries costs $O(q)$. Thus
$$ T_{\mathrm{CSR}}=O\!\left(n+\sum_{i=0}^{n-1}d_i\right) =O(n+q)=O(n+m). $$
Even with many isolated vertices, we must create $n$ outputs. Rather than simply $O(q)$, the more accurate bound is $O(n+q)$. Ordinary dense multiplication processes all $n^2$ entries and costs $O(n^2)$.
def csr_matvec_by_row(matrix, vector):
# CSRの構造を理解するための実装。速度計測にはSciPyの @ を使う。
result = np.zeros(matrix.shape[0], dtype=np.float64)
for i in range(matrix.shape[0]):
for p in range(matrix.indptr[i], matrix.indptr[i + 1]):
j = matrix.indices[p]
result[i] += matrix.data[p] * vector[j]
return result
x = np.arange(1, n + 1, dtype=np.float64)
y = A @ x
pprint({'x': x, 'y': y}, sort_dicts=False)
display(Math(r'\mathbf{x}=' + matrix_tex(x[:, None])
+ r',\qquad\mathbf{A}\mathbf{x}=' + matrix_tex(y[:, None])))
assert np.array_equal(y, [6, 8, 2, 8, 4, 0])
assert np.array_equal(y, csr_matvec_by_row(A, x))
assert np.array_equal(y, A_dense @ x)
# 隣接頂点jからの寄与 A_ij x_j を色分けする。
fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')
bottom = np.zeros(n)
for j in range(n):
contribution = A_dense[:, j] * x[j]
if np.any(contribution):
ax.bar(np.arange(n), contribution, bottom=bottom,
color=colors[j], edgecolor='white', label=f'頂点{j}の値')
bottom += contribution
for i, value in enumerate(y):
ax.text(i, value + 0.150, str(int(value)), ha='center')
ax.set(xticks=range(n), xlabel='値を受け取る頂点 i', ylabel='隣接点の値の合計',
ylim=(0, 10), title=r'図4 $\mathbf{A}\mathbf{x}$ の内訳')
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
ax.legend(ncol=3, fontsize=9)
save_figure(fig, '04_neighbor_aggregation.svg')
{'x': array([1.00, 2.00, 3.00, 4.00, 5.00, 6.00]),
'y': array([6.00, 8.00, 2.00, 8.00, 4.00, 0.00])}
$$ \displaystyle \mathbf{x}=\begin{bmatrix}1 \\ 2 \\ 3 \\ 4 \\ 5 \\ 6\end{bmatrix},\qquad\mathbf{A}\mathbf{x}=\begin{bmatrix}6 \\ 8 \\ 2 \\ 8 \\ 4 \\ 0\end{bmatrix} $$
The table compares costs. Let $d_i$ be the nonzero count in row $i$, and assume CSR duplicates and explicit zeros have been removed.
| Operation | Dense matrix | CSR |
|---|---|---|
| Array storage | $O(n^2)$ | $O(n+q)$ |
| List neighbors of vertex $i$ | $O(n)$ | $O(1+d_i)$ |
| Compute all degrees | $O(n^2)$ | $O(n)$: diff(indptr) |
| Matrix–vector multiplication | $O(n^2)$ | $O(n+q)$ |
np.diff(A.indptr) gives degrees because each neighbor occupies one entry. Weighted degree sums use A.sum(axis=1) and cost $O(n+q)$. For frequent edge insertions, collecting entries in COO and converting later is often simpler than repeatedly modifying CSR.
Equal nonzero counts do not imply equal work per row
The path and star in Figure 5 both have 80 vertices and 79 edges. Their storage and total multiplication costs match, but the star’s center processes 79 entries. Average degree does not reveal this imbalance between rows.
n_structure = 80
path_graph = nx.path_graph(n_structure)
star_graph = nx.star_graph(n_structure - 1)
A_path = nx.to_scipy_sparse_array(path_graph, nodelist=range(n_structure),
dtype=np.float64, format='csr')
A_star = nx.to_scipy_sparse_array(star_graph, nodelist=range(n_structure),
dtype=np.float64, format='csr')
assert A_path.nnz == A_star.nnz == 2 * (n_structure - 1)
assert csr_nbytes(A_path) == csr_nbytes(A_star)
fig, axes = plt.subplots(1, 3, figsize=(11, 3.60), layout='constrained')
for ax, matrix, title in zip(axes[:2], [A_path, A_star], ['道グラフ', '星グラフ']):
ax.spy(matrix, markersize=2, color='#2878a6')
ax.xaxis.tick_bottom()
ax.set(xlabel='列 j', ylabel='行 i', title=f'{title}: q={matrix.nnz}')
axes[2].plot(np.diff(A_path.indptr), label='道グラフ', color='#2878a6', linewidth=2)
axes[2].plot(np.diff(A_star.indptr), label='星グラフ', color='#b75538', linewidth=2)
axes[2].set(xlabel='頂点 i', ylabel='次数', title='各行の処理要素数')
axes[2].legend()
fig.suptitle('図5 同じ非ゼロ要素数を持つ2つのグラフ')
save_figure(fig, '05_sparsity_and_degrees.svg')
5. Implementation and timing with 100,000 vertices
Arrange vertices in a ring and connect each to its five neighbors on either side. Every degree is 10, giving $q=10n$. This fixes the structure to isolate the effect of size; it does not reproduce a real dataset’s degree distribution.
For 100,000 vertices, $q=10^6$. Dense storage requires $8(10^5)^2=80.0\ \mathrm{GB}$, while CSR with 32-bit indices requires $12\times10^6+4(10^5+1)=12400004\ \mathrm{B}\approx12.4\ \mathrm{MB}$. We allocate only CSR and verify that multiplying by the all-ones vector $\mathbf{1}$ gives degree 10 at every vertex.
def ring_adjacency(vertex_count, radius=5):
if vertex_count <= 2 * radius:
raise ValueError('頂点数は左右の接続数の合計より大きくする')
# ±1から±radiusまでの接続先を作る。自己ループも重複もない。
offsets = np.concatenate([
np.arange(-radius, 0, dtype=np.int32),
np.arange(1, radius + 1, dtype=np.int32),
])
row = np.repeat(np.arange(vertex_count, dtype=np.int32), len(offsets))
col = (row + np.tile(offsets, vertex_count)) % vertex_count
data = np.ones(len(row), dtype=np.float64)
return coo_array((data, (row, col)), shape=(vertex_count, vertex_count)).tocsr()
large_n = 100_000
A_large = ring_adjacency(large_n)
large_result = A_large @ np.ones(large_n)
pprint({
'頂点数': large_n,
'非ゼロ要素数': int(A_large.nnz),
'値の型': str(A_large.data.dtype),
'添字の型': str(A_large.indices.dtype),
'CSR配列容量 [MB]': sig3(csr_nbytes(A_large) / 10**6),
'密行列容量の見積もり [GB]': sig3(8 * large_n**2 / 10**9),
}, sort_dicts=False)
pprint(large_result[:10])
assert A_large.nnz == 10 * large_n
assert A_large.indices.dtype == np.int32
assert csr_nbytes(A_large) == 12_400_004
assert np.all(large_result == 10)
{'頂点数': 100000,
'非ゼロ要素数': 1000000,
'値の型': 'float64',
'添字の型': 'int32',
'CSR配列容量 [MB]': '12.4',
'密行列容量の見積もり [GB]': '80.0'}
array([10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0])
Timing conditions
Compare SciPy’s @ with NumPy’s @. Measure dense matrices up to 4,000 vertices and only CSR beyond that. For each case, time seven batches of 20 products and report the median, minimum, and maximum time per product. Warm up the operation first and use the environment’s default BLAS thread settings. Print the BLAS implementation as well. Timings include output-vector allocation but exclude graph construction, format conversion, and plotting.
Computational complexity describes growth with input size. Actual times also depend on cache behavior and memory transfer, so speed ratios vary by environment. Sparse conversion itself takes time and temporary memory; include those costs when deciding how to perform a one-off calculation.
def matvec_times(matrix, vector, number=20, repeats=7):
_ = matrix @ vector # 初回呼び出しを計測から外す。
samples = np.asarray(repeat(lambda: matrix @ vector, number=number, repeat=repeats)) / number
return float(samples.min()), float(np.median(samples)), float(samples.max())
benchmark = []
rng = np.random.default_rng(103)
blas = np.show_config(mode='dicts')['Build Dependencies']['blas']
pprint({'BLAS': blas['name'], 'スレッド設定': '環境既定値'}, sort_dicts=False)
for vertex_count in [250, 500, 1000, 2000, 4000, 10_000, 100_000]:
matrix = A_large if vertex_count == large_n else ring_adjacency(vertex_count)
vector = rng.standard_normal(vertex_count)
sparse_times = matvec_times(matrix, vector)
dense_times = None
if vertex_count <= 4000:
dense_matrix = matrix.toarray()
np.testing.assert_allclose(matrix @ vector, dense_matrix @ vector,
rtol=1.00e-12, atol=1.00e-12)
dense_times = matvec_times(dense_matrix, vector)
del dense_matrix
benchmark.append({'n': vertex_count, 'q': int(matrix.nnz),
'csr': sparse_times, 'dense': dense_times})
# リストの計測結果はpprintで表示する。時間の単位はマイクロ秒。
rows_for_output = []
for item in benchmark:
row = {'n': item['n'], 'q': item['q'],
'CSR中央値 [μs]': sig3(item['csr'][1] * 10**6),
'CSR範囲 [μs]': [sig3(item['csr'][i] * 10**6) for i in [0, 2]]}
if item['dense'] is not None:
row['密行列中央値 [μs]'] = sig3(item['dense'][1] * 10**6)
row['密行列範囲 [μs]'] = [sig3(item['dense'][i] * 10**6) for i in [0, 2]]
rows_for_output.append(row)
pprint(rows_for_output, sort_dicts=False, width=100)
fig, ax = plt.subplots(figsize=(9, 4.50), layout='constrained')
for key, label, color in [('csr', 'CSR', '#2878a6'), ('dense', '密行列', '#b75538')]:
selected = [item for item in benchmark if item[key] is not None]
ns = np.array([item['n'] for item in selected])
times = np.array([item[key] for item in selected]) * 10**6
ax.loglog(ns, times[:, 1], 'o-', label=label, color=color, linewidth=2)
ax.fill_between(ns, times[:, 0], times[:, 2], color=color, alpha=0.180)
ax.set(xlabel='頂点数 n(各頂点の次数は10)', ylabel='積1回の時間 [μs]',
title='図6 行列・ベクトル積の実測時間(線: 中央値、帯: 最小〜最大)')
ax.legend()
ax.grid(True, which='major', alpha=0.250)
save_figure(fig, '06_matvec_benchmark.svg')
{'BLAS': 'accelerate', 'スレッド設定': '環境既定値'}
[{'n': 250,
'q': 2500,
'CSR中央値 [μs]': '2.95',
'CSR範囲 [μs]': ['2.83', '7.55'],
'密行列中央値 [μs]': '6.99',
'密行列範囲 [μs]': ['6.93', '13.3']},
{'n': 500,
'q': 5000,
'CSR中央値 [μs]': '3.98',
'CSR範囲 [μs]': ['3.96', '4.23'],
'密行列中央値 [μs]': '11.2',
'密行列範囲 [μs]': ['10.9', '11.5']},
{'n': 1000,
'q': 10000,
'CSR中央値 [μs]': '6.81',
'CSR範囲 [μs]': ['6.78', '10.2'],
'密行列中央値 [μs]': '35.3',
'密行列範囲 [μs]': ['34.4', '42.1']},
{'n': 2000,
'q': 20000,
'CSR中央値 [μs]': '11.0',
'CSR範囲 [μs]': ['10.8', '11.5'],
'密行列中央値 [μs]': '580',
'密行列範囲 [μs]': ['494', '1.01e+03']},
{'n': 4000,
'q': 40000,
'CSR中央値 [μs]': '24.6',
'CSR範囲 [μs]': ['23.0', '40.8'],
'密行列中央値 [μs]': '3.99e+03',
'密行列範囲 [μs]': ['2.45e+03', '6.64e+03']},
{'n': 10000, 'q': 100000, 'CSR中央値 [μs]': '45.7', 'CSR範囲 [μs]': ['43.1', '103']},
{'n': 100000, 'q': 1000000, 'CSR中央値 [μs]': '500', 'CSR範囲 [μs]': ['456', '613']}]
6. A product of sparse matrices need not be sparse
The cost of $\mathbf{A}\mathbf{x}$ cannot be applied directly to constructing $\mathbf{A}^2$. A matrix product can create nonzeros at positions absent from the original matrix.
Consider an $n$-vertex star centered at vertex 0. The remaining $n-1$ vertices are leaves. Let $n-1$ be the length of the all-ones vector $\mathbf{1}$. The adjacency matrix and its square have the following block forms.
$$ \begin{aligned} \mathbf{A}&= \begin{bmatrix}0&\mathbf{1}^{\mathsf T}\\\mathbf{1}&\mathbf{0}\end{bmatrix},\\ \mathbf{A}^2&= \begin{bmatrix} 0\cdot0+\mathbf{1}^{\mathsf T}\mathbf{1}&0\cdot\mathbf{1}^{\mathsf T}+\mathbf{1}^{\mathsf T}\mathbf{0}\\ \mathbf{1}\cdot0+\mathbf{0}\mathbf{1}&\mathbf{1}\mathbf{1}^{\mathsf T}+\mathbf{0}\mathbf{0} \end{bmatrix}\\ &=\begin{bmatrix}n-1&\mathbf{0}^{\mathsf T}\\\mathbf{0}&\mathbf{1}\mathbf{1}^{\mathsf T}\end{bmatrix}. \end{aligned} $$
Any leaf can reach any other leaf, or itself, in two steps through the center. Thus every entry in the lower-right $(n-1)\times(n-1)$ block is 1.
$$ \operatorname{nnz}(\mathbf{A})=2(n-1),\qquad \operatorname{nnz}(\mathbf{A}^2)=1+(n-1)^2. $$
Although the original nonzero count is $O(n)$, storing the product needs $O(n^2)$ space. With 80 vertices, $158$ entries become $6242$. Figure 7 shows this change.
# ここでは80×80なので積そのものを作り、非ゼロ位置を表示する。
A_squared = A_star @ A_star
expected_nonzeros = 1 + (n_structure - 1)**2
assert A_squared.nnz == expected_nonzeros
pprint({
'Aのnnz': int(A_star.nnz),
'A²のnnz': int(A_squared.nnz),
'A²の行列密度': sig3(A_squared.nnz / n_structure**2),
'AのCSR配列容量 [B]': csr_nbytes(A_star),
'A²のCSR配列容量 [B]': csr_nbytes(A_squared),
}, sort_dicts=False)
fig, axes = plt.subplots(1, 2, figsize=(8, 4), layout='constrained')
for ax, matrix, label in zip(axes, [A_star, A_squared], [r'$\mathbf{A}$', r'$\mathbf{A}^2$']):
ax.spy(matrix, markersize=2, color='#2878a6')
ax.xaxis.tick_bottom()
ax.set(xlabel='列 j', ylabel='行 i', title=f'{label}: q={matrix.nnz}')
fig.suptitle('図7 星グラフの隣接行列を2乗したときの非ゼロ位置')
save_figure(fig, '07_matrix_product_fill_in.svg')
# A²そのものが不要なら、ベクトルにAを2回掛ければよい。
vector = np.arange(n_structure, dtype=np.float64)
via_matrix = A_squared @ vector
via_repetition = A_star @ (A_star @ vector)
np.testing.assert_allclose(via_matrix, via_repetition, rtol=1.00e-12, atol=1.00e-12)
print('A²を作る計算と、Aを2回掛ける計算の結果は一致した。')
{'Aのnnz': 158,
'A²のnnz': 6242,
'A²の行列密度': '0.975',
'AのCSR配列容量 [B]': 3176,
'A²のCSR配列容量 [B]': 100520}
A²を作る計算と、Aを2回掛ける計算の結果は一致した。
If only $\mathbf{A}^2\mathbf{x}$ is needed, calculate A @ (A @ x). More generally, set $\mathbf{z}^{(0)}=\mathbf{x}$ and $\mathbf{z}^{(t+1)}=\mathbf{A}\mathbf{z}^{(t)}$; induction gives $\mathbf{z}^{(k)}=\mathbf{A}^k\mathbf{x}$. Multiplying by the fixed $\mathbf{A}$ a total of $k$ times costs $O(k(n+q))$ and needs $O(n)$ temporary vector storage. There is no need to store $\mathbf{A}^k$ itself.
Conclusion
We inspected sparse graph storage formats and derived memory requirements and matrix–vector multiplication costs.
After duplicates and explicit zeros are removed, CSR stores a matrix with $n$ vertices and $q$ nonzeros in $O(n+q)$ space. For an unweighted undirected graph without self-loops, $q=2m$. With fixed average degree, both storage and matrix–vector multiplication therefore scale linearly with the vertex count.
Build COO from an edge list and convert to CSR for calculations. Include both values and index types when estimating memory. Matrix products can create many nonzeros; if the desired result is a vector, consider repeated matrix–vector products instead.