Keras 框架搭建 textCNN 文本二分类模型的代码
时间: 2023-07-29 20:08:17 浏览: 116
Sure! Here's an example code for building a textCNN model for text binary classification using the Keras framework:
```python
from keras.layers import Conv1D, MaxPooling1D, Embedding, Flatten, Dense
from keras.models import Sequential
# Define the model architecture
model = Sequential()
# Embedding layer
model.add(Embedding(input_dim=vocab_size, output_dim=embedding_dim, input_length=max_sequence_length))
# Convolutional layers with different filter sizes
filters = [3, 4, 5]
conv_blocks = []
for filter_size in filters:
conv = Conv1D(filters=128, kernel_size=filter_size, activation='relu')(model.layers[-1].output)
pool = MaxPooling1D(pool_size=2)(conv)
flatten = Flatten()(pool)
conv_blocks.append(flatten)
# Concatenate the outputs of the conv blocks
concat = concatenate(conv_blocks, axis=-1)
# Fully connected layer
model.add(Dense(128, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Print the model summary
model.summary()
```
Make sure to replace `vocab_size`, `embedding_dim`, and `max_sequence_length` with appropriate values for your dataset.
阅读全文