使用多层双向的LSTM网络实现imdb_reviews数据的二分类任务完整源码
时间: 2024-02-28 19:57:23 浏览: 74
好的,以下是完整的源码实现,包括数据预处理、模型定义、编译训练和评估等步骤:
```
import tensorflow as tf
from tensorflow.keras.datasets import imdb
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, LSTM, Dense, Bidirectional
# 仅使用前10000个最常见的单词
vocab_size = 10000
# 导入数据集并对其进行预处理
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=vocab_size)
maxlen = 500
train_data = pad_sequences(train_data, maxlen=maxlen)
test_data = pad_sequences(test_data, maxlen=maxlen)
# 定义模型
model = Sequential()
model.add(Embedding(vocab_size, 128, input_length=maxlen))
model.add(Bidirectional(LSTM(64, dropout=0.5)))
model.add(Dense(1, activation='sigmoid'))
# 编译模型并训练
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
history = model.fit(train_data, train_labels, epochs=10, batch_size=32, validation_split=0.2)
# 评估模型
test_loss, test_acc = model.evaluate(test_data, test_labels)
print('Test Accuracy: ', test_acc)
```
希望这份完整的代码可以帮到您。
阅读全文