[英]Keras set output of intermediate layer to 0 or 1 based on threshold
我有一個像零件一樣具有“分類”和“回歸”的模型。 我使用乘法層合並它們。 在執行乘法之前,我想根據閾值將分類部分的輸出設置為 0 或 1。 我嘗試使用帶有自定義函數的 Lambda 層,如下所示,但是我遇到了各種錯誤,我對這些錯誤一無所知。 我一邊走一邊一一解決它們並沒有增加我的理解。 誰能解釋如何定義修改值的自定義 Lambda 層函數?
我當前的 Lambda 層函數:(由於FailedPreconditionError: Attempting to use uninitialized value lstm_32/bias
無法工作)
def func(x):
a = x.eval(session=tf.Session())
a[x < 0.5] = 0
a[x >= 0.5] = 1
return K.variable(a)
回歸部分:
input1 = Input(shape=(1, ))
model = Sequential()
model.add(Embedding(vocab_size + 1, embedding, input_length=1))
model.add(LSTM(hidden, recurrent_dropout=0.1, return_sequences=True))
model.add(LSTM(6))
model.add(Reshape((3,2)))
model.add(Activation('linear'))
分類部分:
input2 = Input(shape=(1, ))
model2 = Sequential()
model2.add(Embedding(vocab_size + 1, embedding, input_length=1))
model2.add(LSTM(hidden, recurrent_dropout=0.1, return_sequences=True))
model2.add(LSTM(1))
model2.add(Activation('sigmoid'))
model2.add(???) # need to add 0-1 thresholding here
合並兩部分:
reg_head = model(input1)
clf_head = model2(input2)
merge_head = multiply(inputs=[clf_head, reg_head])
m2 = Model(inputs=[input1, input2], outputs=merge_head)
在func
,您無法eval
張量。
使用張量的想法是它們在整個模型中從頭到尾保持“連接”(他們稱之為圖)。 這種連接允許模型計算梯度。 如果您評估張量並嘗試使用這些值,您將斷開連接。
此外,為了獲取張量的實際值,您需要輸入數據。 並且輸入數據僅在您調用fit
、 predict
和類似方法時才會存在。 在構建階段,沒有數據,只有表示和連接。
僅使用張量的可能函數是:
def func(x):
greater = K.greater_equal(x, 0.5) #will return boolean values
greater = K.cast(greater, dtype=K.floatx()) #will convert bool to 0 and 1
return greater
不過要小心! 這將無法區分。 從現在開始,這些值將被視為模型中的常量。 這意味着在此之前的權重不會在訓練期間更新(您不會通過m2
訓練分類模型,但您仍然可以從model2
訓練它)。 有一些奇特的解決方法,如果您需要它們,請寫評論。
在Lambda
層中使用此函數:
model.add(Lambda(func, output_shape=yourOutputShapeIfUsingTheano))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.