Преобразуйте массив в матрицу, элементы которой заполняют верхний треугольник матрицы в Tensorflow - PullRequest
1 голос
/ 16 мая 2019

Я хочу преобразовать массив в матрицу, заполнив верхний треугольник матрицы одним из следующих способов

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 голосов
/ 17 мая 2019

Один из ваших шаблонов вывода получается путем небольшого рефакторинга вашего кода.

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

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...