TensorFlow,如何索引(batch_size x num_labels)+(batch_size) - > (的batch_size)

时间:2016-04-24 14:43:34

标签: python numpy neural-network tensorflow

假设我有一个矩阵(2D tensorX,其形状为(batch_size x num_labels)。并且每个样本的标签分数存储在矩阵中。现在我想提取真实标签的分数,而真正的标签存储在另一个1D tensor y中,其形状为(batch_size)。 我能做什么 ? 我知道在Theano或Numpy。它可以使用单个表达式完成:X[y]。 但是在TensorFlow中,实现这一目标的最方便或最便宜的方法是什么?

X = tf.get_variable("X",[batch_size,num_labels])
y = tf.placeholder(tf.int32,[batch_size])

注意0 <= y[i] <= num_labels - 1。输出z应为1D tensor,其中z[i]= X[i][y[i]]

1 个答案:

答案 0 :(得分:0)

我知道X是一个包含每个类和批处理实例的概率的向量,并且您希望获得真实标签的概率。我建议解决方案,虽然它可能不是最佳的:

# Create mask for values
increasing = tf.range(start=0, limit=tf.shape(X)[0], delta=1)

# Concatenate batch index and true label
# Note that in Tensorflow < 1.0.0 you must call tf.pack
mask = tf.stack([increasing, y], axis=1)

# Extract values
masked = tf.gather_nd(params=X, indices=mask)

希望它有所帮助。