Tensorflow: Как выполнить операцию параллельно на каждом n элементов? - PullRequest
0 голосов
/ 27 февраля 2019

Что мне делать, если я хочу получить сумму каждых 3 элементов?

test_arr = [1,2,3,4,5,6,7,8]

Звучит как функция карты

map_fn(arr, parallel_iterations = True, lambda a,b,c : a+b+c)

и результат map_fn(test_arr)должно быть

[6,9,12,15,18,21]

, что равно

[(1+2+3),(2+3+4),(3+4+5),(4+5+6),(5+6+7),(6+7+8)]

Я нашел решение после просмотра официальных документов: https://www.tensorflow.org/api_docs/python/tf/map_fn

import tensorflow as tf

def tf_map_elements_every(n, tf_op, input, dtype):
    if n >= input.shape[0]:
        return tf_op(input)
    else:
        return tf.map_fn(
            lambda params: tf_op(params),
            [input[i:i-n+1] if i !=n-1 else input[i:] for i in range(n)], 
            dtype=dtype
        )

Тест

t = tf.constant([1, 2, 3, 4, 5, 6, 7, 8])
op = tf_map_elements_every(3, tf.reduce_sum, t, tf.int32)

sess = tf.Session()
sess.run(op)

[Out]: array([ 6, 9, 12, 15, 18, 21])

Ответы [ 2 ]

0 голосов
/ 27 февраля 2019

Это даже проще: используйте понимание списка.Разделите список на 3-элементные сегменты и возьмите сумму каждого.Оберните их в список.

[sum(test_arr[i-2:i+1]) 
    for i in range(2, len(test_arr))]
0 голосов
/ 27 февраля 2019

Просто перебирайте массив, пока не достигнете 3 с конца.

# Takes a collection as argument
def map_function(array):
    # Initialise results and i
    results = []
    int i = 0

    # While i is less than 3 positions away from the end of the array
    while(i <= (len(array) - 3)):
        # Add the sum of the next 3 elements in results
        results.append(array[i] + array[i + 1] + array[i + 2]

        # Increment i
        i += 1

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