从索引列表到独热编码矩阵

4 投票
3 回答
1590 浏览
提问于 2025-04-18 10:04

在Theano中,将一组索引转换成一个由零和一组成的矩阵,最优雅和高效的方法是什么?这个矩阵的每一行都是对应索引的独热编码(one-of-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]]

3 个回答

1

现在有一个内置的功能可以做到这一点,叫做 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.]]
1

这其实很简单:

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

不过,可能还有更有效的方法,不需要构建整个单位矩阵。对于很大的n和很短的v,这样做可能会有问题。

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.]]

撰写回答