我是使用theano.scan
和theano.scan_module.until
的新手。从这里的文档来看,我不确定如何在while
循环中设置变量,也不确定如何调整本文以使用theano.scan_module.until
。
这是我想翻译成等价的theano的代码。有人想尝试翻译一下吗?(也许还可以解释翻译后的代码。)
# 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
我在这里看到三个赋值操作,以及一个if语句。但我不知道如何把它翻译成西班牙语。
如果你很好奇,你可以在上面粘贴这段代码来设置变量
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
给定:
N = 3
tol = 1.0e-6
你可以这样定义你的符号函数:
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)
然后像这样使用:
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)
顺便说一句,你不是在执行"随机漫步"。你是在求解r,使得rW=r,通常被称为马尔可夫链的平稳分布。