简体   繁体   English

在Theano中使用循环定义函数

[英]Defining a function with a loop in Theano

I want to define the following function of two variables in Theano and compute its Jacobian: 我想在Theano中定义以下两个变量的函数并计算其雅可比行列式:

f(x1,x2) = sum((2 + 2k - exp(k*x1) - exp(k*x2))^2, k = 1..10)

How do I make a Theano function for the above expression - and eventually minimize it using its Jacobian? 如何为上述表达式创建Theano函数 - 并最终使用雅可比行列式最小化它?

Since your function is scalar, the Jacobian reduces to the gradient. 由于您的函数是标量,雅可比行列式会降低到渐变。 Assuming your two variables x1, x2 are scalar (looks like it from the formula, easily generalizable to other objects), you can write 假设你的两个变量x1, x2是标量(从公式看起来很容易推广到其他对象),你可以写

import theano
import theano.tensor as T

x1 = T.fscalar('x1')
x2 = T.fscalar('x2')

k = T.arange(1, 10)

expr = ((2 + 2 * k - T.exp(x1 * k) - T.exp(x2 * k)) ** 2).sum()

func = theano.function([x1, x2], expr)

You can call func on two scalars 你可以在两个标量上调用func

In [1]: func(0.25,0.25)
Out[1]: array(126.5205307006836, dtype=float32)

The gradient (Jacobian) is then 然后是渐变(雅可比)

grad_expr = T.grad(cost=expr, wrt=[x1, x2])

And you can use updates in theano.function in the standard way (see theano tutorials) to make your gradient descent, setting x1, x2 as shared variables in givens, by hand on the python level, or using scan as indicated by others. 你可以用标准方式使用theano.function中的updates (参见theano教程)来制作渐变下降,将x1, x2设置为givens中的共享变量,在python级别上手动设置,或者使用其他人指示的scan

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

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