gpt4 book ai didi

python - 在 Tensorflow 中将一组常量(一维数组)与一组矩阵(三维数组)相乘

转载 作者:太空宇宙 更新时间:2023-11-04 04:34:18 25 4
gpt4 key购买 nike

我的最终目标是训练一个基于均值和协方差参数化的 4D 多元高斯分布

enter image description here

在哪里,

enter image description here

和,

enter image description here

目前我有以下代码:

import tensorflow as tf
import numpy as np

value = [[1,2.0,3,4,5],[0,2,4,6,8],[80,7,6,5,4]]

value=tf.constant(value)

cov= tf.slice(value,[0,int(value.shape[1])-1],[int(value.shape[0]),1])
mean= tf.slice(value,[0,0],[int(value.shape[0]),int(value.shape[1])-1])

eyes=tf.eye(int(mean.shape[1]),batch_shape=[int(value.shape[0])])


#eyes = tf.multiply(eyes,cov)



normal = tf.contrib.distributions.MultivariateNormalFullCovariance(
loc=mean,
covariance_matrix=eyes)

value = [[1,2.0,3,4,5],[0,2,4,6,8],[80,7,6,5,4]] 是其余代码可能接收的示例。

在上面的例子中

cov = <tf.Tensor 'Slice_2:0' shape=(3, 1) dtype=float32>
eyes = <tf.Tensor 'eye_1/MatrixDiag:0' shape=(3, 4, 4) dtype=float32>

cov = [[5.] [8.] [4.]]`
eyes = [[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]

[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]

[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]]`

我的问题是,如何在给定 coveyes 的情况下获得 result?结果如下:

result = [[[5., 0., 0., 0.],
[0., 5., 0., 0.],
[0., 0., 5., 0.],
[0., 0., 0., 5.]],

[[8., 0., 0., 0.],
[0., 8., 0., 0.],
[0., 0., 8., 0.],
[0., 0., 0., 8.]],

[[4., 0., 0., 0.],
[0., 4., 0., 0.],
[0., 0., 4., 0.],
[0., 0., 0., 4.]]]

enter image description here

提前致谢

最佳答案

Tensorflow 使用与 numpy 相同类型的索引,这可能非常强大。

您可以在这里查看详细信息:https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html请注意,np.newaxis 定义为与 None 相同。

对于您的问题,您可以为数据添加一个额外的维度,以确保数组相乘的方式没有歧义。

import numpy as np
cov = np.array([[5.],[8.],[4.]])
eyes = np.array([[[1.0,0,0,0],[0.0,1.0,0.0,0],[0.0,0.0,1.0,0],[0.0,0.0,0.0,1.0]],[[1.0,0,0,0],[0.0,1.0,0.0,0],[0.0,0.0,1.0,0],[0.0,0.0,0.0,1.0]],[[1.0,0,0,0],[0.0,1.0,0.0,0],[0.0,0.0,1.0,0],[0.0,0.0,0.0,1.0]]])
result = cov[:,:,None]*eyes

在这里使用 None 增加了一个额外的维度,使 cov 成为一个 3x1x1 数组,它可以明确地与 3x4x4 数组相乘。您也可以在 tensorflow 中以这种方式使用 None

如果每个对应的维度大小相同,或者其中一个维度的大小为 1,则两个数组可以明确相乘。

关于python - 在 Tensorflow 中将一组常量(一维数组)与一组矩阵(三维数组)相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52087206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com