具有多个标签的一次性编码功能
One-Hot Encode Features With Multiple Labels
在 python 中,我们可以使用多个标签制作 One-Hot Encode 功能
示例:https://chrisalbon.com/machine_learning/preprocessing_structured_data/one-hot_encode_features_with_multiple_labels/
我有一个包含多列的数据框,最后一列是标签。
这个标签是这样的列表(每行一个新行):
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
我想要的是:
A B C D
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
1 1 1 0
1 0 1 0
1 1 0 1
1 1 1 1
一种选择是将 'Labels' 列拆分为 ,
,然后使用 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))
在 python 中,我们可以使用多个标签制作 One-Hot Encode 功能 示例:https://chrisalbon.com/machine_learning/preprocessing_structured_data/one-hot_encode_features_with_multiple_labels/
我有一个包含多列的数据框,最后一列是标签。
这个标签是这样的列表(每行一个新行):
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
我想要的是:
A B C D
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
1 1 1 0
1 0 1 0
1 1 0 1
1 1 1 1
一种选择是将 'Labels' 列拆分为 ,
,然后使用 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))