简体   繁体   English

自己激活 function 时出错

[英]error when making my own activation function

I am trying to test an activation function on MNIST data but it gave an error:我正在尝试在 MNIST 数据上测试激活 function 但它给出了错误:

TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

Here is my activation function:这是我的激活 function:

def fun1(x):
    return np.sqrt(x) if x>=0 else (-(np.sqrt(-x)))

and here is the model:这是 model:

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),  kernel_regularizer=regularizers.l2(w_l2),
             input_shape=input_shape))
model.add(BatchNormalization())
model.add(Activation(fun1))
model.add(Conv2D(64, (3, 3),  kernel_regularizer=regularizers.l2(w_l2)))
model.add(BatchNormalization())
model.add(Activation(fun1))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, kernel_regularizer=regularizers.l2(w_l2)))
model.add(BatchNormalization())
model.add(Activation(fun1))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
          optimizer=keras.optimizers.Adam(),
          metrics=['accuracy'])
model.summary()

In the custom activation function, x is a tensor, so Keras backend methods need to be used instead of numpy.在自定义激活function中, x是张量,所以需要使用Keras backend方法,而不是numpy。 Your implementation could be changed to something like this:您的实现可以更改为如下所示:

from keras import backend as K
def fun1(x):
    return K.sqrt(K.abs(x))

For more examples, look at Keras defined activations:有关更多示例,请查看 Keras 定义的激活:

https://github.com/keras-team/keras/blob/master/keras/activations.py https://github.com/keras-team/keras/blob/master/keras/activations.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM