2016-02-28 69 views
6

我有两个的嵌入张AB,它看起来像reduce_sum某些尺寸

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

​​

我想要做的就是计算L2距离d(A,B)逐元素。

首先,我做了一个tf.square(tf.sub(lhs, rhs))得到

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

,然后我想要做逐元素减少返回

[ 
    3, 
    0 
] 

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

回答

9

添加reduction_indices说法:用

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

1的值,例如,这应该产生你正在寻找的结果。 Here is the documentation on reduce_sum()

3

根据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