介绍
垃圾邮件过滤器是用于检测未经请求的和不想要消息的程序。人工智能可以用来检测垃圾信息。本文包含以下主题:
本项目使用Keras神经网络库,以tensorflow为后端。
背景
如果你对神经网络不熟悉,那就读读迈克尔·尼尔森(Michael Nielsen)的《神经网络与深度学习》(neural networks and Deep Learning)。我们的目标是建立一个可以对垃圾邮件进行分类的神经网络。为此,我使用了双向LSTM (Long - Short - Term Memory)网络。长短期记忆网络——通常被称为“LSTMs”——是一种特殊的RNN,能够学习长期依赖关系。它们是由Hochreiter & Schmidhuber公司(1997)推出的。
使用的代码
1. 准备训练和测试数据
从文件中分离训练和测试数据,并创建训练集.csv和测试集.csv,但这个csv文件不包含头。我们需要添加标题“MessageType”和“Message”。消息类型是垃圾邮件。pandas库用于读取训练和测试数据。
#Read train data
data= pd.read_csv('train.csv')
data = data[['MessageType','Message']]
data['Message'] = data['Message'].apply(lambda x: x.lower())
接下来,我们需要将信息标记为文字。Keras记号赋予程序可以用来分割单词和保存为json的单词索引,稍后在测试部分中使用。消息可以有不同的长度(例如为了保持一致,我们可以使用pad_sequences Keras函数。
max_fatures = 2000
tokenizer = Tokenizer(num_words=max_fatures)
tokenizer.fit_on_texts(data['Message'].values )
dictionary = tokenizer.word_index
# Let's save this out so we can use it later
with open('wordindex.json', 'w') as dictionary_file:
json.dump(dictionary, dictionary_file)
X = tokenizer.texts_to_sequences(data['Message'].values)
X = pad_sequences(X)
Y = pd.get_dummies(data['MessageType']).values
2。建立LSTM模型并进行训练
双向LSTM网络
我们的垃圾邮件检测神经网络的第一层是嵌入层。注意,embed_dim、lstm_out、batch_size、droupout_x变量都是超参数,它们的值在某种程度上是直观的,可以而且必须在能够获得良好结果的范围内使用。所以我对这些超参数尝试了不同的数值,并取得了很好的效果。
embed_dim = 128
lstm_out = 64
model = Sequential()
model.add(Embedding(max_fatures, embed_dim,input_length = X.shape[1]))
model.add(Bidirectional(LSTM(lstm_out)))
model.add(Dropout(0.5))
model.add(Dense(2,activation='softmax'))
model.compile(loss = 'categorical_crossentropy', optimizer='adam',metrics = ['accuracy'])
训练和验证
模型可以使用模型进行训练。在Keras库中拟合函数。
model.fit(X_train, Y_train, epochs = 10, batch_size=batch_size,callbacks=[tbCallBack])
模型精度:100%损耗:0.000026
model.save('spam_lstm_model.h5')
3.测试模型
可以使用test加载和测试已保存的模型(spam_lstm_model.h5).csv数据。
model = load_model('spam_lstm_model.h5')
可以使用model.predictfunction 进行类型预测。
ham_cnt, spam_cnt, spam_correct, ham_correct = 0, 0, 0, 0
count=0
for x in range(len(X_test)):
result = model.predict(X_test[x].reshape(1,X_test.shape[1]),batch_size=1,verbose = 2)[0]
count=count+1
if np.argmax(result) == np.argmax(Y_test[x]):
if np.argmax(Y_test[x]) == 0:
ham_correct += 1
else:
spam_correct += 1
if np.argmax(Y_test[x]) == 0:
ham_cnt += 1
else:
pam_cnt += 1
测试结果:
在测试集上得到了100%的准确率。
4.在浏览器中测试模型
Keras模型可以使用Keras .js.wordindex加载到浏览器中。json用于加载用于创建输入字向量的字索引
$.getJSON('wordindex.json', function (json) {
dict = json;
});
model = new KerasJS.Model({
filepath: 'spam_lstm_model.bin',
gpu: false
});
model
.ready()
.then(() => {
console.log('Model ready');
NProgress.done();
$('#messageText').prop('disabled', false);
$('#wordCnt').html('Words : ' + wordsCount);
})
联系客服