Tensorflow:将输出张量转换为 one-hot [英] Tensorflow: Convert output tensor to one-hot
问题描述
我想做什么:(来自 cs231n 冬季课程)
What I want to do: (from cs231n Winter course)
我将使用 tensorflow
来实现这个.
I'm gonna implement this using tensorflow
.
但问题是我不知道如何将分数转换为 one-hot(上图中的红色线条)
But problem is I have no idea how to convert scores to one-hot (red colored line in above image)
假设我有一个 model
类,它具有所有张量操作作为对象变量.
Let say I have a model
class which has all tensor operations as object variables.
model.outputs
是获取 scores
的张量操作(前馈),我需要将此 outputs
张量转换为 one-hot张量以不同的方式,以便我可以执行梯度操作.
model.outputs
is an tensor operation(feedforward) to get the scores
and I need to convert this outputs
tensor to one-hot tensor IN A DIFFERENCIABLE WAY so that I can perform the gradient operation.
我该如何实施?
推荐答案
假设您的 scores
或 model.outputs
节点的形状为 [batch, #类]
.在下面的例子中,我们使用 batch_size
= 2,我们有 4 个 classes
.
Suppose your scores
or model.outputs
node has a shape of [batch, #class]
. In the example below, we use batch_size
= 2, and we have 4 classes
.
tf.reset_default_graph()
batch_size=2
num_classes=4
score = tf.constant([[0.5, 0.6, 0.2, 0.01],
[0.8, 0.75, 1.0, 1.0]])
max_per_instance = tf.expand_dims(tf.reduce_max(score, axis=1), 0)
tiled = tf.tile(max_per_instance, [num_classes, 1])
n_hot = tf.cast(tf.equal(score, tf.transpose(tiled)), tf.int32)
with tf.Session() as sess:
print sess.run(n_hot)
>> [[0 1 0 0]
[0 0 1 1]]
这篇关于Tensorflow:将输出张量转换为 one-hot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!