【问题标题】:One Hot Encoding of Array with known Classes (Python)具有已知类的数组的一种热编码(Python)
【发布时间】:2022-01-05 14:36:37
【问题描述】:

我想创建一个函数 (Python),它返回一维数组的单热编码。 目前我实现了这样的东西,但这似乎很笨重而且根本不干净:

def one_hot_encode(input_array, class_list):
    # returns a int representation of a class
    class_dict = {}
    for class_el in class_list:
        class_dict[class_el] = len(class_dict)

    for i, el in enumerate(input_array):
        if el in class_list:
            one_hot_vector = [0] * len(class_list)
            one_hot_vector[class_dict[el]] = 1
            input_array[i] = one_hot_vector
    return input_array

list_with_classes = ["A","A","B","C","A","B"]
one_hot_encode(list_with_classes, ("A", "B", "C")) # A,B,C are example classes

有没有“更好”的方法来实现这个,使用标准库或只是 numpy? (听说过 Scikit-learn 但不知道怎么用)

提前致谢

【问题讨论】:

    标签: python one-hot-encoding


    【解决方案1】:

    Scikit-learn 中有一个OneHotEncoder。不过界面和你的略有不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-17
      • 2023-03-06
      • 2018-12-17
      • 2019-07-17
      • 2018-11-04
      • 2022-06-21
      相关资源
      最近更新 更多