【问题标题】:How to convert Countvectorized data back to text data in Python?如何在 Python 中将 Countvectorized 数据转换回文本数据?
【发布时间】:2018-04-17 14:25:23
【问题描述】:

如何将计数矢量化文本数据转换回文本形式。我有文本数据,我使用 countvectorizer 将其制成稀疏矩阵进行分类。现在我希望将文本数据的稀疏矩阵转换回文本数据。

我的代码

 cv = CountVectorizer( max_features = 500,analyzer='word') 
    cv_addr = cv.fit_transform(data.pop('Clean_addr'))

    for i, col in enumerate(cv.get_feature_names()):
        data[col] = pd.SparseSeries(cv_addr[:, i].toarray().ravel(), fill_value=0)

【问题讨论】:

  • 您想要返回原始文本?这是不可能的,向量空间表示会丢失所有位置信息。没有办法区分“狗吃了猫”和“猫吃了狗”和“吃了狗猫”
  • @juanpa.arrivillaga,我已经使用地址文本数据和其他一些数字数据列进行了地址分类。现在我已经将它们分类为基本的两类(商业和住宅)。我怎样才能理解哪些是正确分类的,哪些没有分类。Sklearn 不接受文本数据作为决策树
  • 很抱歉,但这听起来与您的问题完全无关...?究竟是什么问题?您正在处理带标签的数据,不是吗?
  • @juanpa.arrivillaga,我如何知道哪些记录被正确分类,哪些记录没有被正确分类。我已将数据集拆分为测试和训练。这些数据集仅包含数值。
  • 是的。但是你有标签,不是吗?

标签: python pandas scikit-learn sklearn-pandas


【解决方案1】:

我认为不可能 - 所有标点符号、空格、制表符都已删除。此外,所有单词都已转换为小写。 AFAIK 无法将其恢复为原始格式。所以你最好保留Clean_addr 列而不是删除它。

演示:

In [18]: df
Out[18]:
                                         txt
0                              a sample text
1  to be, or not to be, that is the question

In [19]: from sklearn.feature_extraction.text import CountVectorizer

In [20]: cv = CountVectorizer(max_features = 500, analyzer='word')

In [21]: cv_addr = cv.fit_transform(df['txt'])

In [22]: x = pd.SparseDataFrame(cv_addr, columns=cv.get_feature_names(), 
                                index=df.index, default_fill_value=0)

In [23]: x
Out[23]:
   be  is  not  or  question  sample  text  that  the  to
0   0   0    0   0         0       1     1     0    0   0
1   2   1    1   1         1       0     0     1    1   2

In [24]: df.join(x)
Out[24]:
                                         txt  be  is  not  or  question  sample  text  that  the  to
0                              a sample text   0   0    0   0         0       1     1     0    0   0
1  to be, or not to be, that is the question   2   1    1   1         1       0     0     1    1   2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-27
    • 2018-08-01
    • 2022-11-28
    • 2022-07-13
    • 2017-02-19
    相关资源
    最近更新 更多