[英]How to assign values elementwise to theano matrix ? Difference between Numpy and Theano?
我是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
只是為了讓上面發布的theano功能工作,我的版本是:
angle_var = T.dscalar()
def rotate_x_axis_expr(angle):
a = T.deg2rad(angle)
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)
return R
rotate_x_axis = theano.function([angle_var],rotate_x_axis_expr(angle_var))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.