我希望在 tensorflow 中获得向量的n累积和。
import tensorflow as tf
input = tf.placeholder('float32', [None])
n = tf.placeholder('int32', ())
output = some_ops(input, n)
即,
INPUT
input
= [1,3,5,8]
n
= 2
输出
output
= [1 + 3,3 + 5,5 + 8,8]
另一个例子,
INPUT
input
= [1,5,6,2,8,7,9]
n
= 3
输出
output
= [1 + 5 + 6,5 + 6 + 2,6 + 2 + 8,2 + 8 + 7,8 + 7 + 9,7 + 9,9]
我应该为some_ops
使用什么?
答案 0 :(得分:2)
tf.while_loop
是这类事情的便利功能。这是完整的工作代码:
import tensorflow as tf
input = tf.placeholder('float32', [None])
n = tf.placeholder('int32', ())
sess = tf.InteractiveSession()
tmp = tf.concat_v2([input,
tf.zeros(tf.expand_dims(n-1, 0),
dtype='float32')], axis=0)
i = tf.constant(0, dtype='int32')
output = tf.zeros([0], dtype='float32')
def body(i, output):
return i + 1, tf.concat_v2([output,
tf.expand_dims(tf.reduce_sum(tmp[i:i+n]), 0)],
axis=0)
i, output = tf.while_loop(lambda i, _: i < tf.shape(input)[0],
body,
[i, output],
shape_invariants=[tf.TensorShape([]),
tf.TensorShape([None])])
output.eval(feed_dict={n: 2, input:[1, 3, 5, 8]})
# array([ 4., 8., 13., 8.], dtype=float32)
output.eval(feed_dict={n: 3, input:[1,5,6,2,8,7,9]})
# array([ 12., 13., 16., 17., 24., 16., 9.], dtype=float32)