2017-01-29 23 views
1

ベクトルの累積合計をテンソルフローにしたいと考えています。ある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

output = [1 + 3、+ 5 3、+ 8 5、8]

別の例として、

INPUT

input = [1,5,6,2,8 、7,9]

n = 3

OUTPUT

output = [1 + 5 + 6、+ 2 5 + 6、+ 8 6 + 2,2 + 8 + 7、+ 8,9 + 7,7 + 9,9]

私は何を使用する必要がありますsome_ops

答えて

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)