在3D theano张量上广播linalg.pinv [英] broadcasting linalg.pinv on a 3D theano tensor

查看:90
本文介绍了在3D theano张量上广播linalg.pinv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,有一个大小为(4,3,3)的3d numpy矩阵+一种关于如何计算numpy中3 * 3矩阵中的4个矩阵的每一个的pinv的解决方案.我也尝试使用在numpy中使用的相同功能,theano希望实现相同,但是失败了.知道如何在theano中做到这一点吗?

in the example below, there is a 3d numpy matrix of size (4, 3, 3)+ a solution about how to calculate pinv of each of 4 of those 3*3 matrices in numpy. I also tried to use the same function worked in numpy, in theano hoping that it is implemented the same, but it failed. Any idea how to do it in theano?

dt = np.dtype(np.float32)

a=[[[12,3,1],
   [2,4,1],
   [2,4,2],],
   [[12,3,3],
   [2,4,4],
   [2,4,5],],
   [[12,3,6],
   [2,4,5],
   [2,4,4],],
   [[12,3,3],
   [2,4,5],
   [2,4,6]]]

a=np.asarray(a,dtype=dt)
print(a.shape)

apinv=np.zeros((4,3,3))
print(np.linalg.pinv(a[0,:,:]).shape)

#numpy solution
apinv = map(lambda n: np.linalg.pinv(n), a)
apinv = np.asarray(apinv,dtype=dt)

#theano solution (not working)
at=T.tensor3('a')
apinvt = map(lambda n: T.nlinalg.pinv(n), at)

错误是:

Original exception was:
Traceback (most recent call last):
  File "pydevd.py", line 2403, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "pydevd.py", line 1794, in run
    launch(file, globals, locals)  # execute the script
  File "exp_thn_pinv_map.py", line 35, in <module>
    apinvt = map(lambda n: T.nlinalg.pinv(n), at)
  File "theano/tensor/var.py", line 549, in __iter__
    raise TypeError(('TensorType does not support iteration. '
TypeError: TensorType does not support iteration. Maybe you are using builtin.sum instead of theano.tensor.sum? (Maybe .max?)

推荐答案

错误消息是

Traceback (most recent call last):
  File "D:/Dropbox/source/intro_theano/pinv.py", line 32, in <module>
    apinvt = map(lambda n: T.nlinalg.pinv(n), at)
  File "d:\dropbox\source\theano\theano\tensor\var.py", line 549, in __iter__
    raise TypeError(('TensorType does not support iteration. '
TypeError: TensorType does not support iteration. Maybe you are using builtin.sum instead of theano.tensor.sum? (Maybe .max?)

之所以发生这种情况,是因为如错误消息所示,符号变量at不可迭代.

This is occurring because, as the error message indicates, the symbolic variable at is not iterable.

这里的根本问题是您错误地将立即执行的Python代码与延迟执行的Theano符号代码混合在一起.

The fundamental problem here is that you're incorrectly mixing immediately executed Python code with delayed execution Theano symbolic code.

您需要使用符号循环,而不是Python循环.正确的解决方案是使用Theano的scan运算符:

You need to use a symbolic loop, not a Python loop. The correct solution is to use Theano's scan operator:

at=T.tensor3('a')
apinvt, _ = theano.scan(lambda n: T.nlinalg.pinv(n), at, strict=True)
f = theano.function([at], apinvt)
print np.allclose(f(a), apinv)

这篇关于在3D theano张量上广播linalg.pinv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆