Keras set output of intermediate layer to 0 or 1 based on threshold

ぐ巨炮叔叔 提交于 2019-12-08 06:39:31

In func, you cannot eval the tensors.

The idea of using tensors is that they keep a "connection" (a graph, as they call it) from start to end in the entire model. This connection allows the model to compute gradients. If you eval a tensor and try to use these values, you will break the connection.

Also, for taking the actual values of a tensor, you need the input data. And the input data will only exist when you call fit, predict and similar methods. In the build phase there isn't data, only representations and connections.

A possible function using only tensors is:

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 

But be careful! This will not be differentiable. These values will be seen as constants from now on in the model. This means that the weights coming before this point will not be updated during training (you won't train the classification model via m2, but you will still be able to train it from model2). There are some fancy workarounds for this, if you need them, please write a comment.

Use this function in a Lambda layer:

model.add(Lamnda(func,output_shape=yourOtputShapeIfUsingTheano))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!