梯度是張量的嵌套串列。我想獲取漸變中元素的總數,并將這個數字記錄為 int。但是,我不知道如何在 tf.function 中執行此操作。
import tensorflow as tf
grad = [tf.ones((500,200)), tf.ones((200,)), tf.ones((200,1))]
def test(grad):
m = tf.cast(0, tf.int32)
for i in grad:
m = m tf.math.reduce_prod(tf.shape(i))
out = tf.zeros((m,))
out.set_shape((m,))
return out
代碼在渴望模式下按預期作業。如果你應用 tf.function,你會得到以下錯誤
TypeError:維度值必須是整數或無或具有索引方法,得到值 '<tf.Tensor 'add_2:0' shape=() dtype=int32>' 型別為 '<class 'tensorflow.python.framework.ops。張量'>'
問題是 'm' 應該是 <tf.Tensor: shape=(), dtype=int32, numpy=100400> 但它是 <tf.Tensor 'add_2:0' shape=() dtype=int32>。
uj5u.com熱心網友回復:
Per Jirayu 這里是解決方法
import tensorflow as tf
grad = [tf.ones((500,200)), tf.ones((200,)), tf.ones((200,1))]
@tf.function
def test(grad):
m = tf.cast(0, tf.int32)
for i in grad:
m = m tf.math.reduce_prod(tf.shape(i))
m = tf.zeros((m,)).shape[0] # this m can be used to define shape
return out
uj5u.com熱心網友回復:
計算和預計算變數。
減少計算限制的預計算方法作為類似任務。
[ 樣本 ]:
import tensorflow as tf
grad = [tf.ones((500,200)), tf.ones((200,)), tf.ones((200,1))]
@tf.function
def test(grad):
m = tf.cast(0, tf.int32)
m = tf.add(m, 0)
for i in grad:
m = m tf.math.reduce_prod(tf.shape(i))
# Compute of tf.math.multiply
out = tf.zeros((int(m),))
out.set_shape((out.shape[0],))
return out
print( test( grad ) )
[ 輸出 ]:

uj5u.com熱心網友回復:
您不必為了獲取漸變中的元素數量而創建零張量。
grad = [tf.ones((500,100)), tf.ones((200,)), tf.ones((100,1,3))]
@tf.function
def test(grad):
m = tf.reduce_sum([tf.reduce_prod(i.shape) for i in grad])
return m
test(grad)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/473130.html
下一篇:如何正確堆疊RNN層?
