簡體   English   中英

如何對自定義 Keras 層進行故障排除

[英]How to troubleshoot custom Keras layers

I'm creating a model using Keras (I'm a beginner) and wrote a lambda function to randomly choose whether or not to flip the initial input layer.

這是嘗試這樣做的片段:

input_global = Input(shape=(2001,1))
flipped = Lambda(lambda x: keras.backend.reverse(x, axes=1) if np.random.random() < 0.5 else x, output_shape=(input_global.shape[1], input_global.shape[2]))(input_global)

我的 model 編譯,但在 model 的定義中間記錄諸如print("Hello, world")之類的消息只會導致“Hello world”被記錄一次——並非每次數據在訓練期間進入 Z20F35E630DAF44DBFACZC3F6 時。

我怎么知道我的 function 做了我打算做的事情?

在構建 Keras model 時,您正在構建操作圖,並且每當您通過 model 運行輸入時,您正在通過該操作圖運行輸入。 換句話說,您構建一個 model 一次,然后您可以根據需要多次運行輸入。

非 Keras 函數不會成為圖表的一部分,包括printnp.random.random()等操作。 您將需要使用 Keras 等效項。

對於print ,請使用 function keras.backend.print_tensor

對於np.random.random ,使用 function keras.backend.random_uniform

我認為您不打算這樣做,但是因為您在自定義層中使用np.random.random() ,所以只有在構建 model 時才會執行該操作。 只要您通過 model 運行數據,它就不會運行。 換句話說,該層要么只反轉輸入,要么只返回輸入。 要獲得我認為您想要的隨機行為,您需要使用 Keras function (即keras.backend.random_uniform )。 每次運行 model 時,使用 Keras function 將生成一個隨機數。

為了強調這一點, np.random.random()將在您構建 model 時運行一次,本質上它將在構建時確定該層將做什么(即,它要么只反轉輸入,要么它將只返回輸入不變)。 keras.backend.random_uniform() , on the other hand, will not generate a random number when you build the model, but instead it adds a random_uniform operation to the model, so every time data goes through the model, a random number will be從那個點的均勻分布中得出。

暫無
暫無

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

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