基于SVM算法的文本分类实现:Python代码示例

本文将介绍如何使用SVM算法进行文本分类,并提供基于Python的代码示例。代码使用哈工大等停用词表进行文本预处理,并利用TF-IDF特征提取方法进行特征工程,最终实现文本分类任务。

数据集准备

假设您有一个数据集corpus,其目录结构如下所示:

corpus
├── neg
│   ├── 1.txt
│   ├── 2.txt
│   └── ...
└── pos
    ├── 1.txt
    ├── 2.txt
    └── ...

该数据集包含两个类别:neg 和 pos,每个类别下有多个文本文件。

代码示例

import os
import jieba
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import SVC
from sklearn.metrics import classification_report, accuracy_score

# 1. 导入需要的库和停用词表
stopwords_path = 'stopwords.txt'
stopwords = set()
with open(stopwords_path, 'r', encoding='utf-8') as f:
    for line in f.readlines():
        stopwords.add(line.strip())

# 2. 加载数据集并进行分词
corpus_path = 'E:/Learning/大三下/自然语言处理/corpus'

categories = os.listdir(corpus_path)
texts = []
labels = []
for idx, cat in enumerate(categories):
    cat_path = os.path.join(corpus_path, cat)
    for file in os.listdir(cat_path):
        file_path = os.path.join(cat_path, file)
        with open(file_path, 'r', encoding='utf-8') as f:
            text = f.read().strip()
            words = jieba.cut(text)
            words = [word for word in words if word not in stopwords]
            texts.append(' '.join(words))
            labels.append(idx)

# 3. 提取特征并进行训练和测试
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(texts)
y = labels

clf = SVC(kernel='linear')
clf.fit(X, y)

# 测试集
test_texts = []
test_labels = []
for idx, cat in enumerate(categories):
    cat_path = os.path.join(corpus_path, cat)
    for file in os.listdir(cat_path):
        file_path = os.path.join(cat_path, file)
        with open(file_path, 'r', encoding='utf-8') as f:
            text = f.read().strip()
            words = jieba.cut(text)
            words = [word for word in words if word not in stopwords]
            test_texts.append(' '.join(words))
            test_labels.append(idx)
test_X = vectorizer.transform(test_texts)

# 预测
y_pred = clf.predict(test_X)
print(classification_report(test_labels, y_pred))
print('Accuracy:', accuracy_score(test_labels, y_pred))

**注:**以上代码仅供参考,具体实现细节可能需要根据具体情况进行调整。

代码说明

  1. 导入必要的库,包括jieba用于中文分词,sklearn库用于特征提取、模型训练和评估。
  2. 加载停用词表,并将其转换为集合类型以提高查找效率。
  3. 加载数据集并进行分词,去除停用词。
  4. 使用TfidfVectorizer提取文本特征,并使用SVM模型进行训练。
  5. 使用测试集进行预测,并计算分类指标。

总结

本文介绍了使用SVM算法进行文本分类的步骤,并提供了Python代码示例。通过使用停用词表、TF-IDF特征提取和SVM模型,我们可以有效地进行文本分类任务。

基于SVM算法的文本分类实现:Python代码示例

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

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