gpt4 book ai didi

python - 指定分类特征列的形状?

转载 作者:行者123 更新时间:2023-11-28 20:57:34 25 4
gpt4 key购买 nike

我知道我可以使用 categorical_column_with_identity将分类特征转化为一系列单热特征。

例如,如果我的词汇表是["ON", "OFF", "UNKNOWN"]:
“关闭” -> [0, 1, 0]

categorical_column = tf.feature_column.categorical_column_with_identity('column_name', num_buckets=3)
feature_column = tf.feature_column.indicator_column(categorical_column))

但是,我实际上有一个一维的分类特征数组。我想把它变成一个二维系列的单热特征:

[“关闭”、“打开”、“关闭”、“未知”、“打开”]
-
[[0, 1, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0]]

与所有其他功能列不同,categorical_column_with_identity 上似乎没有shape 属性,而且我没有通过 Google 或文档找到任何帮助。

我是否必须放弃 categorical_column_with_identity 并通过 numerical_column 自己创建二维数组?

最佳答案

根据评论,我不确定 tensorflow 能否实现此功能。但是对于 Pandas,您可以通过 pd.get_dummies 获得一个简单的解决方案。 :

import pandas as pd

L = ['OFF', 'ON', 'OFF', 'UNKNOWN', 'ON']

res = pd.get_dummies(L)

print(res)

OFF ON UNKNOWN
0 1 0 0
1 0 1 0
2 1 0 0
3 0 0 1
4 0 1 0

为了性能,或者如果你只需要一个 NumPy 数组,你可以使用 LabelBinarizer来自 sklearn.preprocessing:

from sklearn.preprocessing import LabelBinarizer

LB = LabelBinarizer()

res = LB.fit_transform(L)

print(res)

array([[1, 0, 0],
[0, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 0]])

关于python - 指定分类特征列的形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52785019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com