4

Theano 中将索引向量转换为 0 和 1 矩阵的最佳(优雅和有效)方法是什么,其中每一行都是索引的 N 之一表示?

v = t.ivector()  # the vector of indices
n = t.scalar()   # the width of the matrix
convert = <your code here>
f = theano.function(inputs=[v, n], outputs=convert)

例子:

n_val = 4
v_val = [1,0,3]
f(v_val, n_val) = [[0,1,0,0],[1,0,0,0],[0,0,0,1]]
4

3 回答 3

5

我没有比较不同的选项,但你也可以这样做。它不需要额外的内存。

import numpy as np
import theano

n_val = 4
v_val = np.asarray([1,0,3])
idx = theano.tensor.lvector()
z = theano.tensor.zeros((idx.shape[0], n_val))
one_hot = theano.tensor.set_subtensor(z[theano.tensor.arange(idx.shape[0]), idx], 1)
f = theano.function([idx], one_hot)
print f(v_val)[[ 0.  1.  0.  0.]
 [ 1.  0.  0.  0.]
 [ 0.  0.  0.  1.]]
于 2014-06-17T16:14:20.890 回答
1

它很简单:

convert = t.eye(n,n)[v]

仍然可能有一个更有效的解决方案,不需要构建整个单位矩阵。这对于大 n 和短 v 可能是有问题的。

于 2014-06-17T13:19:09.633 回答
1

现在有一个内置函数 this theano.tensor.extra_ops.to_one_hot

y = tensor.as_tensor([3,2,1])
fn = theano.function([], tensor.extra_ops.to_one_hot(y, 4))
print fn()
# [[ 0.  0.  0.  1.]
#  [ 0.  0.  1.  0.]
#  [ 0.  1.  0.  0.]]
于 2016-11-16T02:11:18.507 回答