[英]can't compile model using Non Max Suppression + Dense layer because of unknown NMS output size
我正在嘗試編寫一個 model 從 128 個提案中提取 10 個感興趣的區域並將它們提供給 Dense 層:
# x is an input tensor of size [None, 128, 4].
# scores is the corresponding [None, 128] score vector.
indices = tf.image.non_max_suppression(x, scores, 10)
x = x[indices]
x = tf.keras.layers.Flatten()(x)
x = tf.keras.layers.Dense(20)(x)
當我將它包裝在 keras Model 中並嘗試編譯它時,圖形構建失敗,因為tf.image.non_max_suppression
返回形狀為(None,)
而不是(10,)
的索引張量。 這使得扁平x[indices]
的(非批量)大小未知,因此 Dense 層在編譯時出現錯誤:
ValueError: The last dimension of the inputs to a Dense layer should be defined. Found None. Full input shape received: (None, None)
我的理解是 NMS 返回 n <= 10 項而不是 10 項,這就是為什么它沒有為圖形指定固定的 output 形狀的原因。 選擇 RoI 的輸入數較高,這樣從 NMS 中得到小於 10 RoI 的機會基本為零。 如何告訴我的 model 它應該總是期望 NMS 准確返回 10 個項目,以便密集層的輸入大小固定為 10*4?
我設法通過將索引填充到固定長度來解決這個問題,如下所示:
fixed_size_indices = tf.zeros(10, tf.int32)
indices = tf.image.non_max_suppression(x, scores, 10)
if tf.less_equal(tf.size(indices), 10):
indices = tf.concat([indices, tf.zeros(10 - tf.size(indices), dtype="int32")], 0)
fixed_size_indices += indices
x = x[fixed_size_indices]
如果我只是在indices
上進行填充而不將其添加到固定大小的張量,它就行不通。
不確定這是否是最好或最優雅的解決方案,但它現在有效。 理想情況下,如果 NMS 返回的區域少於 10 個,它將按照壞度遞增的順序填充額外的區域,但這不在此問題的 scope 范圍內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.