gpt4 book ai didi

python - 带有 scipy.sparse 的马尔可夫链平稳分布?

转载 作者:行者123 更新时间:2023-12-02 05:12:26 25 4
gpt4 key购买 nike

我有一个马尔可夫链,作为一个大型稀疏 scipy 矩阵 A 给出。 (我已经以 scipy.sparse.dok_matrix 格式构建了矩阵,但转换为其他格式或将其构建为 csc_matrix 都可以。)

我想知道该矩阵的任何平稳分布p,它是特征值1的特征向量。该特征向量中的所有条目都应为正且加起来为 1,以便表示概率分布。

这意味着我想要系统的任何解决方案(A-I) p = 0p.sum()=1(其中I=scipy.sparse.eye(*A.shape)是恒等矩阵),但是(A-I)不会是满秩的,甚至整个系统可能是欠定的。此外,可以生成具有负项的特征向量,该特征向量不能被归一化为有效的概率分布。防止 p 中出现负条目会很好。

  • 使用 scipy.sparse.linalg.eigen.eigs 不是解决方案:它不允许指定附加约束。 (如果特征向量包含负项,则归一化没有帮助。)此外,它与真实结果偏差很大,有时会出现收敛问题,表现比 scipy.linalg.eig 更糟糕。 (另外,我使用了shift-invert模式,它可以改进查找我想要的特征值类型,但不能改进它们的质量。如果我不使用它,那就更矫枉过正了,因为我只对一个特定的特征值感兴趣,1。)

  • 转换为稠密矩阵并使用scipy.linalg.eig并不是解决方案:除了负项问题之外,矩阵太大。

  • 使用 scipy.sparse.spsolve 并不是一个明显的解决方案:该矩阵要么不是方阵(当组合加性约束和特征向量条件时),要么不是满秩的(当尝试以某种方式单独指定它们时),有时两者都不是。

是否有一种好方法可以使用 python 以数字方式获得以稀疏矩阵形式给出的马尔可夫链的稳态?如果有办法获得详尽的列表(也可能接近静止状态),我们将不胜感激,但不是必需的。

最佳答案

通过 Google 学术可以找到几篇总结可能方法的文章,以下是其中一篇: http://www.ima.umn.edu/preprints/pp1992/932.pdf

下面所做的是@Helge Dietert 上面关于首先拆分为强连接组件的建议和上面链接的论文中的方法 #4 的组合。

import numpy as np
import time

# NB. Scipy >= 0.14.0 probably required
import scipy
from scipy.sparse.linalg import gmres, spsolve
from scipy.sparse import csgraph
from scipy import sparse


def markov_stationary_components(P, tol=1e-12):
"""
Split the chain first to connected components, and solve the
stationary state for the smallest one
"""
n = P.shape[0]

# 0. Drop zero edges
P = P.tocsr()
P.eliminate_zeros()

# 1. Separate to connected components
n_components, labels = csgraph.connected_components(P, directed=True, connection='strong')

# The labels also contain decaying components that need to be skipped
index_sets = []
for j in range(n_components):
indices = np.flatnonzero(labels == j)
other_indices = np.flatnonzero(labels != j)

Px = P[indices,:][:,other_indices]
if Px.max() == 0:
index_sets.append(indices)
n_components = len(index_sets)

# 2. Pick the smallest one
sizes = [indices.size for indices in index_sets]
min_j = np.argmin(sizes)
indices = index_sets[min_j]

print("Solving for component {0}/{1} of size {2}".format(min_j, n_components, indices.size))

# 3. Solve stationary state for it
p = np.zeros(n)
if indices.size == 1:
# Simple case
p[indices] = 1
else:
p[indices] = markov_stationary_one(P[indices,:][:,indices], tol=tol)

return p


def markov_stationary_one(P, tol=1e-12, direct=False):
"""
Solve stationary state of Markov chain by replacing the first
equation by the normalization condition.
"""
if P.shape == (1, 1):
return np.array([1.0])

n = P.shape[0]
dP = P - sparse.eye(n)
A = sparse.vstack([np.ones(n), dP.T[1:,:]])
rhs = np.zeros((n,))
rhs[0] = 1

if direct:
# Requires that the solution is unique
return spsolve(A, rhs)
else:
# GMRES does not care whether the solution is unique or not, it
# will pick the first one it finds in the Krylov subspace
p, info = gmres(A, rhs, tol=tol)
if info != 0:
raise RuntimeError("gmres didn't converge")
return p


def main():
# Random transition matrix (connected)
n = 100000
np.random.seed(1234)
P = sparse.rand(n, n, 1e-3) + sparse.eye(n)
P = P + sparse.diags([1, 1], [-1, 1], shape=P.shape)

# Disconnect several components
P = P.tolil()
P[:1000,1000:] = 0
P[1000:,:1000] = 0

P[10000:11000,:10000] = 0
P[10000:11000,11000:] = 0
P[:10000,10000:11000] = 0
P[11000:,10000:11000] = 0

# Normalize
P = P.tocsr()
P = P.multiply(sparse.csr_matrix(1/P.sum(1).A))

print("*** Case 1")
doit(P)

print("*** Case 2")
P = sparse.csr_matrix(np.array([[1.0, 0.0, 0.0, 0.0],
[0.5, 0.5, 0.0, 0.0],
[0.0, 0.0, 0.5, 0.5],
[0.0, 0.0, 0.5, 0.5]]))
doit(P)

def doit(P):
assert isinstance(P, sparse.csr_matrix)
assert np.isfinite(P.data).all()

print("Construction finished!")

def check_solution(method):
print("\n\n-- {0}".format(method.__name__))
start = time.time()
p = method(P)
print("time: {0}".format(time.time() - start))
print("error: {0}".format(np.linalg.norm(P.T.dot(p) - p)))
print("min(p)/max(p): {0}, {1}".format(p.min(), p.max()))
print("sum(p): {0}".format(p.sum()))

check_solution(markov_stationary_components)


if __name__ == "__main__":
main()

编辑:发现了一个错误 --- csgraph.connected_components 也返回纯粹的衰减组件,需要将其过滤掉。

关于python - 带有 scipy.sparse 的马尔可夫链平稳分布?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21308848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com