簡體   English   中英

如何在 Tensorflow 循環中轉換循環?

[英]How to convert the loop in Tensorflow loop?

我已經編寫了一個程序並嘗試用 Tensorflow 編寫它,以便我可以使用 GPU。 請讓我知道我可以做些什么來將其轉換為 tensorflow。
這是正常執行的代碼:

def function(array,position,times):
    o = []
    for loop in range(position,30):
        result = 0.0
        for k in range(times):
            result += array[loop-k]
        result /= times
        o.append(result)
    return o
q = [i for i in range(30)]
output = function(q,10,5)
print(output)

使用 Tensorflow 我試過這個:

import tensorflow as tf
tf.enable_eager_execution()
def function_tf(array,position,times):
    o = tf.TensorArray(tf.float32,(30-position))
    index = tf.Variable(0)
    for loop in range(position,30):
        result = tf.Variable(0.0)
        for k in range(times):
            result.assign_add(array[loop-k].numpy())
            # print(result)
        result = tf.divide(result,times)
        o = o.write(index.numpy(),result.numpy())
        index.assign_add(1)
    return o.stack().numpy()
q = [i for i in range(30)]
q = tf.convert_to_tensor(q)

output = function_tf(q,tf.constant(10),tf.constant(5.0))
print(output)

輸出是一樣的:

[ 8.  9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25.
 26. 27.]

但唯一的事實是 Tensorflow 代碼中的循環仍然是 Python 循環,因此它將與 CPU 一起工作,而不是與 GPU 一起工作。 我希望一切都在 GPU 內發生。 只能通過 CPU 進行分配。
請幫我轉換循環。

實際上,您可以在沒有循環的情況下更簡單地編寫該函數,如下卷積:

import tensorflow as tf
tf.enable_eager_execution()

def function(array, position, times):
    array = tf.convert_to_tensor(array)
    array = array[tf.newaxis, tf.maximum(position - times + 1, 0):, tf.newaxis]
    filter = tf.fill([times, 1, 1], tf.dtypes.cast(1 / times, array.dtype))
    return tf.nn.conv1d(array, filter, stride=1, padding='VALID')[0, :, 0]
print(function(tf.range(30.), 10, 5).numpy())
# [ 8.000001  9.       10.       11.       12.       13.       14.
#  15.       16.       17.       18.       19.       20.       21.
#  21.999998 23.       24.000002 25.       26.       26.999998]

編輯:如果您想在原始代碼中顯式地重新創建循環(盡管它可能會更慢),您可以使用tf.while_loop進行如下操作:

import tensorflow as tf
tf.enable_eager_execution()

def function(array, position, times):
    array = tf.convert_to_tensor(array)
    dt = array.dtype
    ta = tf.TensorArray(dt, size=tf.size(array) - position, element_shape=())
    ta, _ = tf.while_loop(
        lambda ta, i: i < tf.size(array),
        lambda ta, i: (ta.write(i - position, tf.reduce_sum(array[i - times + 1:i + 1]) / times), i + 1),
        [ta, position])
    return ta.stack()
print(function(tf.range(30.), 10, 5).numpy())
# [ 8.  9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25.
#  26. 27.]

或者,更進一步,編寫兩個循環而不是使用tf.reduce_sum

import tensorflow as tf
tf.enable_eager_execution()

def function(array, position, times):
    array = tf.convert_to_tensor(array)
    dt = array.dtype
    ta = tf.TensorArray(dt, size=tf.size(array) - position, element_shape=())
    ta, _ = tf.while_loop(
        lambda ta, i: i < tf.size(array),
        lambda ta, i: (ta.write(i - position, 
                                tf.while_loop(lambda s, j: j < times,
                                              lambda s, j: (s + array[i - j], j + 1),
                                              [tf.zeros((), dt), 0])[0] / times),
                       i + 1),
        [ta, position])
    return ta.stack()
print(function(tf.range(30.), 10, 5).numpy())
# [ 8.  9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25.
#  26. 27.]

由於您使用的是急切執行,您還可以直接使用 Python 循環,如下所示:

import tensorflow as tf
tf.enable_eager_execution()

def function(array, position, times):
    array = tf.convert_to_tensor(array)
    o = []
    for loop in range(position, tf.size(array)):
        result = 0
        for k in range(times):
            result += array[loop-k]
        result /= times
        o.append(result)
    return tf.stack(o)
print(function(tf.range(30.), 10, 5).numpy())
# [ 8.  9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25.
#  26. 27.]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM