将数字编码为分类向量

时间:2018-10-23 17:03:06

标签: r list one-hot-encoding

我有一个整数y <- c(1, 2, 3, 3)的向量,现在我想将其转换成这样的列表(一个热编码):

1 0 0 
0 1 0
0 0 1
0 0 1

我试图找到一个to_categorical的解决方案,但是我在数据类型方面遇到了问题...有人知道该任务的智能而又平滑的解决方案吗?

这是我的尝试:

 for (i in 1:length(y)) {
  one_character <- list(as.vector(to_categorical(y[[i]], num_classes = 3)))
  list_test <- rbind(list_test, one_character)
  }

但出现以下错误:

Error in py_call_impl(callable, dots$args, dots$keywords) : 
  IndexError: index 3 is out of bounds for axis 1 with size 3

4 个答案:

答案 0 :(得分:5)

这是base R中的一种方式。创建一个matrix为0的值,并根据行序列和y值将1分配为列索引

m1 <- matrix(0, length(y), max(y))
m1[cbind(seq_along(y), y)] <- 1
m1
#      [,1] [,2] [,3]
#[1,]    1    0    0
#[2,]    0    1    0
#[3,]    0    0    1
#[4,]    0    0    1

base R中,我们也可以这样做

table(seq_along(y), y)
#  y
#    1 2 3
#  1 1 0 0
#  2 0 1 0
#  3 0 0 1
#  4 0 0 1

或者另一个选择是model.frame中的base R

model.matrix(~factor(y) - 1)

答案 1 :(得分:3)

为简单起见,我更喜欢@akrun的答案,但有一些选择:

数据:

dat <- data.frame(y=c(1,2,3,3))
dat$id <- seq_len(nrow(dat))
dat$one <- 1L

添加了“ id”字段,以使行分开/唯一。由于我正在重塑数据,因此需要保留一个值,因此临时变量为“ one”。

基本R

dat_base <- reshape(dat, idvar="id", v.names="one", timevar="y", direction="wide")
dat_base[2:4] <- lapply(dat_base[2:4], function(a) replace(a, is.na(a), 0))
dat_base
#   id one.1 one.2 one.3
# 1  1     1     0     0
# 2  2     0     1     0
# 3  3     0     0     1
# 4  4     0     0     1

dplyr

library(dplyr)
library(tidyr)
dat %>%
  spread(y, one) %>%
  mutate_all(~if_else(is.na(.), 0L, .))
#   id 1 2 3
# 1  1 1 0 0
# 2  2 0 1 0
# 3  3 0 0 1
# 4  4 0 0 1

data.table

library(data.table)
datdt <- as.data.table(dat)
dcast(datdt, id ~ y, value.var = "one", fill = 0)
#    id 1 2 3
# 1:  1 1 0 0
# 2:  2 0 1 0
# 3:  3 0 0 1
# 4:  4 0 0 1

答案 2 :(得分:2)

带有mltoolsdata.table的单线:

one_hot(as.data.table(as.factor(y)))
   V1_1 V1_2 V1_3
1:    1    0    0
2:    0    1    0
3:    0    0    1
4:    0    0    1

答案 3 :(得分:1)

还提供了splitstackshape软件包。

y <- c(1, 2, 3, 3)
splitstackshape:::numMat(y, fill = 0L)
#     1 2 3
#[1,] 1 0 0
#[2,] 0 1 0
#[3,] 0 0 1
#[4,] 0 0 1
相关问题