图结构(Graph Structures)是了解Theano内在工作原理的基础。
Theano编程的核心是用符号占位符把数学关系表示出来。
图结构的组成部分
如图实现了这段代码:
importtheano.tensor as T x= T.matrix('x' ) y= T.matrix('y' ) z= x + y
变量节点(variable nodes)
红色表示。变量节点都有owner,其中x与y的owner为none。z的owner为apply。
操作节点(op nodes)
绿色表示。表示各个变量之间的运算(例如+, -, **, sum(),tanh()等等)。
应用节点(apply nodes)
蓝色表示。其他节点都连在上面。
分析nodes对应属性
对于以下代码,分析其节点属性。
importtheano.tensor as T x= T.dmatrix('x' ) y= x * 2. >>>y.owner.op.name 'Elemwise{mul,no_inplace}' >>>len(y.owner.inputs) 2 >>>y.owner.inputs[0 ] x >>>y.owner.inputs[1 ] InplaceDimShuffle{x,x}.0
#注意这里第二个输入并不是2,而是和x同样大小的矩阵框架,因为等会要广播才能相乘
>>>type(y.owner.inputs[ 1 ]) <class 'theano.tensor.basic.TensorVariable' > >>>type(y.owner.inputs[1 ].owner) <class 'theano.gof.graph.Apply' > >>>y.owner.inputs[1 ].owner.op <class 'theano.tensor.elemwise.DimShuffle object at 0x14675f0' > >>>y.owner.inputs[1 ].owner.inputs [2.0 ]
自动优化
编译Theano其实是编译了一张图。 这张图从输入变量开始贯穿全图直到输出变量。Theano可以检测关键子图 ,来进行替换,防止重复,以达到优化的目的。比如用x替换xy/y。
举个例子
>>> import theano >>>a = theano.tensor.vector("a" ) >>>b = a + a ** 10 >>>f = theano.function([a], b) >>>print f([ 0 , 1 , 2 ])
优化前
优化后