【发布时间】:2018-12-13 20:59:13
【问题描述】:
我想创建多个矩阵,它们的对角线为零并且是对称的。这种形式的 n 维矩阵需要 n*(n-1)/2 个参数才能完全指定。 这些参数稍后会学习...
在 numpy 中,我可以通过使用 numpy.triu_indices 来计算上三角矩阵的索引,该索引从主对角线上方的第一个对角线开始,然后用提供的参数填充它,如下面的代码 sn- p:
import numpy as np
R = np.array([[1,2,1,1,2,1], [1,1,1,1,1,1]])
s = R.shape[1]
M = R.shape[0]
iu_r, iu_c = np.triu_indices(s,1)
Q = np.zeros((M,s,s),dtype=float)
Q[:,iu_r,iu_c] = R
Q = Q + np.transpose(Q,(0,2,1))
输出:
[[[0. 1. 2. 1.]
[1. 0. 1. 2.]
[2. 1. 0. 1.]
[1. 2. 1. 0.]]
[[0. 1. 1. 1.]
[1. 0. 1. 1.]
[1. 1. 0. 1.]
[1. 1. 1. 0.]]]
但显然不能直接将其转换为 tensorflow,因为
import tensorflow as tf
import numpy as np
M = 2
s = 4
iu_r, iu_c = np.triu_indices(s,1)
rates = tf.get_variable(shape=(M,s*(s-1)/2), name="R", dtype=float)
Q = tf.get_variable(shape=(M,s,s), dtype=float, initializer=tf.initializers.zeros, name="Q")
Q = Q[:,iu_r,iu_c].assign(rates)
失败
TypeError: Tensors in list passed to 'values' of 'Pack' Op have types [int32, int64, int64] that don't all match.
从张量流中的向量张量定义矩阵张量的正确方法是什么?
编辑:
我目前的解决方案是使用 tensorflow 提供的 scatter_nd 函数进行嵌入,因为它适合不需要像 fill_triangular 那样分配冗余变量的需要。但是,索引与 numpy 生成的索引不兼容。目前硬编码以下示例有效:
import tensorflow as tf
import numpy as np
M = 2
s = 4
iu_r, iu_c = np.triu_indices(s,1)
rates = tf.get_variable(shape=(M,s*(s-1)/2), name="R", dtype=float)
iupper = [[[0,0,1],[0,0,2],[0,0,3],[0,1,2],[0,1,3],[0,2,3]],[[1,0,1],[1,0,2],[1,0,3],[1,1,2],[1,1,3],[1,2,3]]]
Q = tf.scatter_nd(iupper,rates,shape=(M,s,s), name="rate_matrix")
翻译得到的索引应该没问题
iu_r, iu_c = np.triu_indices(s,1)
但也许有人对此有更优雅的解决方案?
【问题讨论】:
标签: python-3.x numpy tensorflow