简体   繁体   English

Theano:将theano.scan与theano.scan_module.until一起使用

[英]Theano: Using theano.scan with theano.scan_module.until

I'm new to using theano.scan and theano.scan_module.until . 我是使用theano.scantheano.scan_module.until From the docs here , I'm not sure how to set variables in my while loop, and I'm uncertain how to adapt this post here to use theano.scan_module.until . 这里的文档中,我不确定如何在while循环中设置变量,并且不确定如何将此处的帖子改编为使用theano.scan_module.until

This is the code I'd like to translate to equivalent theano. 这是我想翻译为等效theano的代码。 Someone wanna take a shot in translating this? 有人想翻译一下吗? (And perhaps explaining the translated code.) (也许解释翻译后的代码。)

# Code to perform a random walk using a row stochastic matrix M.
for i in range(100):
    r_last = r
    r = r.dot(M)
    err = np.linalg.norm(r - r_last, ord=1).sum()
    if err < N * tol:
        break

I see three assignment operations here, and one if-statement. 我在这里看到三个赋值操作和一个if语句。 But I don't know how to translate this to theano. 但是我不知道如何将其翻译为theano。

And if you were curious, you could paste this code above to set the variables 如果您好奇,可以在上面粘贴此代码以设置变量

import numpy as np

N = 3
tol = 1.0e-6
M = np.random.rand(N, N)
M = M / M.sum(axis=1).reshape(-1, 1)

r = np.ones(N, dtype=np.float) / N

Given: 鉴于:

N = 3
tol = 1.0e-6

You can define your symbolic function like this: 您可以这样定义符号函数:

r_init = T.vector()
W = T.matrix()

def step(r):
    r_prime = T.dot(r, W)
    delta = (r_prime - r).norm(1)
    condition = T.lt(delta, N * tol)
    return r_prime, theano.scan_module.until(condition)

outputs, updates = theano.scan(step, outputs_info=[r_init], n_steps=1024)
r_final = outputs[-1]

solve = theano.function(inputs=[r_init, W], outputs=r_final)

And then use it like this: 然后像这样使用它:

M = np.random.rand(N, N)
M /= M.sum(axis=1).reshape((-1, 1))

r = np.ones(N, dtype=np.float) / N

print solve(r, M)

By the way, you are not performing a "random walk." 顺便说一句,您没有执行“随机行走”。 You are solving for r such that rW = r, typically called the stationary distribution of the Markov chain. 您正在求解r使得rW = r,通常称为马尔可夫链的平稳分布。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM