在最后一篇博客中,我们介绍了如何使用几个深度学习模型对中文文本进行情感分类,这是非常详细的。在这里,我只是重复与上一篇博客相同的内容。感兴趣的朋友可以点击查看。
轻松搞懂word2vec BiLSTM、TextCNN、CNN BiLSTM、BiLSTM Attention实现中英文情感分类 【TF-IDF、word2vec、svm、cnn、textcnn、bilstm、cnn bilstm、bilstm attention】英文长文分类实战
在本博客中,我将详细介绍如何使用常见的机器学习模型——支持向量机来分类文本情感。
从最初的数据集准备到训练word2vec所有的模型都和上一篇博客一样,这里就不重复了。
在此之前,我们已经训练好了word2vec模型可以通过word2vec得到单词的对应向量,但数据集的标记是针对整个句子的标记,所以我们需要做的是通过单词向量得到句向量。
如果想将word2vec换成fastText,只需要将 from gensim.models.word2vec import Word2Vec 换成 from gensim.models.fasttext import FastText 对应位置Word2Vec换成FastText即可。
在这里,我们使用的是寻求平均的方法,即通过添加句子中的单词向量,然后除以单词的数量来获得句子的特征。这种方法简单易行,但不可避免地忽略了句子的语序信息。(但效果并不一定相对较差)
# 直接词向量相加的求平均值 def fea_sentence(list_w): n0 = np.array([0. for i in range(vocab_dim)], dtype=np.float32) for i in list_w: n0 = i fe = n0 / len(list_w) fe = fe.tolist() return fe def parse_dataset(x_data, word2vec): xVec = [] for x in x_data: sentence = [] for word in x: if word in word2vec: sentence.append(word2vec[word]) else: # 如果单词不存在,则补零向量。 sentence.append([0. for i in range(vocab_dim)]) xVec.append(fea_sentence(sentence)) xVec = np.array(xVec)
return xVec
注意,这里是跟上一篇博客不同的,标签不需要转换成one-hot的格式。
from sklearn.model_selection import train_test_split
def get_data(word2vec, data, y):
data = parse_dataset(data, word2vec)
x_train, x_test, y_train, y_test = train_test_split(data, y, test_size=0.2, random_state=5)
return x_train, y_train, x_test, y_test
得到句特征之后,我们就可以开始训练模型啦,那在这里,我们用到了GridSearchCV(网格搜索)的方法,帮助我们进行调参。
由于数据集较大,训练时间可能会非常长,没有时间的朋友可以直接将前六行代码注释掉,将下面注释掉的代码恢复。
def train_svm(x_train, y_train):
svc = svm.SVC(verbose=True)
parameters = {
'C':[1, 2], 'gamma':[0.5 ,1, 2]}
clf = GridSearchCV(svc, parameters, scoring='f1')
clf.fit(x_train, y_train, )
print('最佳参数: ')
print(clf.best_params_)
# clf = svm.SVC(kernel='rbf', C=2, gamma=2, verbose=True)
# clf.fit(x_train,y_train)
# 封装模型
print('保存模型...')
joblib.dump(clf, 'svm.pkl')
import joblib
from sklearn.metrics import classification_report
if __name__ == '__main__':
svm = joblib.load('svm.pkl')
y_pred = svm.predict(x_test)
# target_names = ['负面', '正面']
print(classification_report(y_test, y_pred))

“智能”推荐: 轻松搞懂word2vec+BiLSTM、TextCNN、CNN+BiLSTM、BiLSTM+Attention实现中英文情感分类 【TF-IDF、word2vec、svm、cnn、textcnn、bilstm、cnn+bilstm、bilstm+attention】英文长文本分类实战
代码下载链接,有需要的请自行提取,不想hua前的朋友,可评论同我说,我会回复你,但可能会比较慢。祝好!
https://download.csdn.net/download/qq_44186838/60890812