python使用词袋模型将句子向量化,使用KNN进行文本分类

发布于:2024-03-15 ⋅ 阅读:(84) ⋅ 点赞:(0)

要使用词袋模型将句子向量化,并使用KNN进行分类,你可以使用Python的sklearn库。以下是一个简单的例子:

  1. 加载数据集
  2. 文本预处理(如分词、去除停用词等)
  3. 使用词袋模型进行向量化
  4. 使用KNN进行训练和分类

首先,确保你已经安装了sklearnnltk库。如果没有,请使用pip安装:

pip install sklearn nltk

接下来是代码示例:

import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

# 示例数据
sentences = [
    "我喜欢吃苹果",
    "苹果很好吃",
    "我不喜欢吃香蕉",
    "香蕉很甜",
    "我喜欢吃橙子",
    "橙子很酸"
]
labels = [0, 0, 1, 1, 2, 2]  # 假设0代表苹果,1代表香蕉,2代表橙子

# 文本预处理:分词、去除停用词
nltk.download('punkt')  # 如果还没下载punkt tokenizer的话,需要首先下载
nltk.download('stopwords')  # 如果还没下载停用词的话,需要首先下载
stop_words = set(stopwords.words('chinese'))  # 对于中文,你可能需要自定义停用词列表

def preprocess(sentence):
    words = word_tokenize(sentence)
    words = [word for word in words if word not in stop_words]
    return ' '.join(words)

processed_sentences = [preprocess(sentence) for sentence in sentences]

# 使用词袋模型进行向量化
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(processed_sentences)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, labels, test_size=0.2, random_state=42)

# 使用KNN进行分类
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train.toarray(), y_train)

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

# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")

注意:这个例子是基于假设你已经知道每个类别的标签。在实际应用中,你可能需要使用有监督学习来训练模型,并使用交叉验证来评估模型的性能。此外,对于中文文本,你可能需要使用专门的中文分词器和停用词列表。

此外,词袋模型不考虑词的顺序和上下文,所以它可能不适合所有类型的文本分类任务。在某些情况下,使用更复杂的模型(如TF-IDF、word2vec或BERT等)可能会获得更好的结果。


网站公告

今日签到

点亮在社区的每一天
去签到