将数组转换为矩阵,其元素填充Tensorflow中矩阵的上三角

时间:2019-05-16 01:08:47

标签: python tensorflow matrix

我想通过以下一种方式将数组转换成填充矩阵上三角的矩阵

array to matrix

tf.contrib.distributions.fill_triangular 中,三角形矩阵元素按顺时针螺旋填充,包括对角元素。我尝试了以下命令,但没有用。

x = placeholder(tf.float32, shape=[None, 891])
dummy_expected_output = placeholder(tf.float32, shape=[None, 42, 42])
ones = tf.ones_like(dummy_expected_output) #size of the output matrix 
mask_a = tf.matrix_band_part(ones, 0, -1)  # Upper triangular matrix of 0s and 1s
mask_b = tf.matrix_band_part(ones, 0, 0)  # Diagonal matrix of 0s and 1s
mask = tf.subtract(mask_a, mask_b) # Mask of upper triangle above diagonal
zero = tf.constant(0, dtype=tf.float32)
non_zero = tf.not_equal(ones, zero) #Conversion of mask to Boolean matrix

indices = tf.cast(tf.where(non_zero),dtype=tf.int64) # Extracting the indices of upper triangle elements

zeros = tf.zeros_like(dummy_expected_output) #size of the output matrix
out = tf.add(zeros, tf.sparse_to_dense(indices,tf.cast(tf.shape(zeros),dtype=tf.int64), tf.reshape(x,[-1]), default_value=0))

它导致错误“ 未能将类型的对象转换为Tensor。内容:[无]。考虑将元素强制转换为受支持的类型 ”。我尝试了投射,但没有成功。有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

您的输出模式之一是通过稍微重构代码而获得的。

public function rules()
{
    return [
        'token' => 'required|string|size:32'
    ];
}

输出是这个。

sess = tf.InteractiveSession()
x = tf.constant([1, 2, 3, 4, 5, 6])
ones = tf.ones((4,4),dtype=tf.int64) #size of the output matrix
mask_a = tf.matrix_band_part(ones, 0, -1)  # Upper triangular matrix of 0s and 1s
mask_b = tf.matrix_band_part(ones, 0, 0)  # Diagonal matrix of 0s and 1s
mask = tf.subtract(mask_a, mask_b) # Mask of upper triangle above diagonal

zero = tf.constant(0, dtype=tf.int64)
non_zero = tf.not_equal(mask, zero) #Conversion of mask to Boolean matrix
sess.run(non_zero)
indices = tf.where(non_zero) # Extracting the indices of upper trainagle elements

out = tf.SparseTensor(indices,x,dense_shape=tf.cast((4,4),dtype=tf.int64))
dense = tf.sparse_tensor_to_dense(out)
dense = tf.print(dense, [dense], summarize=100)
sess.run(dense)

enter image description here