从索引列表到单热矩阵

Joh*_*ues 4 python matrix theano

在Theano中将索引向量转换为零和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)
Run Code Online (Sandbox Code Playgroud)

例:

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]]
Run Code Online (Sandbox Code Playgroud)

nou*_*uiz 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.]]
Run Code Online (Sandbox Code Playgroud)