from keras.models import Sequential from keras.layers import Embedding, Convolution1D, GlobalMaxPooling1D, Dense model = Sequential() model.add(Embedding(input_dim=10000, output_dim=32, input_length=100)) model.add(Convolution1D(64, 3, padding='same', activation='relu')) model.add(GlobalMaxPooling1D()) model.add(Dense(1, activation='sigmoid'))
from keras import backend as K from keras.layers import Layer class CustomConv1D(Layer): def __init__(self, filters, kernel_size, activation, **kwargs): self.filters = filters self.kernel_size = kernel_size self.activation = K.activations.get(activation) super(CustomConv1D, self).__init__(**kwargs) def build(self, input_shape): self.kernel = self.add_weight(name='kernel', shape=(self.kernel_size, input_shape[-1], self.filters), initializer='glorot_uniform', trainable=True) super(CustomConv1D, self).build(input_shape) def call(self, inputs): outputs = K.conv1d( inputs, self.kernel, padding='valid' ) return self.activation(outputs) model = Sequential() model.add(Convolution1D(64, 3, activation='relu')) model.add(CustomConv1D(128, 3, activation='tanh')) model.add(Dense(1, activation='sigmoid'))In this example, we define a custom implementation of the 1D convolution layer that allows specifying the activation function. We implement this using the Keras Layer class and overriding the build and call methods to define the layer computation. We then use this custom layer in a sequential model with a pre-defined Convolution1D layer and add a final dense layer with sigmoid activation for binary classification predictions. Package library: Keras