一个热门编码函数

时间:2018-05-15 13:04:04

标签: r one-hot-encoding

我需要创建一个带有两个整数xN的函数,其中N > x并返回一个维度N的向量,其中包含全零,但组件x,其中包含1

我设法按以下方式进行,

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

但是当我需要迭代过程并将其应用于大量实现时,它非常慢。另一方面,我的一个朋友可以使用python的一个功能(我认为" OneHotEncoder")做同样的事情,并且它超级快。

我想知道R中是否有适合此目的的功能。

3 个答案:

答案 0 :(得分:7)

按照@Axeman的说法,您应该考虑是否可以以矢量化的方式找到单热编码,即类似的东西

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

model.matrix方法与上面给出的方法进行比较:

#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 

答案 1 :(得分:6)

尝试

one_hot_encoder <- function(x, N) {
  vec <- integer(N)
  vec[x] <- 1L
  return(vec)
}

答案 2 :(得分:1)

@ cryo111答案的一点点细节:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div  id='clone'>
    <div class="form-group">
    <label for="exampleInputEmail1">Start Time</label>
    <input type="text" name="start_time" id="start_time" class="form-control start_time" readonly="readonly"  value="" placeholder="Start Time">
    </div>
    </div>
    
    <div id="box-footer">                        
    <button type="button"  class="btn btn-success" name="add_period_break"  id="add_period_break"><i class="glyphicon glyphicon-plus"></i> Add Periods/ Breaks</button>
    <button type="submit" class="btn btn-primary"> Submit</button>
    </div>