reduce_sum按特定维度

bxs*_*shi 6 tensorflow

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

[
  [1,1,1],
  [1,1,1]
]
Run Code Online (Sandbox Code Playgroud)

[
  [0,0,0],
  [1,1,1]
]
Run Code Online (Sandbox Code Playgroud)

我想要做的是按d(A,B)元素计算L2距离.

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

[
  [1,1,1],
  [0,0,0]
]
Run Code Online (Sandbox Code Playgroud)

然后我想做一个返回的元素减少

[
  3,
  0
]
Run Code Online (Sandbox Code Playgroud)

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

小智 9

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

tf.reduce_sum( tf.square( tf.sub( lhs, rhs) ), 1 )
Run Code Online (Sandbox Code Playgroud)

这应该产生你正在寻找的结果.这里是文档reduce_sum().


GPr*_*hap 5

根据TensorFlow文档,reduce_sum函数有四个参数.

tf.reduce_sum(input_tensor, axis=None, keep_dims=False, name=None, reduction_indices=None).
Run Code Online (Sandbox Code Playgroud)

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

例如,这取自文档,

# '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
Run Code Online (Sandbox Code Playgroud)

上述要求可以这种方式写出,

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
Run Code Online (Sandbox Code Playgroud)