生成LSTM预测分类的python代码
时间: 2023-10-24 18:12:18 浏览: 105
当然可以,以下是一个使用 LSTM 进行分类预测的 Python 代码示例:
```python
import numpy as np
from keras.datasets import imdb
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout, Embedding
from keras.preprocessing import sequence
# 加载 IMDB 数据集
(X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=5000)
# 将输入序列填充或截断为固定的长度
max_words = 500
X_train = sequence.pad_sequences(X_train, maxlen=max_words)
X_test = sequence.pad_sequences(X_test, maxlen=max_words)
# 构造 LSTM 模型
model = Sequential()
model.add(Embedding(input_dim=5000, output_dim=32, input_length=max_words))
model.add(Dropout(0.2))
model.add(LSTM(100))
model.add(Dropout(0.2))
model.add(Dense(1, activation='sigmoid'))
# 编译模型
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# 训练模型
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=3, batch_size=64)
# 评估模型
scores = model.evaluate(X_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1] * 100))
```
希望这段代码能够对你有所帮助。如果你有更多的问题,欢迎继续问我哦。
阅读全文