假设你想做的是锻炼吸收前的预期步数 http://en.wikipedia.org/wiki/Absorbing_Markov_chain#Expected_number_of_steps,维基百科上转载的“有限马尔可夫链”(Kemeny 和 Snell)的方程为:
或者扩展基本矩阵
重新排列:
这是使用函数求解线性方程组的标准格式
将其付诸实践以证明性能差异(即使对于比您所描述的系统小得多的系统)。
import networkx as nx
import numpy
def example(n):
"""Generate a very simple transition matrix from a directed graph
"""
g = nx.DiGraph()
for i in xrange(n-1):
g.add_edge(i+1, i)
g.add_edge(i, i+1)
g.add_edge(n-1, n)
g.add_edge(n, n)
m = nx.to_numpy_matrix(g)
# normalize rows to ensure m is a valid right stochastic matrix
m = m / numpy.sum(m, axis=1)
return m
提出计算预期步数的两种替代方法。
def expected_steps_fundamental(Q):
I = numpy.identity(Q.shape[0])
N = numpy.linalg.inv(I - Q)
o = numpy.ones(Q.shape[0])
numpy.dot(N,o)
def expected_steps_fast(Q):
I = numpy.identity(Q.shape[0])
o = numpy.ones(Q.shape[0])
numpy.linalg.solve(I-Q, o)
选择一个足够大的示例来演示计算基本矩阵时出现的问题类型:
P = example(2000)
# drop the absorbing state
Q = P[:-1,:-1]
产生以下时序:
%timeit expected_steps_fundamental(Q)
1 loops, best of 3: 7.27 s per loop
And:
%timeit expected_steps_fast(Q)
10 loops, best of 3: 83.6 ms per loop
需要进一步的实验来测试稀疏矩阵的性能影响,但很明显,计算逆矩阵比您预期的要慢得多。
与此处介绍的方法类似的方法也可用于步骤数的方差