具有多个标签的一键编码功能

时间:2019-04-17 15:20:28

标签: r autoencoder one-hot-encoding

在python中,我们可以使多个标签成为一键编码功能 示例:https://chrisalbon.com/machine_learning/preprocessing_structured_data/one-hot_encode_features_with_multiple_labels/

我有一个包含几列的数据框,最后一个是Label。

此标签是这样的列表(每行一个新行):

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

我尝试:

Label
"A"
"B"
"C"
"D"
"A,B,C"
"A,C"
"D,B,A"
"D,C,B,A"

但是我得到的是:

levels(data_Frame$Label)<-c("A","B","C","D")
New_data_Frame<-as.data.frame(decodeClassLabels(data_Frame$Label))

我想要的是:

A   B   C   D
1   0   0   0
0   1   0   0 
0   0   1   0 
0   0   0   1 
0   0   0   0 
0   0   0   0 
0   0   0   0
0   0   0   0 

1 个答案:

答案 0 :(得分:1)

一种选择是将“标签”列除以,,然后使用mtabulate

library(qdapTools)
+(mtabulate(strsplit(df1$Label, ",")) > 0) 
#     A B C D
#[1,] 1 0 0 0
#[2,] 0 1 0 0
#[3,] 0 0 1 0
#[4,] 0 0 0 1
#[5,] 1 1 1 0
#[6,] 1 0 1 0
#[7,] 1 1 0 1
#[8,] 1 1 1 1

数据

df1 <- structure(list(Label = c("A", "B", "C", "D", "A,B,C", "A,C", 
"D,B,A", "D,C,B,A")), class = "data.frame", row.names = c(NA, 
  -8L))