关于使用TensorFlow计算单热嵌入有一些堆栈溢出问题,这是可接受的解决方案:
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)
Run Code Online (Sandbox Code Playgroud)
这几乎与官方教程中的代码相同: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
Run Code Online (Sandbox Code Playgroud)
您是否希望此实施更快?它是否有任何其他原因的缺陷?
tensorflow ×1