【问题标题】:How to make an onehot tensor with every row of the tensor contains more than one '1'?如何制作一个张量的每一行包含多个“1”的单热张量?
【发布时间】:2018-01-26 17:08:24
【问题描述】:

我需要构建一个onehot张量,张量的每一行都包含两个'1',并且我已经得到了索引张量,但是如何构建张量?我知道如果batchsize=1,onehot = tf.sparse_to_dense(index, tf.stack([batchsize,10]), 1.0, 0.0)可以完成,但是如果batchsize>1,我该怎么办? 换句话说,如何构建张量:

[[ 0.  1.  0.  1.  0.  1.  0.  0.  0.  0.]
 [ 0.  0.  0.  1.  0.  1.  1.  0.  0.  0.]]

带有标签:

[[1,3,5]
 [3,5,6]]

【问题讨论】:

  • 这应该在数据准备时完成,在将数据输入到 tensorflow 之前。

标签: python tensorflow deep-learning one-hot-encoding


【解决方案1】:
import tensorflow as tf
sess = tf.InteractiveSession()
indices = [[1,3,5], [3,5,6]]
depth = 10
tmp_onehot_3D = tf.one_hot(indices, depth)
onehot_2D = tf.reduce_sum(tmp_onehot_3D, axis=1)
onehot_2D.eval()

结果:

array([[0., 1., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.]], dtype=float32)

【讨论】:

    【解决方案2】:

    这不如@Maosi Chen 简洁,但它也提供了另一种方法。要点是将切片转换为二维坐标集,然后从中生成稀疏张量,并将其转换为密集张量。

    import tensorflow as tf
    
    slices = tf.constant([[1, 3, 5], [3, 5, 6]], dtype=tf.int64)
    values = tf.ones_like(slices)
    
    nrows = 2
    ncols = 10
    
    row_inds = tf.range(nrows, dtype=slices.dtype)
    
    flattened_indices = tf.reshape(slices * nrows + row_inds[:, None], [-1])
    
    twod_inds = tf.stack(
        [flattened_indices % nrows, flattened_indices // nrows], axis=1)
    
    one_hot_sparse = tf.SparseTensor(
        twod_inds, values=tf.reshape(values, [-1]), dense_shape=(nrows, ncols))
    
    one_hot_dense = tf.sparse_tensor_to_dense(one_hot_sparse, validate_indices=False)
    with tf.Session() as sess:
        print(sess.run(one_hot_dense))
    

    这是输出

    [[0 1 0 1 0 1 0 0 0 0]
     [0 0 0 1 0 1 1 0 0 0]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-24
      • 1970-01-01
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多