Python中的马尔可夫聚类

时间:2018-10-19 05:13:36

标签: python python-3.x algorithm markov-chains

正如标题所述,我正在尝试使马尔可夫聚类算法在Python中工作,即Python 3.7

不幸的是,它没有做任何事情,它使我无所适从。

编辑:首先,我对主代码进行了调整,以使每一列的总和为100,即使它不是完美平衡。我将在最终答案中尝试说明这一点。

要明确的是,最大的问题是数字突然失控,变成了容易理解的数字5.56268465e-309,而我不知道如何将其转换为可以理解的数字。

这是到目前为止的代码:

import numpy as np
import math
## How far you'd like your random-walkers to go (bigger number -> more walking)
EXPANSION_POWER = 2
## How tightly clustered you'd like your final picture to be (bigger number -> more clusters)
INFLATION_POWER = 2
ITERATION_COUNT = 10
def normalize(matrix):
    return matrix/np.sum(matrix, axis=0)

def expand(matrix, power):
    return np.linalg.matrix_power(matrix, power)

def inflate(matrix, power):
    for entry in np.nditer(transition_matrix, op_flags=['readwrite']):
        entry[...] = math.pow(entry, power)
    return matrix

def run(matrix):
    #np.fill_diagonal(matrix, 1)
    #print(matrix)
    matrix = normalize(matrix)
    print(matrix)
    for _ in range(ITERATION_COUNT):
        matrix = normalize(inflate(expand(matrix, EXPANSION_POWER), INFLATION_POWER))
    return matrix

transition_matrix = np.array ([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                                [0.5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                                [0.5,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                                [0,0,0.34,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                                [0,0,0.33,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                                [0,0,0.33,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                                [0,0,0,0.34,0,0,0,0,0,0,0,0,0,0,0,0,0.125,0],
                                [0,0,0,0.33,0,0,0.5,0,0,0,0,0,0,0,0,0,0.125,1],
                                [0,0,0,0.33,0,0,0.5,1,1,0,0,0,0,0,0,0,0.125,0],
                                [0,0,0,0,0.166,0,0,0,0,0,0,0,0,0,0,0,0.125,0],
                                [0,0,0,0,0.166,0,0,0,0,0.2,0,0,0,0,0,0,0.125,0],
                                [0,0,0,0,0.167,0,0,0,0,0.2,0.25,0,0,0,0,0,0.125,0],
                                [0,0,0,0,0.167,0,0,0,0,0.2,0.25,0.5,0,0,0,0,0,0],
                                [0,0,0,0,0.167,0,0,0,0,0.2,0.25,0.5,0,1,0,0,0.125,0],
                                [0,0,0,0,0.167,0,0,0,0,0.2,0.25,0,1,0,1,0,0.125,0],
                                [0,0,0,0,0,0.34,0,0,0,0,0,0,0,0,0,0,0,0],
                                [0,0,0,0,0,0.33,0,0,0,0,0,0,0,0,0,0.5,0,0],
                                [0,0,0,0,0,0.33,0,0,0,0,0,0,0,0,0,0.5,0,0]])
run(transition_matrix)
print(transition_matrix)

这是uni作业的一部分-我需要对数组进行加权和不加权(尽管加权部分可以等到我血腥的东西都工作了)任何提示或建议?

1 个答案:

答案 0 :(得分:3)

您的转换矩阵无效。

>>> transition_matrix.sum(axis=0)
>>> matrix([[1.  , 1.  , 0.99, 0.99, 0.96, 0.99, 1.  , 1.  , 0.  , 1.  ,
         1.  , 1.  , 1.  , 0.  , 0.  , 1.  , 0.88, 1.  ]])

不仅有些列的总和不为1,有些列的总和为0。

这意味着当您尝试对矩阵进行归一化时,由于要除以0,因此最终会得到nan

最后,您是否有理由使用Numpy矩阵而不是Numpy数组,这是此类数据的推荐容器?因为使用Numpy数组将简化某些操作,例如将每个项提升为幂。另外,Numpy矩阵和Numpy数组之间存在一些差异,可能会导致细微的错误。