python - 如何为机器学习方法编码我的数据?

标签 python python-3.x machine-learning scikit-learn one-hot-encoding

我想为机器学习方法编码我输入的字符串字母。让我们假设我的火车数据是这样的:

  score     text
    1   show photos
    1   show my photos
    2   who are you?

目前我在做这样的事情:

for index, row in train_set.iterrows():

    list2 = []

    list2 = list(row.text.lower())

    for n, key in enumerate(list2):

        if key in dictionary:

            list2[n] = dictionary[key]

        else:

            dictionary[key] = i
            list2[n] = i
            i += 1

    train_set.set_value(index,'text', list2)

作为这个示例数据的结果,我得到:

  score                 text
    1    [0, 1, 2, 3, 4, 5, 1, 2, 6, 2, 0]
    1    [0, 1, 2, 3, 4, 7, 8, 4, 5, 1, 2, 6, 2, 0]
    2    [3, 1, 2, 4, 10, 13, 9, 4, 8, 2, 19, 21]

如您所知,例如对于神经网络,使用这些值并不是一种正确的方法,因此在我看来,在这种情况下,单一热编码将是最佳解决方案。我想知道在 test_set 数据框的 text 列以及 train_set< 中的 text 列中转换这些值的最有效方法是什么 数据框,它看起来像 test_set 但显然第一列没有预期值。我认为在这两种情况下,在使用一种热编码后我应该具有相同大小的列,并且相同的索引和行应该对应于 test_settrain_set 中的相同字符数据框。我希望你明白我的意思。如果没有,请告诉我。我将尝试以更清楚的方式解释它。我该怎么做?有什么想法吗?

最佳答案

一种解决方案是使用自定义 Prepper 类来编码您的训练集。当训练集被编码时,Prepper 类对象记录(单词,单热索引)对应关系。

然后您将使用相同的 Prepper 对象来编码您的测试集。

Prepper 类的粗略骨架是:

from collections import defaultdict

class Prepper(object):

   def __init__(self):
      self.vocab = defaultdict(lambda : len(self.vocab))

   def encode_train_word(self, train_word):
      return self.vocab[train_word]

   def encode_test_word(self, test_word):
      if test_word in self.vocab:
         return self.vocab[test_words]
      else:
         return -1 # index for unknown token

如果我不得不重新获取您的代码片段,它看起来像:

prepper = Prepper()

for index, row in train_set.iterrows():
   list2 = list(row.text.lower())
   encoded_list_2 = [prepper.encode_train_word(word) for word in list2]

   train_set.set_value(index, 'text', encoded_list_2)

## and for the test set

for index, row in test_set.iterrows():
   list2 = list(row.text.lower())
   encoded_list_2 = [prepper.encode_test_word(word) for word in list2]

   test_set.set_value(index, 'text', encoded_list_2)

关于python - 如何为机器学习方法编码我的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50431164/

相关文章:

python - 如何在 Pandas 中添加字符串数字

python - 由 ascii 忽略编码的 pandas csv 写入

c# - ML.NET:功能列的架构不匹配 'Features'

mysql - Mysql是否支持PMML

bash - ./build/tools/caffe : No such file or directory

python - Python : prohibit instantiation 中没有抽象方法的抽象数据类

python - Matplotlib:绘制两个 x 轴,一个是线性的,一个是对数刻度

python - 将两个 Python 脚本集成为一个?

sql-server - 如何使用 Azure 机器学习笔记本连接到 SQL Server 和 Azure SQL 数据库?

python - 在这种情况下如何获得两个字符串的交集?