【问题标题】:How to transform the data and calculate the TFIDF value?如何转换数据并计算 TFIDF 值?
【发布时间】:2019-04-21 13:57:34
【问题描述】:

我的数据格式是: datas = {[1,2,4,6,7],[2,3],[5,6,8,3,5],[2],[93,23,4,5,11,3,5,2],...} datas 中的每个元素是一个句子,每个数字是一个单词。我想获取每个数字的 TFIDF 值。用sklearn或者其他方式怎么做?

我的代码:

from sklearn.feature_extraction.text import TfidfTransformer  
from sklearn.feature_extraction.text import CountVectorizer  
datas = {[1,2,4,6,7],[2,3],[5,6,8,3,5],[2],[93,23,4,5,11,3,5,2]}
vectorizer=CountVectorizer()

transformer = TfidfTransformer()
tfidf = transformer.fit_transform(vectorizer.fit_transform(datas))  
print(tfidf)

我的代码不起作用。错误:

Traceback (most recent call last):   File
"C:/Users/zhuowei/Desktop/OpenNE-master/OpenNE-
master/src/openne/buildTree.py", line 103, in <module>
    X = vectorizer.fit_transform(datas)   File
"C:\Users\zhuowei\Anaconda3\lib\site-
packages\sklearn\feature_extraction\text.py", line 869, in fit_transform
    self.fixed_vocabulary_)   File "C:\Users\zhuowei\Anaconda3\lib\site-
packages\sklearn\feature_extraction\text.py", line 792, in _count_vocab
    for feature in analyze(doc):   File 
"C:\Users\zhuowei\Anaconda3\lib\site-
packages\sklearn\feature_extraction\text.py", line 266, in <lambda>
    tokenize(preprocess(self.decode(doc))), stop_words)   File 
"C:\Users\zhuowei\Anaconda3\lib\site-
packages\sklearn\feature_extraction\text.py", line 232, in <lambda>
    return lambda x: strip_accents(x.lower()) 
AttributeError: 'int' object has no attribute 'lower'

【问题讨论】:

  • 您搜索了什么来解决这个问题,您发现了什么?您尝试了什么,为什么没有成功?
  • 我已经把我的代码放在上面了
  • 感谢您的代码。不过,请仍然包含完整的回溯。
  • 好的我已经添加了完整的回溯,我认为我的方式是错误的,但我不知道如何解决它
  • 不幸的是,这看起来不像是完整的回溯。此外,回溯中的str(nodes[0]) 似乎与您的问题中的任何内容都不对应。您可能应该查看有关如何创建 minimal reproducible example 的指南。

标签: python-3.x scikit-learn nlp tf-idf


【解决方案1】:

您正在使用CountVectorizer,它需要一个可迭代的字符串。比如:

datas = ['First sentence', 
         'Second sentence', ...
          ...
         'Yet another sentence']

但是您的数据是列表的列表,这就是发生错误的原因。您需要将内部列表设置为字符串,以便 CountVectorizer 工作。你可以这样做:

datas = [' '.join(map(str, x)) for x in datas]

这将导致datas 像这样:

['1 2 4 6 7', '2 3', '5 6 8 3 5', '2', '93 23 4 5 11 3 5 2']

现在此表单可供CountVectorizer 使用。但是即使那样你也不会得到正确的结果,因为默认的token_pattern in CountVectorizer

token_pattern : '(?u)\b\w\w+\b'

字符串正则表达式表示什么构成 “令牌”,仅在分析器 == 'word' 时使用。默认正则表达式选择 2 个或更多字母数字字符的标记(标点完全 忽略并始终视为标记分隔符)

为了让它将您的数字视为单词,您需要对其进行更改,以便它可以接受单个字母作为单词:

vectorizer = CountVectorizer(token_pattern=r"(?u)\b\w+\b")

那么它应该可以工作。但是现在你的数字变成了字符串

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2013-05-14
    • 2012-05-08
    • 1970-01-01
    • 2023-03-19
    • 2018-10-26
    • 1970-01-01
    相关资源
    最近更新 更多