tensorflow - TensorFlow 中的这种单热编码速度快吗?或者出于任何原因有缺陷?

标签 tensorflow

关于使用 TensorFlow 计算 one-hot 嵌入有一些堆栈溢出问题,这里是公认的解决方案:

num_labels = 10
sparse_labels = tf.reshape(label_batch, [-1, 1])
derived_size = tf.shape(label_batch)[0]
indices = tf.reshape(tf.range(0, derived_size, 1), [-1, 1])
concated = tf.concat(1, [indices, sparse_labels])
outshape = tf.reshape(tf.concat(0, [derived_size, [num_labels]]), [-1])
labels = tf.sparse_to_dense(concated, outshape, 1.0, 0.0)

这与官方教程中的代码几乎相同:https://www.tensorflow.org/versions/0.6.0/tutorials/mnist/tf/index.html

对我来说似乎是因为 tf.nn.embedding_lookup存在,它可能更有效。这是一个使用它的版本,它支持任意形状的输入:
def one_hot(inputs, num_classes):
    with tf.device('/cpu:0'):
        table = tf.constant(np.identity(num_classes, dtype=np.float32))
        embeddings = tf.nn.embedding_lookup(table, inputs)
    return embeddings

你希望这个实现更快吗?它是否因任何其他原因而存在缺陷?

最佳答案

one_hot()您问题中的函数看起来是正确的。但是,我们不推荐这样写代码的原因是内存效率极低 .要了解原因,假设您的批次大小为 32 和 1,000,000 个类。

  • 在教程中建议的版本中,最大的张量将是 tf.sparse_to_dense() 的结果。 ,这将是 32 x 1000000 .
  • one_hot()问题中的函数,最大张量将是 np.identity(1000000) 的结果, 即 4 TB。当然,分配这个张量可能不会成功。即使类的数量少得多,显式存储所有这些零仍然会浪费内存——TensorFlow 不会自动将您的数据转换为稀疏表示,即使这样做可能有利可图。

  • 最后,我想为最近添加到开源存储库中的新功能提供一个插件,并将在下一个版本中提供。 tf.nn.sparse_softmax_cross_entropy_with_logits() 允许您将整数向量指定为标签,并使您不必构建密集的 one-hot 表示。对于大量类的任何一种解决方案都应该更有效。

    关于tensorflow - TensorFlow 中的这种单热编码速度快吗?或者出于任何原因有缺陷?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35226198/

    相关文章:

    tensorflow - 如何查看 tf.train.batch() 的输出

    tensorflow - tensorflow-gpu 2.0alpha0 错误

    python - 如何使用新的数据集 API 在 tensorflow 中仅循环使用占位符提供的数据一次

    linux - 在 Windows 10 下的 Linux VM 中配置 Tensorflow

    python - Tensorflow model.fit() 使用数据集生成器

    python - 使用 python pip 在 Windows 中的 Tensorflow

    python - Tensorflow : bucketize a tensor, 然后生成分类张量

    python - TensorFlow 中的矩阵逆

    python - tensorflow object detection 从现有检查点微调模型

    python - 在 Keras 和 Tensorflow 中为多线程设置复制模型