Theano:使用 theano.scan 和 theano.scan_module.until
Theano: Using theano.scan with theano.scan_module.until
我刚开始使用 theano.scan
和 theano.scan_module.until
。从文档 here, I'm not sure how to set variables in my while
loop, and I'm uncertain how to adapt this post here 到使用 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 语句。但我不知道如何将其翻译成 theano。
如果你好奇的话,你可以粘贴上面的代码来设置变量
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)
顺便说一下,您没有执行 "random walk." 您正在求解 r 使得 rW = r,通常称为马尔可夫链的平稳分布。
我刚开始使用 theano.scan
和 theano.scan_module.until
。从文档 here, I'm not sure how to set variables in my while
loop, and I'm uncertain how to adapt this post here 到使用 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 语句。但我不知道如何将其翻译成 theano。
如果你好奇的话,你可以粘贴上面的代码来设置变量
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)
顺便说一下,您没有执行 "random walk." 您正在求解 r 使得 rW = r,通常称为马尔可夫链的平稳分布。