python - 如何仅对张量的一部分求和?
问题描述
我想从上到下对张量的一部分求和,而那部分取决于另一个张量的值。
例如: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]
任何帮助深表感谢。
解决方案
你可以试试:
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]
推荐阅读
- javascript - 为什么iframe源代码比文件源代码?
- azure-resource-manager - 如何使用 Bicep 引用其他订阅中的资源?
- c# - WinUI 3 中的 Shell_NotifyIcon
- regex - 上一次重复期间的正则表达式模式不同的行为
- python - 在 Pandas 中返回列和组时制作 SQL 案例
- python - 用python读取Excel文件
- merge - 在 SNOWFLAKE 中进行横向展平时重复主键
- angular - 角度嵌套导航和路由器插座
- python - 在 Replit 中保存游戏并加载以从保存的位置开始
- jquery - 查找完全没有属性的元素