首页 > 解决方案 > 如何仅对张量的一部分求和?

问题描述

我想从上到下对张量的一部分求和,而那部分取决于另一个张量的值。

例如:L = [1,2,3]I = [2.5]

然后我想得到: 1 + 2 + 3*0.5 = 4.5

另一个例子:L = [2,5,8]I = [1.3]

然后我想得到: 2 + 5*0.3 = 3.5

这是什么操作?我可以这样做tensorflow吗?理想情况下不使用循环或条件语句?

我也想在更高的维度上做到这一点。

例如:L = [[1,2,3],[2,5,8]]I = [2.5, 1.3]

然后我想得到: [4.5, 3.5]

任何帮助深表感谢。

标签: pythontensorflow

解决方案


你可以试试:

import tensorflow as tf

L_tf = tf.placeholder(shape=(None,3),dtype=tf.float64)
I_tf = tf.placeholder(shape=(None,),dtype=tf.float64)

a = tf.sequence_mask(I_tf,L_tf.shape[1],dtype=tf.float64)
# [[1. 1. 0.]
#  [1. 0. 0.]]
b = tf.sequence_mask(tf.ceil(I_tf),L_tf.shape[1],dtype=tf.float64)
# [[1. 1. 1.]
#  [1. 1. 0.]]
c = tf.mod(tf.stack([I_tf]*L_tf.shape[1],axis=1),1)
# [[0.5 0.5 0.5]
#  [0.3 0.3 0.3]]
prod = tf.where(tf.not_equal(a,b),c,tf.zeros_like(a)) + a
# [[1.  1.  0.5]
#  [1.  0.3 0. ]]
result = tf.reduce_sum(L_tf*prod,axis=1)

L = [[1,2,3],[2,5,8]]
I = [2.5, 1.3]
with tf.Session() as sess:
    print(sess.run(result,feed_dict={L_tf:L,I_tf:I}))

[4.5 3.5]

推荐阅读