你如何在 Python 中使用 Keras LeakyReLU? [英] How do you use Keras LeakyReLU in Python?

查看:29
本文介绍了你如何在 Python 中使用 Keras LeakyReLU?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Keras 制作 CNN,并编写了以下代码:

I am trying to produce a CNN using Keras, and wrote the following code:

batch_size = 64
epochs = 20
num_classes = 5

cnn_model = Sequential()
cnn_model.add(Conv2D(32, kernel_size=(3, 3), activation='linear',
                     input_shape=(380, 380, 1), padding='same'))
cnn_model.add(Activation('relu'))
cnn_model.add(MaxPooling2D((2, 2), padding='same'))
cnn_model.add(Conv2D(64, (3, 3), activation='linear', padding='same'))
cnn_model.add(Activation('relu'))
cnn_model.add(MaxPooling2D(pool_size=(2, 2), padding='same'))
cnn_model.add(Conv2D(128, (3, 3), activation='linear', padding='same'))
cnn_model.add(Activation('relu'))
cnn_model.add(MaxPooling2D(pool_size=(2, 2), padding='same'))
cnn_model.add(Flatten())
cnn_model.add(Dense(128, activation='linear'))
cnn_model.add(Activation('relu'))
cnn_model.add(Dense(num_classes, activation='softmax'))

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

我想使用 Keras 的 LeakyReLU 激活层,而不是使用 Activation('relu').但是,我尝试在适当的位置使用 LeakyReLU(alpha=0.1),但这是 Keras 中的激活层,我收到关于使用激活层而不是激活函数的错误.

I want to use Keras's LeakyReLU activation layer instead of using Activation('relu'). However, I tried using LeakyReLU(alpha=0.1) in place, but this is an activation layer in Keras, and I get an error about using an activation layer and not an activation function.

在这个例子中我如何使用 LeakyReLU?

How can I use LeakyReLU in this example?

推荐答案

Keras 中的所有高级激活,包括 LeakyReLU,都可以作为 layers,而不是作为激活;因此,您应该这样使用它:

All advanced activations in Keras, including LeakyReLU, are available as layers, and not as activations; therefore, you should use it as such:

from keras.layers import LeakyReLU

# instead of cnn_model.add(Activation('relu'))
# use
cnn_model.add(LeakyReLU(alpha=0.1))

这篇关于你如何在 Python 中使用 Keras LeakyReLU?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆