如何在 theano 函数中将一个矩阵值映射到另一个矩阵值
How to map one matrix value to another in theano function
我想在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
我收到错误 TensorType does not support iteration
我必须使用扫描吗?还是有更简单的方法?
谢谢!
因为 b 是 ndarray
类型,我假设每个 b_row
具有相同的长度。
如果我理解正确,代码会根据 dictx
交换 b
中列的顺序,并用零填充 non-specified 列。
主要问题是 Theano 没有 dictionary-like 数据结构(如果有的话请告诉我)。
因为在您的示例中字典键和值是 range(len(b_row))
内的整数,解决此问题的一种方法是构造一个使用索引作为键的向量(如果某些索引不应包含在字典中, 使其值为-1)。
同样的想法应该适用于一般矩阵的映射元素,当然还有其他(更好的)方法可以做到这一点。
这是代码。
麻木的:
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]]
我想在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
我收到错误 TensorType does not support iteration
我必须使用扫描吗?还是有更简单的方法?
谢谢!
因为 b 是 ndarray
类型,我假设每个 b_row
具有相同的长度。
如果我理解正确,代码会根据 dictx
交换 b
中列的顺序,并用零填充 non-specified 列。
主要问题是 Theano 没有 dictionary-like 数据结构(如果有的话请告诉我)。
因为在您的示例中字典键和值是 range(len(b_row))
内的整数,解决此问题的一种方法是构造一个使用索引作为键的向量(如果某些索引不应包含在字典中, 使其值为-1)。
同样的想法应该适用于一般矩阵的映射元素,当然还有其他(更好的)方法可以做到这一点。
这是代码。
麻木的:
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]]