写一个用训练好的BP神经网络模型进行文本分类的代码
时间: 2024-02-25 13:54:39 浏览: 69
好的,以下是一个用训练好的BP神经网络模型进行文本分类的Python代码示例:
```python
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 读取数据
data = pd.read_csv('data.csv')
# 将标签编码为数字
le = LabelEncoder()
data['label'] = le.fit_transform(data['label'])
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(data['text'], data['label'], test_size=0.2, random_state=42)
# 构建词向量
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
tokenizer = Tokenizer(num_words=10000)
tokenizer.fit_on_texts(X_train)
X_train_seq = tokenizer.texts_to_sequences(X_train)
X_test_seq = tokenizer.texts_to_sequences(X_test)
X_train_pad = pad_sequences(X_train_seq, maxlen=100)
X_test_pad = pad_sequences(X_test_seq, maxlen=100)
# 构建BP神经网络模型
from keras.models import Sequential
from keras.layers import Dense, Embedding, Flatten
model = Sequential()
model.add(Embedding(input_dim=10000, output_dim=32, input_length=100))
model.add(Flatten())
model.add(Dense(units=64, activation='relu'))
model.add(Dense(units=1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# 加载训练好的模型参数
model.load_weights('model_weights.h5')
# 使用模型进行预测
y_pred = model.predict_classes(X_test_pad)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
需要注意的是,这只是一个简单的示例,实际应用中还需要根据具体情况进行调整和优化。同时,训练好的模型参数也需要保存下来,以便在实际应用中加载使用。
阅读全文