tensorflow - map_fn 对两个张量的每个可能组合进行计算 [英] tensorflow - map_fn to do computation on every possible combination of two tensors

查看:27
本文介绍了tensorflow - map_fn 对两个张量的每个可能组合进行计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何使用 map_fn 或任何其他 tensorflow-func 对两个输入张量的每个组合进行计算?

does anyone know how to use map_fn or any other tensorflow-func to do a computation on every combination of two input-tensors?

所以我想要的是这样的:有两个数组([1,2][4,5]),我想要一个带有计算输出的矩阵(例如 add) 在两个数组的每个可能的组合上.所以结果是:

So what i want is something like this: Having two arrays ([1,2] and [4,5]) i want as a result a matrix with the output of the computation (e.g. add) on every possible combination of the two arrays. So the result would be:

[[5,6],
 [6,7]]

我使用了 map_fn 但这仅采用索引方式的元素:

I used map_fn but this only takes the elements index-wise:

[[5]
 [7]]

有没有人知道如何实现这一点?

Has anyone an idea how implement this?

谢谢

推荐答案

您可以为每个 Tensor 添加新的单位维度,然后依赖广播添加:

You can add new unit dimensions to each Tensor, then rely on broadcasting addition:

import tensorflow as tf
import tensorflow.contrib.eager as tfe
tfe.enable_eager_execution()
first = tf.constant([1, 2])
second = tf.constant([4, 5])
print(first[None, :] + second[:, None])

打印:

tf.Tensor(
[[5 6]
 [6 7]], shape=(2, 2), dtype=int32)

这篇关于tensorflow - map_fn 对两个张量的每个可能组合进行计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆