Numpy 将二项式向量构成的矩阵变换为连续零的范围

Numpy 将二项式向量构成的矩阵变换为连续零的范围,numpy,theano,Numpy,Theano,我试图找出如何在一个大小不确定的矩阵中象征性地进行这种转换 发件人: 致: 因此,对于每一个连续的0,我想要一个不断增加的范围,每当我偶然发现一个1,范围就会重置。这里有一种方法,使用低效扫描: import theano import theano.tensor as tt def inner_step(x_t_t, y_t_tm1): return tt.switch(x_t_t, 0, y_t_tm1 + 1) def outer_step(x_t): return

我试图找出如何在一个大小不确定的矩阵中象征性地进行这种转换

发件人:

致:


因此,对于每一个连续的0,我想要一个不断增加的范围,每当我偶然发现一个1,范围就会重置。

这里有一种方法,使用低效扫描:

import theano
import theano.tensor as tt


def inner_step(x_t_t, y_t_tm1):
    return tt.switch(x_t_t, 0, y_t_tm1 + 1)


def outer_step(x_t):
    return theano.scan(inner_step, sequences=[x_t], outputs_info=[0])[0]


def compile():
    x = tt.bmatrix()
    y = theano.scan(outer_step, sequences=[x])[0]
    return theano.function([x], y)


def main():
    f = compile()
    data = [[0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1],
            [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1]]
    print f(data)

main()
运行时,此选项将打印:

[[1 2 3 0 1 2 3 4 5 0 0 1 0 1 2 3 0]
 [1 2 3 4 5 6 7 8 0 1 2 0 0 0 0 0 0]]
import theano
import theano.tensor as tt


def inner_step(x_t_t, y_t_tm1):
    return tt.switch(x_t_t, 0, y_t_tm1 + 1)


def outer_step(x_t):
    return theano.scan(inner_step, sequences=[x_t], outputs_info=[0])[0]


def compile():
    x = tt.bmatrix()
    y = theano.scan(outer_step, sequences=[x])[0]
    return theano.function([x], y)


def main():
    f = compile()
    data = [[0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1],
            [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1]]
    print f(data)

main()
[[1 2 3 0 1 2 3 4 5 0 0 1 0 1 2 3 0]
 [1 2 3 4 5 6 7 8 0 1 2 0 0 0 0 0 0]]