简答
这是一个在不使用 numpy、pandas 或其他包的情况下进行one-hot-encoding 的函数。它需要一个整数、布尔值或字符串(可能还有其他类型)的列表。
import typing
def one_hot_encode(items: list) -> typing.List[list]:
results = []
# find the unique items (we want to unique items b/c duplicate items will have the same encoding)
unique_items = list(set(items))
# sort the unique items
sorted_items = sorted(unique_items)
# find how long the list of each item should be
max_index = len(unique_items)
for item in items:
# create a list of zeros the appropriate length
one_hot_encoded_result = [0 for i in range(0, max_index)]
# find the index of the item
one_hot_index = sorted_items.index(item)
# change the zero at the index from the previous line to a one
one_hot_encoded_result[one_hot_index] = 1
# add the result
results.append(one_hot_encoded_result)
return results
例子:
one_hot_encode([2, 1, 1, 2, 5, 3])
# [[0, 1, 0, 0],
# [1, 0, 0, 0],
# [1, 0, 0, 0],
# [0, 1, 0, 0],
# [0, 0, 0, 1],
# [0, 0, 1, 0]]
one_hot_encode([True, False, True])
# [[0, 1], [1, 0], [0, 1]]
one_hot_encode(['a', 'b', 'c', 'a', 'e'])
# [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 0, 1]]
长(呃)答案
我知道这个问题已经有很多答案了,但我注意到了两件事。首先,大多数答案都使用像 numpy 和/或 pandas 这样的包。这是一件好事。如果您正在编写生产代码,您可能应该使用像 numpy/pandas 包中提供的健壮、快速的算法。但是,为了教育起见,我认为应该有人提供一个具有透明算法的答案,而不仅仅是别人算法的实现。其次,我注意到许多答案没有提供单热编码的稳健实现,因为它们不满足以下要求之一。以下是有用、准确和健壮的 one-hot 编码功能的一些要求(如我所见):
one-hot 编码函数必须:
- 处理各种类型的列表(例如整数、字符串、浮点数等)作为输入
- 处理具有重复项的输入列表
- 返回对应于输入的列表列表(以相同的顺序)
- 返回列表列表,其中每个列表尽可能短
我测试了这个问题的许多答案,其中大多数都未能满足上述要求之一。