【问题标题】:Scikit-Learn TfidfVectorizerScikit-Learn TfidfVectorizer
【发布时间】:2018-01-23 23:50:37
【问题描述】:

我正在研究一个文本分类问题,从 RSS 提要解析新闻报道,我怀疑许多 HTML 元素和乱码被计为标记。我知道 Beautiful Soup 提供了清理 HTML 的方法,但我想尝试传入字典以更好地控制计数的标记。

这在概念上似乎很简单,但我得到了我不明白的结果。

from sklearn.feature_extraction.text import TfidfVectorizer

eng_dictionary = []
with open("C:\\Data\\words_alpha.txt") as f:
    eng_dictionary = f.read().splitlines()

short_dic = []
short_dic.append(("short"))
short_dic.append(("story"))

stories = []
stories.append("This is a short story about the color red red red red blue blue blue i am in a car")
stories.append("This is a novel about the color blue red red red red i am in a boot")
stories.append("I like the color green, but prefer blue blue blue blue blue red red red red i am on a bike")

vec = TfidfVectorizer(decode_error=u'ignore', stop_words='english', analyzer='word', lowercase=True)
pos_vector = vec.fit_transform(stories).toarray()

print(vec.get_feature_names())

vec = TfidfVectorizer(decode_error=u'ignore', stop_words='english', analyzer='word', lowercase=True, vocabulary=short_dic)
pos_vector = vec.fit_transform(stories).toarray()

print(vec.get_feature_names())

vec = TfidfVectorizer(decode_error=u'ignore', stop_words='english', analyzer='word', lowercase=True, vocabulary=eng_dictionary)
pos_vector = vec.fit_transform(stories).toarray()

print(vec.get_feature_names())

程序的输出如下;

['bike', 'blue', 'boot', 'car', 'color', 'green', 'like', 'novel', 'prefer', 'red', 'short', 'story']
['short', 'story']
ptic', 'skeptical', 'skeptically', 'skepticalness', 'skepticism', 'skepticize', 'skepticized', 'skepticizing'...

第三次打印的输出一直持续,所以我故意将其缩短,但奇怪的是它从单词中间开始,正如我在上面显示的那样。前两个打印语句的结果对我来说很有意义;

  • 没有词汇意味着特征是直接从语料库中构建的。
  • 提供词汇表意味着特征是根据语料库和词汇表中的标记构建的

但是,第三次打印中显示的特征不是我的语料库的一部分,为什么会出现?

【问题讨论】:

    标签: python scikit-learn tf-idf


    【解决方案1】:

    “词汇表”参数将使用词汇表中的单词创建一个 TF-IDF 矩阵。然后,如果该单词存在,则将填充这些值。

    例如,假设 'color' 在您的 'words_alpha.txt' 文件中:

                  skeptical    skeptically ... ... ...      color
    stories[2]        0             0      ... ... ...   TFI-DF value
    

    这就是他们出现的原因。

    它从中间词开始的事实可能与您的文件有关。您正在使用 splitlines(),所以我的猜测是您的文件有一堆单词,达到一个限制,然后转到单词 'skeptic 中间的下一行,这就是您的词汇表 (eng_dictionary) 开始的地方

    【讨论】:

    • 我怎样才能只从现有的词汇表中提取特征?
    • 你的意思是eng_dictionary中的单词和第三个故事之间的重叠吗?还是只是第三个故事中的文字?
    • 我正在寻找 eng_dictionary 中的单词和每个故事之间的重叠
    • 为此,您需要使用story_words = story.split(sep=" ") 之类的内容来拆分故事。然后,您需要创建一个集合,该集合只是此列表和 eng_dictionary 之间的交集。像overlap = set(story_words).intersection(set(eng_dictionary)) 这样的东西应该可以工作,但我还没有测试过。然后,将该变量 overlap 作为词汇表传递,您应该一切顺利!
    猜你喜欢
    • 2014-08-22
    • 2014-11-12
    • 2019-04-03
    • 2017-05-26
    • 2015-08-30
    • 1970-01-01
    • 2016-08-16
    • 1970-01-01
    相关资源
    最近更新 更多