将一组常量(1D数组)与一组矩阵(3D数组)相乘(以十为单位)

2024-04-24 13:34:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

提前谢谢。你知道吗


Tags: 代码importvaluetfasslicemeancov
1条回答
网友
1楼 · 发布于 2024-04-24 13:34:40

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成为一个3x1x1x1数组,它可以与3x4x4数组明确相乘。在tensorflow中也可以这样使用None。你知道吗

如果两个数组的每个对应维度的大小相同,或者其中一个数组的大小为1,那么两个数组可以毫不含糊地相乘。你知道吗

相关问题 更多 >