cnn-lstm神经网络预测文本代码
时间: 2023-09-28 21:07:39 浏览: 108
DNN lstm预测代码
以下是一个简单的 cnn-lstm 神经网络预测文本的代码示例,使用了 Keras 框架:
```python
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout, Conv1D, MaxPooling1D, Flatten, Activation
from keras.utils import np_utils
from keras.callbacks import ModelCheckpoint
from keras.optimizers import Adam
# 数据预处理
max_features = 2000
maxlen = 100
# 读取数据
X_train, y_train, X_test, y_test = load_data()
# 将数据转换为 one-hot 编码
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
# 构建模型
model = Sequential()
model.add(Conv1D(filters=64, kernel_size=3, padding='same', activation='relu', input_shape=(maxlen, max_features)))
model.add(Conv1D(filters=64, kernel_size=3, padding='same', activation='relu'))
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(0.25))
model.add(LSTM(128, return_sequences=True))
model.add(Dropout(0.5))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(2, activation='softmax'))
# 编译模型
adam = Adam(lr=0.001)
model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])
# 打印模型摘要
model.summary()
# 训练模型
filepath="cnn-lstm-best.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
callbacks_list = [checkpoint]
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=64, callbacks=callbacks_list)
# 加载最佳模型
model.load_weights("cnn-lstm-best.hdf5")
# 评估模型
score, acc = model.evaluate(X_test, y_test, verbose=0)
print('Test score:', score)
print('Test accuracy:', acc)
```
注意,这只是一个简单的示例,实际上,你需要根据你的数据集和应用场景修改和优化模型。
阅读全文