what
get_dummies是Pandas进行独热编码(One-Hot encode)的函数
上图的左边灰色框(python debug出来的)是python执行下述代码后的结果
dummies_Embarked = pd.get_dummies(data_train['Embarked'],prefix='Embarked')
上图的右边是一个Excel 中的Embarked列,很明显:
get_dummies 函数直白的表示就是把一个属性(Embarked)中不同类别分开并用布尔值表示出来,0(False)表示非这类。
如(上图灰框的第一行可理解为第一个实验对象):
Embarked_C、Embarked_Q、Embarked_S分别为:0 0 1
表示第一个实验对象属于属性Embarked中的S类
目的:常用于机器学习过程中,把一些类属性(如男的女的)转换成数值属性(0,1)或 (False, True) 便于后续特征的输入
使用说明
def get_dummies(data, prefix=None, dummy_na: bool = False, dtype)
- prefix(前缀):
将列名的前缀换一下,如下:
df = pd.DataFrame({'A': ['a', 'b', 'a'], 'B': ['b', 'a', 'c']})
print(df)
print(pd.get_dummies(df))
print(pd.get_dummies(df, prefix=['col1', 'col2']))
output:
A B
0 a b
1 b a
2 a c
A_a A_b B_a B_b B_c
0 True False False True False
1 False True True False False
2 True False False False True
col1_a col1_b col2_a col2_b col2_c
0 True False False True False
1 False True True False False
2 True False False False True
可以看出就是把 A、B 换成了 col1、col2
- dummy_na:
默认为False, prefixl里面出现Nan直接忽略,设置为True时将多出一列显示Nan
例子:
s = ['a', 'b', np.nan]
print(pd.get_dummies(s))
print(pd.get_dummies(s, dummy_na=True))
output:
a b
0 True False
1 False True
2 False False
a b NaN
0 True False False
1 False True False
2 False False True
- dtype :
输出的 data类型,如下:
s = ['a', 'b']
print(pd.get_dummies(s))
print(pd.get_dummies(s, dtype=float))
a b
0 True False
1 False True
a b
0 1.0 0.0
1 0.0 1.0
扩展:
sklearn里用OneHotEncoder
from sklearn.preprocessing import OneHotEncoder
# 将标签转换为独热编码
encoder = OneHotEncoder()
Y = encoder.fit_transform(Y.reshape(Y.shape[0], 1))
Y = Y.toarray().T
Y = Y.astype('uint8')
tensorflow的one_hot Encoder
one_hot(indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None)
该函数的功能主要是转换成one_hot类型的张量输出。
参数功能如下:
1)indices中的元素指示on_value的位置,不指示的地方都为off_value。indices可以是向量、矩阵。
2)depth表示输出张量的尺寸,indices中元素默认不超过(depth-1),如果超过,输出为[0,0,···,0]
3)on_value默认为1
4)off_value默认为0
5)dtype默认为tf.float32
https://www.cnblogs.com/muzidaitou/p/11262820.html
Pytorch里的one_hot Encoder
import torch
targets = torch.tensor([5, 3, 2, 1])
targets_to_one_hot = torch.nn.functional.one_hot(targets) # 默认按照targets其中的最大值+1作为one_hot编码的长度
# result:
# tensor(
# [0, 0, 0, 0, 0, 1],
# [0, 0, 0, 1, 0, 0],
# [0, 0, 1, 0, 0, 0],
# [0, 1, 0, 0, 0, 0]
#)
targets_to_one_hot = torch.nn.functional.one_hot(targets, num_classes=7) 3# 指定one_hot编码长度为7
# result:
# tensor(
# [0, 0, 0, 0, 0, 1, 0],
# [0, 0, 0, 1, 0, 0, 0],
# [0, 0, 1, 0, 0, 0, 0],
# [0, 1, 0, 0, 0, 0, 0]
#)
https://blog.csdn.net/weixin_44604887/article/details/109523281