python - Tensorflow 中的 n 累积和

标签 python tensorflow

我想在tensorflow中获得向量的n累积和。

import tensorflow as tf
input = tf.placeholder('float32', [None])
n = tf.placeholder('int32', ())

output = some_ops(input, n)

也就是说,

输入

输入 = [1, 3, 5, 8]

n = 2

输出

输出 = [1+3, 3+5, 5+8, 8]

再举一个例子,

输入

输入 = [1,5,6,2,8,7,9]

n = 3

输出

输出 = [1+5+6, 5+6+2, 6+2+8, 2+8+7, 8+7+9, 7+9, 9]

我应该为 some_ops 使用什么?

最佳答案

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)

关于python - Tensorflow 中的 n 累积和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41917424/

相关文章:

python - FastAPI - 如何在响应中使用 HTTPException?

python - 在 Python 3 中使用 SAX 解析器解析 XML

python - 将屏幕大小与当前根窗口大小进行比较

python - 为列组合填充缺失日期

python - Anaconda Python : Delete . pkgs 中的 tar.gz

machine-learning - Tensorflow:权重衰减与 Logits 标准化

python - 如何处理使用 simpleITK 加载的图像中的负像素值

android - 使用SNPE转换tensorflow dense layer时报错

python - BiLSTM_Classifier 中的输入/输出/循环 dropout 层以及它们如何影响模型和预测

python - 如何修复尝试安装 Tensorflow 导致的异常?