文本分类实战:基于SVM算法和哈工大停用词表的中文文本分类

本文将使用Python语言,结合SVM算法和哈工大停用词表,实现基于文本特征提取的中文文本分类。代码示例包括数据集加载、停用词处理、特征提取、模型训练和评估等步骤,并附带详细说明和代码解释。

数据集和环境

  • 数据集:本文使用自定义数据集 corpus,包含若干类数据。目录结构如下:
    corpus
    ├── neg
    │   └── 1.txt
    │   └── 2.txt
    │   └── ...
    └── pos
        └── 1.txt
        └── 2.txt
        └── ...
    
  • 停用词表:采用哈工大停用词表,文件名为 stopwords.txt。
  • 工具库:jieba分词库、sklearn库

代码实现

import os
import jieba
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report

# 定义停用词表
stopwords_path = 'stopwords.txt'
stopwords = set()
with open(stopwords_path, 'r', encoding='utf-8') as f:
    for line in f:
        stopwords.add(line.strip())

# 加载数据集
corpus_path = 'E:/Learning/大三下/自然语言处理/corpus'
categories = os.listdir(corpus_path)
documents = []
labels = []
for category in categories:
    category_path = os.path.join(corpus_path, category)
    for file_name in os.listdir(category_path):
        file_path = os.path.join(category_path, file_name)
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
            words = jieba.cut(content)
            words = [word for word in words if word not in stopwords]
            documents.append(' '.join(words))
            labels.append(category)

# 特征提取
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(documents)
y = labels

# 分割训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

# 训练模型
clf = SVC()
clf.fit(X_train, y_train)

# 预测测试集
y_pred = clf.predict(X_test)

# 输出评估结果
print(classification_report(y_test, y_pred))

代码解释

  1. 导入库:导入必要的库,包括 os、jieba、sklearn 等。
  2. 加载停用词表:从 stopwords.txt 文件中读取停用词,并存储在 stopwords 集合中。
  3. 加载数据集:遍历 corpus 目录下的每个类别,读取每个文件内容,并进行分词和停用词过滤,最终得到词语序列和类别标签。
  4. 特征提取:使用 TfidfVectorizer 提取文本特征,并转换为矩阵形式。
  5. 分割训练集和测试集:使用 train_test_split 将数据集分割成训练集和测试集。
  6. 训练模型:使用 SVC 算法训练文本分类模型。
  7. 预测测试集:使用训练好的模型预测测试集的类别标签。
  8. 评估结果:使用 classification_report 计算模型的评估指标,包括精确率、召回率、F1值等。

总结

本文通过代码示例,展示了使用SVM算法和哈工大停用词表实现中文文本分类的过程。该方法可以有效地对中文文本进行分类,并能根据实际情况进行调整和优化。

注意:

  • 上述代码中使用的jieba分词库和sklearn库需要提前安装。
  • 停用词表需要自己准备,可以从网上下载或自行创建。
  • 可以根据实际情况调整代码参数,例如停用词表、特征提取方法、模型参数等,以获得更好的分类效果。
文本分类实战:基于SVM算法和哈工大停用词表的中文文本分类

原文地址: https://www.cveoy.top/t/topic/ocYE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录