2017-02-13 4 views
1

Я пытаюсь использовать функцию scatter_nd в TensorFlow для изменения порядка элементов в строках матрицы. Например, предположим, что у меня есть код:Перемещение элементов внутри строк и столбцов матрицы - TensorFlow scatter_nd

indices = tf.constant([[1],[0]]) 
updates = tf.constant([ [5, 6, 7, 8], 
         [1, 2, 3, 4] ]) 
shape = tf.constant([2, 4]) 
scatter1 = tf.scatter_nd(indices, updates, shape) 
$ print(scatter1) = [[1,2,3,4] 
        [5,6,7,8]] 

Это переупорядочивает строки в updates матрицы.

Вместо того, чтобы изменять порядок строк, я хотел бы также изменить порядок отдельных элементов в каждой строке. Если у меня только есть вектор (Тензор ранга 1), то этот пример работает:

indices = tf.constant([[1],[0],[2],[3]]) 
updates = tf.constant([5, 6, 7, 8]) 
shape = tf.constant([4]) 
scatter2 = tf.scatter_nd(indices, updates, shape) 
$ print(scatter2) = [6,5,7,8] 

Что я действительно забочусь о том, чтобы иметь возможность поменять местами элементы в каждой строке в scatter1, как я сделал в scatter2, но сделайте это для каждой строки scatter1. Я пробовал различные комбинации indices, но продолжаю получать ошибки, которые не соответствуют строкам, заданными функцией scatter_nd.

ответ

1

В следующем обменивает элементы каждой строки каждой строки с помощью scatter_nd

indices = tf.constant([[[0, 1], [0, 0], [0, 2], [0, 3]], 
         [[1, 1], [1, 0], [1, 2], [1, 3]]]) 
updates = tf.constant([ [5, 6, 7, 8], 
         [1, 2, 3, 4] ]) 
shape = tf.constant([2, 4]) 
scatter1 = tf.scatter_nd(indices, updates, shape) 
with tf.Session() as sess: 
    print(sess.run(scatter1)) 

Давая выход:
[[6 5 7 8] [2 1 3 4]]

Местоположение координаты в indices определить, где принимается значение от updates и фактические кординаты определяют, где значения будут размещены в scatter1.

Этот ответ на несколько месяцев опоздал, но, надеюсь, по-прежнему полезен.

0

Предположим, вы хотите поменять элементы во втором измерении, сохраняя первый порядок измерения или нет.

import tensorflow as tf 
sess = tf.InteractiveSession() 


def prepare_fd(fd_indices, sd_dims): 
    fd_indices = tf.expand_dims(fd_indices, 1) 
    fd_indices = tf.tile(fd_indices, [1, sd_dims]) 
    return fd_indices 

# define the updates 
updates = tf.constant([[11, 12, 13, 14], 
         [21, 22, 23, 24], 
         [31, 32, 33, 34]]) 
sd_dims = tf.shape(updates)[1] 

sd_indices = tf.constant([[1, 0, 2, 3], [0, 2, 1, 3], [0, 1, 3, 2]]) 
fd_indices_range = tf.range(0, limit=tf.shape(updates)[0]) 
fd_indices_custom = tf.constant([2, 0, 1]) 

# define the indices 
indices1 = tf.stack((prepare_fd(fd_indices_range, sd_dims), sd_indices), axis=2) 
indices2 = tf.stack((prepare_fd(fd_indices_custom, sd_dims), sd_indices), axis=2) 

# define the shape 
shape = tf.shape(updates) 

scatter1 = tf.scatter_nd(indices1, updates, shape) 
scatter2 = tf.scatter_nd(indices2, updates, shape) 

print(scatter1.eval()) 

# array([[12, 11, 13, 14], 
#  [21, 23, 22, 24], 
#  [31, 32, 34, 33]], dtype=int32) 

print(scatter2.eval()) 

# array([[21, 23, 22, 24], 
#  [31, 32, 34, 33], 
#  [12, 11, 13, 14]], dtype=int32) 

Может этот пример помочь.

Смежные вопросы