gpt4 book ai didi

python - theano中的嵌套循环

转载 作者:行者123 更新时间:2023-11-28 18:25:54 25 4
gpt4 key购买 nike

我有以下受 MLP Theano 教程启发的定义:

Weights = rng.uniform(low=low, high=high, size=(n_in, n_out))
W_values = numpy.asarray(Weights, dtype=theano.config.floatX)
W = theano.shared(value=W_values, name='W', borrow=True)
b_values = numpy.zeros((n_out,), dtype=theano.config.floatX)
b = theano.shared(value=b_values, name='b', borrow=True)
sigmas = rng.uniform(low=0.001, high=100, size=(n_out,))
s_values = numpy.asarray(sigmas, dtype=theano.config.floatX)
s = theano.shared(value=s_values, name='s', borrow=True)
input = T.matrix("input")

我想像这样计算高斯激活:

output = array([[numpy.exp(-numpy.linalg.norm(w_s - x_s, 2) ** 2 / 2*s_s ** 2) for w_s, s_s in zip(W.T, s)] for x_s in X]) + b

但是,这不可能直接实现,因为 W、X 和 s 都不是可迭代的。如何以高效的方式编写 Theano 版本?

非常感谢。

编辑:

我已经配置了一个解决方案:

# Declare an intermediate shared variable:
h_values = numpy.zeros((batch_s, n_out), dtype=theano.config.floatX)
dot_H = theano.shared(value=h_values, name='h', borrow=True)
# compute the kernel for an input vector and then for the whole batch
for i in range(batch_s):
dot_H=T.set_subtensor(dot_H[i],theano.scan(lambda w, sig, bias: \
T.exp(-ops.norm(w - input[i], 2) ** 2 / 2*sig ** 2)
+bias,
sequences=[self.W.T, self.s, self.b])[0])
# retrieve the solution as a numpy matrix
output = dot_H

但是..我观察到这会返回 dot_H 中的所有项目零。似乎即使是差异 w - input[i] 也无法正确计算。

EDIT_2 我已经解决了这个问题,但是我认为我的解决方案不是最有效的解决方案,请问有人能给我一些更好的建议吗?

import theano.tensor as T
import numpy
import theano

batch_s=5
dims=10
hidd_s=3
out_s=2

missing_param = None #"ignore"

rng = numpy.random.RandomState(1234)
input = T.matrix("input")
X = numpy.asarray(rng.uniform(low=-2.1, high=5.0, size=(batch_s, dims)))

def layer(x):

W=theano.shared(
value=numpy.asarray(
rng.uniform(low=0.001, high=1.0, size=(dims, hidd_s)),
dtype=theano.config.floatX),
name='W', borrow=True)

S=theano.shared(
value=numpy.asarray(
rng.uniform(low=10.0, high=100.0, size=(hidd_s, )),
dtype=theano.config.floatX),
name='S', borrow=True)

dot_H = theano.shared(
value=numpy.zeros((batch_s, hidd_s),
dtype=theano.config.floatX),
name='dot_H', borrow=True)

for i in range(batch_s):
for j in range(hidd_s):
dot_H = T.set_subtensor(dot_H[i,j],
T.exp(-(W.T[j] - x[i]).norm(2) ** 2) / 2 * S[j] ** 2)


return dot_H

layer_out = theano.function(
inputs=[input],
outputs=layer(input),
on_unused_input=missing_param
)

print layer_out(X)

最佳答案

T.set_subtensor(x[...], y) 将返回一个“符号”变量,其中给定的子张量替换为 y。它实际上不会在 x 内部运行。要更改共享变量 x,您需要使用 theano.function 和“updatex一个新的值(value)。

关于python - theano中的嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41531002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com