首页 > 解决方案 > keras 张量流中的函数实现

问题描述

假设我有三个张量形状(n,1) T,r,E,我想实现一个计算:sum(i,j) (T[j] < T[i]) (r[j] > r[i]) E[j]. 我该如何进行?

这就是我所拥有的

#tensor examples
T=K.constant([1,4,5])
r=K.constant([.8,.3,.7])
E=K.constant([1,0,1])

# cartesian product of T to compare element wise
c = tf.stack(tf.meshgrid(T, T, indexing='ij'), axis=-1)
cartesian_T = tf.reshape(c, (-1, 2))

# cartesian product of r to compare elemento wise
r = tf.stack(tf.meshgrid(r, r, indexing='ij'), axis=-1)
cartesian_r = tf.reshape(r, (-1, 2))

# TO DO: 
# compare the two columns in cartesian T and cast to integer 1/0 if  
# second column in T less/greater than first column in T => return tensor


# compare the two columns in cartesian E and cast to integer 1/0 if  
# second column in r greater/less than first column in r => return tensor

# multiply previous tensors by a broadcasted version of E, then do K.sum()

你认为我在正确的轨道上吗?你会建议什么来实现这个?

标签: python-3.xtensorflowkeras

解决方案


尝试:

import keras.backend as K
import tensorflow as tf

T=K.constant([1,4,5])
r=K.constant([.8,.3,.7])
E=K.constant([1,0,1])

T_new = tf.less(T[tf.newaxis,:],T[:,tf.newaxis])
r_new = tf.greater(r[tf.newaxis,:],r[:,tf.newaxis])
E_row,_ = tf.meshgrid(E, E)
result = tf.reduce_sum(tf.boolean_mask(E_row,tf.logical_and(T_new,r_new)))

with tf.Session() as sess:
    print(sess.run(result))

#print
2.0

推荐阅读