溫馨提示×

Scikit-learn中怎么實現文本聚類

小億
132
2024-05-10 18:24:58
欄目: 編程語言

在Scikit-learn中,可以使用TfidfVectorizer和KMeans來實現文本聚類。以下是一個簡單的示例代碼:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans

# 文本數據
documents = [
    'This is the first document.',
    'This document is the second document.',
    'And this is the third one.',
    'Is this the first document?',
]

# 使用TfidfVectorizer將文本轉換成TF-IDF特征
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(documents)

# 使用KMeans進行聚類
kmeans = KMeans(n_clusters=2)
kmeans.fit(X)

# 輸出聚類結果
clusters = kmeans.labels_
for i, text in enumerate(documents):
    print(f"Document '{text}' belongs to cluster {clusters[i]}")

在上面的代碼中,首先使用TfidfVectorizer將文本數據轉換成TF-IDF特征,然后使用KMeans進行聚類,最后輸出每個文檔所屬的聚類??梢愿鶕嶋H情況調整聚類的數量和其他參數來獲取更好的聚類效果。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女