[FIXED] one hot encoding function

Issue

I need to create a function that takes two integer numbers x and N, where N > x and returns a vector of dimension N with all zeros with the exception of component x, in which it has a 1.

I managed to do it in the following way,

Function=function(x,N){
  vec=rep(0,N)
  r=as.integer(x)
  vec[r]=1
  return(vec)
}

but it is incredibly slow when I need to iterate the process and apply it to a large number of realizations. On the other hand, a friend of mine is able to do the same thing with a single function of python (I think "OneHotEncoder") and it's super fast.

I was wondering if there are functions in R that are suited for this purpose.


Solution

Along the lines of what @Axeman said, you should think of whether you could find the one-hot-encoding in a vectorized way, i.e., something like that

set.seed(1234)
x = sample.int(5, size=10, replace=TRUE)
x
#  [1] 1 4 4 4 5 4 1 2 4 3

nC = max(x) #could be also larger (user-defined)
nR = length(x)
matrix(`[<-`(integer(nR * nC),(seq.int(nR) - 1) * nC + x, 1),
       nR, nC, byrow=TRUE)
#       [,1] [,2] [,3] [,4] [,5]
#  [1,]    1    0    0    0    0
#  [2,]    0    0    0    1    0
#  [3,]    0    0    0    1    0
#  [4,]    0    0    0    1    0
#  [5,]    0    0    0    0    1
#  [6,]    0    0    0    1    0
#  [7,]    1    0    0    0    0
#  [8,]    0    1    0    0    0
#  [9,]    0    0    0    1    0
# [10,]    0    0    1    0    0

Compare model.matrix approach to approach given above:

#longer input vector
x = sample.int(5, size=1e4, replace=TRUE)

oneHotMtx = function(x) {
  nC = max(x) #could be also larger (user-defined)
  nR = length(x)
  matrix(`[<-`(integer(nR * nC),(seq.int(nR) - 1) * nC + x, 1),
         nR, nC, byrow=TRUE)
}

oneHotMdl = function(x) {
  xf = factor(x)
  model.matrix(~xf+0)
}

oneHotMdl2=function(x) {
  #version without factor conversion
  model.matrix(~x+0)
}

xf = factor(x)
library(microbenchmark)
microbenchmark(oneHotMtx(x),
               oneHotMdl(x),
               oneHotMdl2(xf), times=1e3)

#Unit: microseconds
#          expr      min       lq      mean    median       uq        max neval cld
#  oneHotMtx(x)  386.621  412.510  678.2977  416.4625  435.382   5394.265  1000 a  
#  oneHotMdl(x) 7363.481 7528.230 8823.8435 7629.8850 7851.019 261808.302  1000   c
#oneHotMdl2(xf) 4253.366 4377.784 5059.0979 4471.5315 4638.637 257106.400  1000  b 


Answered By - cryo111
Answer Checked By - Clifford M. (Python.Easybugfix Volunteer)

Related Posts

Post a Comment