您的位置:首页 > 其它

Theano2.1.15-基础知识之theano如何处理shapre信息

2015-06-19 10:05 525 查看
来自:http://deeplearning.net/software/theano/tutorial/shape_info.html

How Shape Information is Handled by Theano

当建立一个graph的时候,是没法严格的执行theano变量的shape的,因为在运行的时候将具体的值作为提供给一个theano函数的参数来说,也许会受到它graph中theano变量的shape的限制。

当前,有两种方式来使用shape信息:

当准确的输出shape已经提前知道的情况下,为了在cpu和gpu上让2d卷积得到更快的c代码。

当我们只想要知道shape,而不是一个变量的实际的值的时候,也就是为了移除graph中的计算。可以使用方法: Op.infer_shape

例子:

>>> import theano
>>> x = theano.tensor.matrix('x')
>>> f = theano.function([x], (x ** 2).shape)
>>> theano.printing.debugprint(f)
MakeVector [@A] ''   2
|Shape_i{0} [@B] ''   1
| |x [@C]
|Shape_i{1} [@D] ''   0
|x [@C]


这个编译后的函数的输出不包含任何乘法或幂次运算。theano已经将它们移除,直接计算输出的shape。

一、Shape的推测问题

Theano 在graph中传播关于shape的信息。有时候,这会导致错误,考虑下面的例子:

>>> import numpy
>>> import theano
>>> x = theano.tensor.matrix('x')
>>> y = theano.tensor.matrix('y')
>>> z = theano.tensor.join(0, x, y)
>>> xv = numpy.random.rand(5, 4)
>>> yv = numpy.random.rand(3, 3)


>>> f = theano.function([x,y], z.shape)
>>> theano.printing.debugprint(f)
MakeVector [@A] ''   4
|Elemwise{Add}[(0, 0)] [@B] ''   3
| |Shape_i{0} [@C] ''   1
| | |x [@D]
| |Shape_i{0} [@E] ''   2
|   |y [@F]
|Shape_i{1} [@G] ''   0
|x [@D]
print f(xv,yv)# 不应该引起错误。[8, 4]

>>> f = theano.function([x,y], z)# Do not take the shape.
>>> theano.printing.debugprint(f)
Join [@A] ''   0
|TensorConstant{0} [@B]
|x [@C]
|y [@D]
>>> f(xv,yv)
>>> # Raises a dimensions mismatch error.


正如你看到的,当只想要知道一些计算的shape的时候 (例子中的join ),可以在没有执行该计算本身(在第一个输出和调试打印的时候没有 join )的时候,直接得到一个推测的shape


这使得shape的计算更快,不过它同样也隐藏着错误。在这个例子中,join的输出的shape的计算只基于第一个输入的theano变量得到的,这会引发一个错误。

当使用其他ops的时候,例如 elemwise 和 dot,错误也许会发生。确实,为了执行一些优化(速度或者稳定性),theano首先假设计算是正确的。

你可以通过运行没有优化的代码来检测这些问题,使用theano flagoptimizer_excluding=local_shape_to_shape_i。你同样可以通过在模式FAST_COMPILE(它不会使用这个优化,也不会使用其他的大部分优化)
或者 DebugMode (它会在所有优化之后来进行测试(更慢))下运行来得到同样的结果。

二、指定准确的shape

当前,指定一个shape梅雨哦和我们想的那样容易和灵活。我们打算进行一些升级。这里就是当前我们可以做到的:

你可以在调用conv2d函数的时候,直接将shape信息传递给 ConvOp 。简单的在调用的时候设置参数为 image_shape 和filter_shape 。他们必须是4个元素的元组。例如:

theano.tensor.nnet.conv2d(..., image_shape=(7, 3, 5, 5), filter_shape=(2, 3, 4, 4))


你可以使用 SpecifyShape 操作来在graph的任何位置上增加shape信息。这可以允许执行某些优化。在下面的例子中,这使得对theano函数进行预计算成为一个常量。

>>> import theano
>>> x = theano.tensor.matrix()
>>> x_specify_shape = theano.tensor.specify_shape(x, (2, 2))
>>> f = theano.function([x], (x_specify_shape ** 2).shape)
>>> theano.printing.debugprint(f)
DeepCopyOp [@A] ''   0
|TensorConstant{(2,) of 2} [@B]

三、未来的计划

参数 “constant shape”可以加入到 theano.shared()中 。这可能是在使用shared变量的时候最频繁的操作了。它会让代码更简单,而且可可以当更新shared变量的时候使得shape不发生改变。

参考资料:

[1]官网:http://deeplearning.net/software/theano/tutorial/shape_info.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: