首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用于文本聚类分析的tf-idf

用于文本聚类分析的tf-idf
EN

Stack Overflow用户
提问于 2020-05-12 01:05:17
回答 1查看 64关注 0票数 1

我想对数据帧中的列df['Texts']中包含的小文本进行分组。下面是一个要分析的句子示例:

代码语言:javascript
复制
    Texts

  1 Donald Trump, Donald Trump news, Trump bleach, Trump injected bleach, bleach coronavirus.
  2 Thank you Janey.......laughing so much at this........you have saved my sanity in these mad times. Only bleach Trump is using is on his heed ?
  3 His more uncharitable critics said Trump had suggested that Americans drink bleach. Trump responded that he was being sarcastic.
  4 Outcry after Trump suggests injecting disinfectant as treatment.
  5 Trump Suggested 'Injecting' Disinfectant to Cure Coronavirus?
  6 The study also showed that bleach and isopropyl alcohol killed the virus in saliva or respiratory fluids in a matter of minutes.

因为我知道TF-IDF对集群很有用,所以我一直在使用以下代码行(通过遵循社区中之前的一些问题):

代码语言:javascript
复制
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
import re
import string

def preprocessing(line):
    line = line.lower()
    line = re.sub(r"[{}]".format(string.punctuation), " ", line)
    return line

tfidf_vectorizer = TfidfVectorizer(preprocessor=preprocessing)
tfidf = tfidf_vectorizer.fit_transform(all_text)

kmeans = KMeans(n_clusters=2).fit(tfidf) # the number of clusters could be manually changed

但是,由于我考虑的是来自dataframe的列,所以我不知道如何应用上述函数。你能帮我拿一下吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-12 01:29:37

代码语言:javascript
复制
def preprocessing(line):
    line = line.lower()
    line = re.sub(r"[{}]".format(string.punctuation), " ", line)
    return line

tfidf_vectorizer = TfidfVectorizer(preprocessor=preprocessing)
tfidf = tfidf_vectorizer.fit_transform(df['Texts'])

kmeans = KMeans(n_clusters=2).fit(tfidf)

你只需要用你的df替换all_text即可。最好先构建一个管道,然后同时应用向量化器和Kmeans。

此外,为了获得更精确的结果,对文本进行更多的预处理也不是一个坏主意。此外,我不认为降低文本是一个好主意,因为你很自然地删除了写作风格的一个好特征(如果我们认为你想要找到作者或将作者分配到一个组中),但为了获得句子的情感,是的,最好是降低。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61735218

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档