reduce_sum 按特定维度
reduce_sum by certain dimension
我有两个嵌入张量 A
和 B
,看起来像
[
[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]
]
然后我想做一个元素明智的减少 returns
[
3,
0
]
但是tf.reduce_sum
不允许我按行减少。任何输入将不胜感激。谢谢。
添加值为1的reduction_indices
参数,例如:
tf.reduce_sum( tf.square( tf.sub( lhs, rhs) ), 1 )
这应该会产生您要查找的结果。 Here is the documentation 于 reduce_sum()
。
根据 TensorFlow documentation,reduce_sum
带有四个参数的函数。
tf.reduce_sum(input_tensor, axis=None, keep_dims=False, name=None, reduction_indices=None).
但是 reduction_indices
已被弃用。最好使用 axis 而不是。如果未设置轴,则减小其所有尺寸。
例如,这取自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
我有两个嵌入张量 A
和 B
,看起来像
[
[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]
]
然后我想做一个元素明智的减少 returns
[
3,
0
]
但是tf.reduce_sum
不允许我按行减少。任何输入将不胜感激。谢谢。
添加值为1的reduction_indices
参数,例如:
tf.reduce_sum( tf.square( tf.sub( lhs, rhs) ), 1 )
这应该会产生您要查找的结果。 Here is the documentation 于 reduce_sum()
。
根据 TensorFlow documentation,reduce_sum
带有四个参数的函数。
tf.reduce_sum(input_tensor, axis=None, keep_dims=False, name=None, reduction_indices=None).
但是 reduction_indices
已被弃用。最好使用 axis 而不是。如果未设置轴,则减小其所有尺寸。
例如,这取自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