我需要做一些我認為應該直截了當的事情:將卷積層的輸出除以批量大小(如果您對原因感興趣,我可以詳細說明)。
這是重現我正在嘗試做的最小代碼
from keras.models import *
from keras.layers import *
from keras import backend as K
input = Input((24,24,3))
conv = Conv2D(8,4,1,'SAME')(input)
norm = Lambda(lambda x:x[0]/x[1])((conv,input.shape[0]))
model = Model(inputs = input, outputs = norm)
model.summary()
但是,我收到錯誤:
----> norm = Lambda(lambda x:x[0]/x[1])((conv,input.shape[0]))
model = Model(inputs = input, outputs = norm)
ValueError: Exception encountered when calling layer "lambda_9" (type Lambda).
None values not supported.
Call arguments received:
? inputs=('tf.Tensor(shape=(None, 24, 24, 8), dtype=float32)', 'None')
? mask=None
? training=None
我覺得這是“應該允許的”。我錯過了什么或做錯了什么?謝謝!
uj5u.com熱心網友回復:
實際上有兩種方法可以獲得符號張量的形狀:(tensor.shape您正在使用的那個)和tf.shape(tensor). 簡而言之,tensor.shape回傳在編譯時已知的張量的“靜態形狀”。在以下情況下這可能會出現問題:您嘗試使用在編譯時未知但在模型實際運行時定義的維度。tensor.shape在這里失敗,因為它只會回傳靜態已知的None(本質上是未知批量大小的占位符)。
另一方面,tf.shape(tensor)回傳張量的動態形狀,它實際上是張量本身,您可以使用它來定義基于未知形狀的操作。這意味著您只需要替換一行:
norm = Lambda(lambda x:x[0]/x[1])((conv, tf.cast(tf.shape(input)[0], tf.float32)))
請注意,我們必須將形狀轉換為浮點數以避免 dtype 不匹配。這讓單元格運行良好:
Model: "model"
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
input_3 (InputLayer) [(None, 24, 24, 3)] 0 []
tf.compat.v1.shape_1 (TFOpLamb (4,) 0 ['input_3[0][0]']
da)
tf.__operators__.getitem_1 (Sl () 0 ['tf.compat.v1.shape_1[0][0]']
icingOpLambda)
conv2d_2 (Conv2D) (None, 24, 24, 8) 392 ['input_3[0][0]']
tf.cast (TFOpLambda) () 0 ['tf.__operators__.getitem_1[0][0
]']
lambda_2 (Lambda) (None, 24, 24, 8) 0 ['conv2d_2[0][0]',
'tf.cast[0][0]']
==================================================================================================
Total params: 392
Trainable params: 392
Non-trainable params: 0
__________________________________________________________________________________________________
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/473129.html
