我是 theano 的新手。我想用 theano 函数替换脚本中的 numpy 函数,以加快计算过程。我不知道该怎么做。
我的最终目标是对 3D 刚体应用仿射变换,为每次变换后的构象分配一个分数,并对决定分数的参数做一些优化。
这是我尝试做的一个例子。
import numpy as numpy
import theano
import theano.tensor as T
pi = 3.141592653
deg2rad = lambda angle: (angle/180.)*pi
# generate 3D transformation matrix for rotation around x axis by angle
def rotate_x_axis_numpy(angle): # my old numpy function
a = deg2rad(angle)
cosa = np.cos(a)
sina = np.sin(a)
R = np.identity(4)
R[1][1] = cosa; R[1][2] = -sina
R[2][1] = sina; R[2][2] = cosa
return R
angle_var = T.dscalar()
def rotate_x_axis_expr(angle): # new theano function expression I expected to work
a = T.deg2rad(angle)
cosa = T.cos(a)
sina = T.sin(a)
R = theano.shared(np.identity(4))
R[1][1] = cosa; R[1][2] = -sina
R[2][1] = sina; R[2][2] = cosa
return R
rotate_x_axis_theano = theano.function([angle_var], rotate_x_axis_expr(angle_var))
上面的theano函数没有通过编译。我收到以下错误消息。
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)<ipython-input-85-8d98ae1d1c9b> in <module>()
17 return R
18
---> 19 rotate_x_axis_theano = theano.function([angle_var],rotate_x_axis_expr(angle_var))
<ipython-input-85-8d98ae1d1c9b> in rotate_x_axis_expr(angle)
12
13
---> 14 R[1][1] = cosa; R[1][2] = -sina
15 R[2][1] = sina; R[2][2] = cosa
16
TypeError: 'TensorVariable' object does not support item assignment
一般来说,我的问题是
(1) 有没有一种方法可以按元素分配、更新或初始化具有特定形状的 theano 矩阵,
(2)theano与numpy关系密切,那么theano与numpy在数学表达式的定义、优化、求值方面有何不同,
和 (3) theano 可以替代 numpy,因为我们可以仅使用 theano 函数来定义、优化和评估数学表达式,而无需调用 numpy 函数。
最佳答案
我无法回答你的问题 1、2、3,因为我在十分钟前还没有使用过 theano。但是,要在 theano 中定义函数,您似乎没有使用 def
结构;你想做更像这样的事情:
angle_var = T.dscalar('angle_var')
a = T.deg2rad(angle_var)
cosa = T.cos(a)
sina = T.sin(a)
R = theano.shared(np.identity(4))
R = T.set_subtensor(R[1,1], cosa)
R = T.set_subtensor(R[1,2], -sina)
R = T.set_subtensor(R[2,1], sina)
R = T.set_subtensor(R[2,2], cosa)
rotate_x_axis_theano = theano.function([angle_var], R)
虽然对速度没有多大帮助,至少对于标量角而言:
In [368]: timeit rotate_x_axis_theano(10)
10000 loops, best of 3: 67.7 µs per loop
In [369]: timeit rotate_x_axis_numpy(10)
The slowest run took 4.23 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 22.7 µs per loop
In [370]: np.allclose(rotate_x_axis_theano(10), rotate_x_axis_numpy(10))
Out[370]: True
关于python - 如何按元素将值分配给 theano 矩阵? Numpy 和 Theano 的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32280071/