python-3.x - 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()
你认为我在正确的轨道上吗?你会建议什么来实现这个?
解决方案
尝试:
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
推荐阅读
- dialogflow-es - 如何通过 Dialogflow Fulfillment 向 Facebook 发送快速回复
- keras - Keras 中的 VAE 在 3 类图像上可视化潜在空间
- docker - 如何使用 Dockerfile 完全将 weblogic 应用程序部署为 docker 容器?
- azure - 将数据工厂的公共访问权限从启用更改为禁用的 Powershell 命令
- c# - .net 应用程序基本身份验证
- c - 在不同的函数中使用 C 全局变量时被截断
- excel - 转换 Excel 函数或 VBA 以在 Word 宏中使用
- python - TypeError:'WindowsPath' 类型的参数不可迭代 - 在 django python 中
- speech-recognition - 适用于 3 名以上参与者的演讲者分类工具
- html - CSS:表格边框属性被覆盖