【问题标题】:Transform an array into a matrix with its elements filling the upper triangle of matrix in Tensorflow将数组转换为矩阵,其元素填充 Tensorflow 中矩阵的上三角形
【发布时间】:2019-05-16 01:08:46
【问题描述】:

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

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))

导致错误“无法将类型对象转换为张量。内容:[无]。考虑将元素转换为支持的类型”。我尝试铸造,但没有奏效。谁能帮帮我?

【问题讨论】:

  • 我看到这个错误tensorflow.python.framework.errors_impl.InvalidArgumentError: WhereOp : Unhandled input dimensions: 0 你的x 是这样的吗? x = tf.constant([1, 2, 3, 4, 5])
  • 'x' 是另一个占位符,它是用于填充矩阵的一维数组/向量。我认为问题在于,作为占位符,它可以具有可变的批量大小。批量大小的可变性最终会导致此错误。当我使用恒定张量(如您提到的那个)进行测试时,它工作正常。我还没找到解决办法
  • 请用您评论的详细信息更新您的问题。
  • 我已经更新了问题
  • 我认为你提供了占位符?对吧?

标签: python tensorflow matrix


【解决方案1】:

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

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)

输出是这样的。

[[0 1 2 3]
 [0 0 4 5]
 [0 0 0 6]
 [0 0 0 0]]

【讨论】:

  • 'x' 是一个占位符,它是一个用于填充矩阵的一维数组/向量。当声明一个常量张量时,代码可以正常工作。我无法找到处理“x”的可变批量大小的解决方案。我尝试使用“InteractiveSession”,但没有成功
  • 很棒的答案,而且它没有赞成票被严重低估了 IMO。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-17
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
  • 2016-10-03
  • 2022-11-29
  • 1970-01-01
相关资源
最近更新 更多