【问题标题】:Does it make sense to use both countvectorizer and tfidfvectorizer as feature vectors for text clustering with KMeans?使用 countvectorizer 和 tfidfvectorizer 作为 KMeans 文本聚类的特征向量是否有意义?
【发布时间】:2015-02-14 06:07:59
【问题描述】:

我正在尝试从包含大约 1000 个 cmets 的 csv 文件中构建我的特征向量。我的特征向量之一是使用 scikit learn 的 tfidf 矢量化器的 tfidf。也使用计数作为特征向量是否有意义,或者我应该使用更好的特征向量吗?

如果我最终使用 Countvectorizer 和 tfidfvectorizer 作为我的功能,我应该如何将它们都放入我的 Kmeans 模型(特别是 km.fit() 部分)?目前我只能将 tfidf 特征向量拟合到模型中。

这是我的代码:

vectorizer=TfidfVectorizer(min_df=1, max_df=0.9, stop_words='english', decode_error='ignore')
vectorized=vectorizer.fit_transform(sentence_list)

#count_vectorizer=CountVectorizer(min_df=1, max_df=0.9, stop_words='english', decode_error='ignore')
#count_vectorized=count_vectorizerfit_transform(sentence_list)

km=KMeans(n_clusters=num_clusters, init='k-means++',n_init=10, verbose=1)
km.fit(vectorized)

【问题讨论】:

    标签: python machine-learning scipy scikit-learn feature-extraction


    【解决方案1】:

    本质上,您所做的是找到文本文档的数字表示(特征工程)。在某些问题中,计数效果更好,而在其他一些问题中,tfidf 表示是最佳选择。你真的应该尝试它们。虽然这两种表示非常相似,因此携带的信息大致相同,但通过使用完整的特征集(tfidf+counts),您可能会获得更好的精度。通过在这个特征空间中搜索,有可能更接近真实模型。

    这是您可以水平堆叠功能的方式:

    import scipy.sparse
    
    X = scipy.sparse.hstack([vectorized, count_vectorized])
    

    那么你可以这样做:

    model.fit(X, y)  # y is optional in some models
    

    【讨论】:

    • 实际上,我收到了错误'y' is not defined。当我尝试时:X,y = scipy.sparse.hstack([vectorized, count_vectorized]) 我得到错误:TypeError: 'coo_matrix' object has no attribute '__getitem__'
    • hstack的结果应该分配给X而不是X,y
    • 如果模型是 KMeans,则不需要 y。抱歉,我的示例代码具有误导性。
    • 应该改为X = scipy.sparse.hstack([vectorized, count_vectorized]) 吗? #缺少方括号?
    猜你喜欢
    • 2019-11-19
    • 2017-02-21
    • 2015-02-26
    • 2019-08-05
    • 2018-09-19
    • 2014-07-23
    • 2019-12-01
    • 2019-08-01
    • 2015-07-26
    相关资源
    最近更新 更多