【问题标题】:From list of indices to one-hot matrix从索引列表到 one-hot 矩阵
【发布时间】:2016-11-16 10:11:18
【问题描述】:

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

【问题讨论】:

    标签: python matrix theano


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      很简单:

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

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

      【讨论】:

        【解决方案3】:

        现在这个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.]]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-11-28
          • 2019-06-20
          • 2018-03-30
          • 2019-01-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多