python - 使用两个张量向量创建 N x M 张量矩阵并为每个 (n,m) 对应用一个函数

标签 python tensorflow

我有两个形状为 (100,) 的张量 X 和 Z,我想创建一个 Tensor X x Z,它的形状为 (100, 100).

对于这个矩阵中的每个对元素,我想应用一些我已经定义的函数,即 fn(x,z) 用于矩阵中的每个可能组合。

我是 TensorFlow 的新手,我习惯于按顺序思考,在处理 numpy 数组时对每个向量使用两个 for 循环。

我如何在 TensorFlow 中执行此操作?非常感谢。

最佳答案

一般问题

您可以创建一个自定义层来解决这个问题。

import tensorflow as tf
from tensorflow.keras.layers import Layer


def fn(x, y):
    return x + y


class PairMatrix(Layer):
    def __init__(self, func=None):
        super(PairMatrix, self).__init__()
        self.func = func

    def call(self, inputs, **kwargs):
        X, Y = tf.meshgrid(inputs[0], inputs[1])
        return self.func(X, Y)


x = tf.constant([1, 2, 3])
y = tf.constant([1, 2, 3])

z = PairMatrix(func=fn).apply([x, y])

应该创建一个将函数作为参数的层。调用时,该函数将应用于输入 x 和 y 的构造网格。

在上面的简单测试用例中,产生的输出是:

z = tf.Tensor([[2 3 4]
               [3 4 5]
               [4 5 6]], shape=(3, 3), dtype=int32)

关于您的评论

如果您只对协方差感兴趣,可以使用 tfp.stats.covariance

关于python - 使用两个张量向量创建 N x M 张量矩阵并为每个 (n,m) 对应用一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60903203/

相关文章:

python - pytest 可以忽略特定警告吗?

python - 在 Tensorflow 中使用镜像策略时出错

python - 连接表中的列值 - pandas

javascript - 是否有 Python、JavaScript 和 CSS 的配置系统?

python - 在 Pandas 中将一个时间序列插值到另一个时间序列

tensorflow - 如何在 Tensorflow r12 中按文件名恢复模型?

tensorflow - 使用 tf.image.Dataset 时卡住 tensorflow 中的图形

tensorflow - 如何实现标记嵌入的中心损失和其他运行平均值

python - tensorflow TFRecord k-hot 编码

python - 使用其中一个数据帧作为键将 Python 中的数据帧组合到字典中