reduce_sum按特定维度

时间:2016-02-28 04:49:53

标签: tensorflow

我有两个嵌入张量AB,看起来像

[
  [1,1,1],
  [1,1,1]
]

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

我想要做的是逐个计算L2距离d(A,B)

首先我做了tf.square(tf.sub(lhs, rhs))来获取

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

然后我想做一个以元素为单位的reduce返回

[
  3,
  0
]

tf.reduce_sum不允许我按行减少。任何输入将不胜感激。感谢。

2 个答案:

答案 0 :(得分:9)

添加值为1的reduction_indices参数,例如:

tf.reduce_sum( tf.square( tf.sub( lhs, rhs) ), 1 )

这应该产生你正在寻找的结果。 reduce_sum()上的Here is the documentation

答案 1 :(得分:5)

根据TensorFlow documentationreduce_sum函数,它有四个参数。

tf.reduce_sum(input_tensor, axis=None, keep_dims=False, name=None, reduction_indices=None).

reduction_indices已被弃用。最好用轴代替。如果未设置轴,则减小其所有尺寸。

例如,这取自documentation

# 'x' is [[1, 1, 1]
#         [1, 1, 1]]
tf.reduce_sum(x) ==> 6
tf.reduce_sum(x, 0) ==> [2, 2, 2]
tf.reduce_sum(x, 1) ==> [3, 3]
tf.reduce_sum(x, 1, keep_dims=True) ==> [[3], [3]]
tf.reduce_sum(x, [0, 1]) ==> 6

以上要求可以这种方式编写,

import numpy as np
import tensorflow as tf

a = np.array([[1,7,1],[1,1,1]])
b = np.array([[0,0,0],[1,1,1]])

xtr = tf.placeholder("float", [None, 3])
xte = tf.placeholder("float", [None, 3])

pred = tf.reduce_sum(tf.square(tf.subtract(xtr, xte)),1)

# Initializing the variables
init = tf.global_variables_initializer()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)
    nn_index = sess.run(pred, feed_dict={xtr: a, xte: b})
    print nn_index
相关问题