Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 具有scipy.sparse的马尔可夫链平稳分布?_Python_Scipy_Sparse Matrix_Markov Chains - Fatal编程技术网

Python 具有scipy.sparse的马尔可夫链平稳分布?

Python 具有scipy.sparse的马尔可夫链平稳分布?,python,scipy,sparse-matrix,markov-chains,Python,Scipy,Sparse Matrix,Markov Chains,我有一个马尔可夫链,作为一个大的稀疏矩阵scipymatrixa。(我已经用scipy.sparse.dok_矩阵格式构造了矩阵,但是转换为其他格式或将其构造为csc_矩阵是可以的。) 我想知道这个矩阵的任何平稳分布p,它是特征值1的特征向量。该特征向量中的所有条目都应为正,加起来等于1,以表示概率分布 这意味着我需要系统的任何解决方案 (A-I)p=0,p.sum()=1(其中I=scipy.sparse.eye(*A.shape)是同一矩阵),但(A-I)将不是满秩,甚至整个系统可能未确定。

我有一个马尔可夫链,作为一个大的稀疏矩阵
scipy
matrix
a
。(我已经用
scipy.sparse.dok_矩阵
格式构造了矩阵,但是转换为其他格式或将其构造为
csc_矩阵
是可以的。)

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

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

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

  • 转换为密集矩阵并使用
    scipy.linalg.eig
    不是一个解决方案:除了负输入问题,矩阵太大

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

有没有一种很好的方法可以使用python从数值上获得作为稀疏矩阵给出的马尔可夫链的平稳状态? 如果有一种方法可以得到一个详尽的列表(也可能是几乎静止的状态),这是值得赞赏的,但不是必要的

使用幂迭代(例如):


或者,您可以使用scipy.sparse.linalg.eig(即ARPACK)的移位反转模式来查找接近1的特征值。“指定”标准化是不必要的,因为您可以在之后对值进行标准化。

这是在解决可能未指定的矩阵方程,因此可以使用
scipy.sparse.linalg.lsqr来完成。我不知道如何确保所有的条目都是正数,但除此之外,它非常简单

import scipy.sparse.linalg
states = A.shape[0]

# I assume that the rows of A sum to 1.
# Therefore, In order to use A as a left multiplication matrix,
# the transposition is necessary.
eigvalmat = (A - scipy.sparse.eye(states)).T
probability_distribution_constraint = scipy.ones((1, states))

lhs = scipy.sparse.vstack(
    (eigvalmat,
     probability_distribution_constraint))

B = numpy.zeros(states+1)
B[-1]=1

r = scipy.sparse.linalg.lsqr(lhs, B)
# r also contains metadata about the approximation process
p = r[0]

解决了平稳解不是唯一的,解可能不是非负的这一点

这意味着你的马尔可夫链不是不可约的,你可以把问题分解成不可约的马尔可夫链。为此,您希望找到马尔可夫链的封闭通信类,这本质上是对过渡图的连通分量的研究(建议使用一些线性算法来查找强连通分量)。此外,您可以遍历所有开放的通信类,因为这些类上的每个静止状态都必须消失

如果你有一个封闭的通信类C_1,…,C_n你的问题很有希望被分成几个简单的小部分:每个封闭类C_i上的马尔可夫链现在是不可约的,因此限制转移矩阵M_i只有一个特征值为0的特征向量,而这个特征向量只有正分量(参见Perron-Frobenius定理),因此我们只有一个稳态x_i

全马尔可夫链的平稳状态现在都是封闭类中x_i的线性组合。事实上,这些都是平稳状态


为了找到稳态x_i,您可以连续应用M_i,迭代将收敛到该状态(这也将保留您的归一化)。一般来说,很难判断收敛速度,但它为您提供了一种提高解决方案准确性和验证解决方案的简便方法。

Google scholar提供了几篇文章,总结了可能的方法,如下所示:

下面所做的是结合上面@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\u组件也返回纯粹的衰减组件,需要过滤掉。

我使用了移位反转模式,这改进了查找我想要的特征值类型,但不提高其质量。此外,仅规范化特征向量不起作用,因为它们可能包含负项,我必须通过在特征向量之间找到正确的线性组合来解决这个问题——如果特征向量不精确,就会有问题。我使用了你代码的一些部分来开发一个马尔可夫链模块