如何在Theano函数中将一个矩阵值映射到另一个矩阵值

3
我希望在Theano函数中实现以下功能:
a=numpy.array([ [b_row[dictx[idx]] if idx in dictx else 0 for idx in range(len(b_row))]
               for b_row in b])
where a, b are narray, and dictx is a dictionary

我收到了错误信息:张量类型不支持迭代。 我需要使用 scan 吗?还是有更简单的方法? 谢谢!


我相信使用智能索引是可能的。如果您能够制作一个可以独立运行并准确展示您想要实现的小例子,那么制作 Theano 版本就会更容易。 - eickenberg
1个回答

2

由于bndarray类型,我会假设每个b_row的长度都相同。

如果我理解正确,该代码根据dictx交换了b中的列顺序,并用零填充了未指定的列。

主要问题是Theano没有类似字典的数据结构(如果有,请告诉我)。

因为在您的示例中,字典键和值是range(len(b_row))内的整数,一种解决方法是构造一个向量,使用索引作为键(如果某个索引不应包含在字典中,请将其值设置为-1)。

同样的想法应该适用于映射矩阵中的元素,肯定还有其他更好的方法来实现这一点。

以下是代码。
Numpy:

dictx = {0:1,1:2}
b = numpy.asarray([[1,2,3],
                [4,5,6],
                [7,8,9]])
a = numpy.array([[b_row[dictx[idx]] if idx in dictx else 0 for idx in range(len(b_row))] for b_row in b])
print a

Theano:

dictx = theano.shared(numpy.asarray([1,2,-1]))
b = tensor.matrix()
a = tensor.switch(tensor.eq(dictx, -1), tensor.zeros_like(b), b[:,dictx])
fn = theano.function([b],a)
print fn(numpy.asarray([[1,2,3],
                        [4,5,6],
                        [7,8,9]]))

他们都输出:
[[2 3 0]  
 [5 6 0]  
 [8 9 0]]

是的,应该是range(len(b_row)),我已经修复了。感谢您提供的解决方案! - Irene W.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接