使用Python进行词袋编码及词汇表

我正在尝试在我的机器学习模型中添加新的列。如果在爬取的数据文本中发现某个特定的词,就应该创建一个数值列。为此,我创建了一个测试用的虚拟脚本。

import pandas as pd
bagOfWords = ["cool", "place"]
wordsFound = ""
mystring = "This is a cool new place"
mystring = mystring.lower()
for word in bagOfWords:
    if word in mystring:
        wordsFound = wordsFound + word + " "
print(wordsFound)
pd.get_dummies(wordsFound)

输出结果是

    cool place
0   1

这意味着有一句话标记为”0″,以及一个”cool place”的条目。这是不正确的。期望的输出应该是这样的:

    cool place
0   1    1

回答:

由于找不到任何进一步的方法,我找到了另一种解决方案。这是一种简单的直接独热编码。为此,我为每个需要的新词在数据框中添加一个新列,并直接创建编码。

vocabulary = ["achtung", "suchen"]
for word in vocabulary:
    df2[word] = 0
    for index, row in df2.iterrows():
        if word in row["title"].lower():
            df2.set_value(index, word, 1)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注