1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| from keras.wrappers.scikit_learn import KerasClassifier def create_model(kernel_initializer='he_normal', optimizer='adam', activation='relu', dropout=0.5): inputs = Input(shape=(sequence_length,), dtype='int32') embedding = Embedding(input_dim=vocabulary_size, output_dim=embedding_dim, input_length=sequence_length)(inputs) reshape = Reshape((sequence_length, embedding_dim, 1))(embedding)
conv_0 = Conv2D(num_filters, kernel_size=( filter_sizes[0], embedding_dim), padding='valid', kernel_initializer=kernel_initializer, activation=activation)(reshape) conv_1 = Conv2D(num_filters, kernel_size=( filter_sizes[1], embedding_dim), padding='valid', kernel_initializer=kernel_initializer, activation=activation)(reshape) conv_2 = Conv2D(num_filters, kernel_size=( filter_sizes[2], embedding_dim), padding='valid', kernel_initializer=kernel_initializer, activation=activation)(reshape)
maxpool_0 = MaxPool2D(pool_size=( sequence_length - filter_sizes[0] + 1, 1), strides=(1, 1), padding='valid')(conv_0) maxpool_1 = MaxPool2D(pool_size=( sequence_length - filter_sizes[1] + 1, 1), strides=(1, 1), padding='valid')(conv_1) maxpool_2 = MaxPool2D(pool_size=( sequence_length - filter_sizes[2] + 1, 1), strides=(1, 1), padding='valid')(conv_2)
concatenated_tensor = Concatenate(axis=1)( [maxpool_0, maxpool_1, maxpool_2]) flatten = Flatten()(concatenated_tensor) dropout = Dropout(dropout)(flatten) output = Dense(units=2, activation='softmax')(dropout)
model = Model(inputs=inputs, outputs=output)
model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy']) return model
keras_clf = KerasClassifier(build_fn=create_model)
|