April 2019
 
 
by @mw

The fastest density estimation in R

There are many packages dealing with density estimation in R. They offer several advantages over manually coded algorithms, including bandwidth-selection procedures or involving some more complex features of density estimation, like derivative estimation or higher order kernels. Some of them are also coded in native C language, which should speed up the calculations and enhance memory management. Nevertheless, many of these extra features may be often unused in simple applications of density estimations. That leaves the question open: which algorithm is the fastest?

I try to look at the broadest possible set of R packages dealing with density estimation, including
np
,
kdensity
,
sm
and
GenKern
. There are some other packages which I skip here, as I wanted to make sure I estimate the density at a given point, and not across the domain, to make the numbers comparable. (As a side comment, package
GenKern
seems to have some scaling problems depending on the sample size, but given that the scaling factor is a multiple of 10, I include the package in the comparison). To finally compare the results, I write two functions to perform density estimation. The first one utilizes a standard
for
loop, and the second one offers a vectorized solution. In theory, the vectorized program should have quite good performance. To compare the solutions I use the package
microbenchmark
, which executes the codes multiple times in a random order, and compares the aggregate results.

Although there is a wide literature on density estimation, the technical implementation is quite simple. For more information and technicalities behind the method, I refer you to the set of lecture notes of Bruce Hansen, which offer a great introduction to the topic [LINK]. Given sample $\{X_i: i=1,...,n\}$, where $n$ is the sample size, and a regular kernel function $K$, which typically is a probability density function, one can estimate the density at point $x$ as

$$ f↖{∧}(x) = {1}/{n h} ∑↙{i=1}↖n K({x-X_i}/h). $$

Here, the parameter $h$ is the so-called bandwidth, which controls the amount of smoothing of the estimator. It is usually data-driven and converges to 0 as the sample size tends to infinity. For the experiment I take the same bandwidth parameter for all the estimators.

The strategy is simple. I would like to generate a sample of size 10,000 from a standard normal distribution, and estimate the density at point 1.25 using different algorithms. As emphasized above, I will utilize overall 6 different functions:

  • K.dens - a simple function to sum over the realizations of $X_i$
  • K.vdens - a vectorized version of K.dens
  • npudens from the package
    np
  • kde from the package
    kdensity
  • sm.density from the package
    sm
  • KernSec from the package
    GenKern

The plug-in code to reproduce the results is given below.

#load necessary packages
require(ks)
require(np)
require(kdensity)
require(sm)
require(GenKern)
require(microbenchmark)
 
#non-vectorized density estimates
K.dens = function(x, H, p) {
  x = as.matrix(x)
  H = as.matrix(H)
  n = length(x[,1])
  d = length(x[1,])
 
  dens = 0
  for(i in 1:n) {
    dens = dens + exp( -1/2 * t(p-x[i,]) %*% solve(H) %*% (p-x[i,]) )
  }
 
  return( dens / det(sqrt(H)) / (2*pi)^(d/2) / n )
}
 
#vectorized density estimates
K.vdens = function(x, H, p) {
  x = as.matrix(x)
  H = as.matrix(H)
  d = length(x[1,])
 
  if(d == 1) {
    u = (p - x)/sqrt(H[1,1])
    return( mean( dnorm( u ) / sqrt(H[1,1]) ) )
  }
  if(d > 1)  {
    u = sweep(sweep(x,2,p),2,sqrt(diag(H)),"/")
    return( mean( apply(sapply(1:d, FUN = function(i) dnorm( (p[i] - x[,i])/sqrt(H[i,i]) )/sqrt(H[i,i]) ), 1, FUN = prod) ) )
  }
}
 
#simulation setup
vector <- rnorm(10000, 0, 1)
point  <- c(1.25)
h      <- hns(vector)
H      <- h^2
 
#check if the values are the same
K.dens(x = vector, H = H, p = point)
K.vdens(x = vector, H = H, p = point)
npudens(bws = h, tdat = vector, edat = point)\$dens
kde(vector, h = h, eval.points = point)\$estimate
sm.density(vector, h, eval.points = point)\$estimate
KernSec(vector, xbandwidth = h, range.x=point )\$yden
#compare the performance      
ts <- microbenchmark(K.dens(x = vector, H = H, p = point),
               K.vdens(x = vector, H = H, p = point),
               npudens(bws = h, tdat = vector, edat = point)\$dens,
               kde(vector, h = h, eval.points = point)\$estimate,
               sm.density(vector, h, eval.points = point)\$estimate,
               KernSec(vector, xbandwidth = h, range.x=point )\$yden)
 
boxplot(ts)

The codes generates a plot with time performance for each of the selected functions, probably similar to the graph below.

Candlestick chart As it can be observed, the kde function from
kdensity
package is the best but the vectorized version of the simple estimator seems to be nearly as good. Interestingly, the most advanced in my opinion
np
is somewhat slower, but this is a result of an extra functionality and probably many consistency checks and verifications along the lines. It may well be that the performance of these functions differs if $X$ vector has more dimensions, but this is a topic to be investigated in the next post.

Comments

2 weeks ago
 
http://mewkid.net/buy-amoxicillin/ - Amoxicillin <a href="http://mewkid.net/buy-amoxicillin/">Amoxicillin 500mg</a> agq.bviq.marcinwolski.org.qga.xg http://mewkid.net/buy-amoxicillin/

yesterday
 
<a href="http://canadianorderpharmacy.com/#">canadianorderpharmacy.com</a> pharmacy canada canadian pharmacy uk delivery <a href=http://canadianorderpharmacy.com/#>http://canadianorderpharmacy.com/</a> canadian drugs http://canadianorderpharmacy.com/#generic-for-viagra <a href="http://test-automation-pp-03062014-222212.com/__media__/js/netsoltrademark.php?d=http://canadianorderpharmacy.com/#">canada drugs</a> <a href="http://ug-gsm.com/bitrix/rk.php?goto=http://canadianorderpharmacy.com/#">canadian online pharmacies</a>

3 hrs ago
 
<a href="http://canadianpharmacyies.com/#">pharmacy uk</a> canadian pharmacy cialis <a href="http://canadianpharmacyies.com/#">canadianpharmacyies.com</a> online pharmacy <a href=http://canadianpharmacyies.com/#>http://canadianpharmacyies.com/</a> online pharmacies in usa http://canadianpharmacyies.com/ <a href=http://canadianpharmacyies.com/#>canada pharmacies</a> п»їhttp://iluvglhec.biz/__media__/js/netsoltrademark.php?d=canadianpharmacyies.com <a href="http://letsdetox.com/__media__/js/netsoltrademark.php?d=canadianpharmacyies.com#">canadian pharmacies without an rx</a> http://stroyeffect.ru/bitrix/rk.php?goto=canadianpharmacyies.com <a href="http://avtoremont48.ru/bitrix/redirect.php?event1=&event2=&event3=&goto=http://canadianpharmacyies.com/#">canadian pharmacy world</a> <a href="https://forum.tourcrackers.com/member.php?u=76837-DeloresScu">pharmacy onesource</a> http://forum.arrow-bax.ir/member.php?u=1049-JodiSpruil

2 hrs ago
 
http://hotscrunch.com/__media__/js/netsoltrademark.php?d=eddrugsgeneric.com <a href="http://filmsmediagroup.net/__media__/js/netsoltrademark.php?d=https://eddrugsgeneric.com#">erectile pills over the counter</a> <a href="http://aveailetisimhizmetleri.com/__media__/js/netsoltrademark.php?d=https://eddrugsgeneric.com#">herbs for erectile dysfunction</a> <a href="http://stanfordhealthplan.com/__media__/js/netsoltrademark.php?d=https://eddrugsgeneric.com#">solutions to erectile dysfunction</a> <a href="http://free2013.com/__media__/js/netsoltrademark.php?d=https://eddrugsgeneric.com#">best erectile dysfunction drug</a> http://xn--80adbgeb5bshcrcgfp8r.xn--p1ai/bitrix/redirect.php?event1=&event2=&event3=&goto=https://eddrugsgeneric.com/ <a href="http://taimyr24.ru/bitrix/redirect.php?event1=&event2=&event3=&goto=https://https://eddrugsgeneric.com/#">best erectile dysfunction medication</a> <a href="http://tekys.ru/bitrix/redirect.php?event1=&event2=&event3=&goto=https://https://eddrugsgeneric.com/#">buy erectile dysfunction pills</a> <a href="http://dance-art-project.ru/bitrix/rk.php?goto=https://https://eddrugsgeneric.com/#">erectile enhancement pills</a> <a href="http://xn--80aedhqqvlr2l.xn--p1ai/bitrix/rk.php?goto=https://https://eddrugsgeneric.com/#">top erectile dysfunction pills</a> <a href="https://deblaasbalgen.nl/?p=594721#">online prescription</a> <a href="http://www.motuoka.com/home.php?mod=space&uid=98666&do=profile#">canadian pharmacy</a> <a href="http://www.lylcgs.com/home.php?mod=space&uid=2128&do=profile&from=space#">canadian pharmacies</a> <a href="http://sasamean.com/anon/1502#">vardenafil 20mg</a> <a href="http://windytalez.moo.jp/userinfo.php?uid=2186#">buy levitra online</a>

an hour ago
 
<a href="http://cialissi.com/#">cialis without a doctor prescription</a> generic for cialis medication <a href="http://cialissi.com/#">cialissi.com</a> cialis pharmacy <a href=http://cialissi.com/#>http://cialissi.com/</a> cialis coupon http://cialissi.com/ <a href=http://cialissi.com/#>can you buy viagra without prescription</a> http://credentialprinter.com/__media__/js/netsoltrademark.php?d=cialissi.com <a href="http://temasekforum.com/__media__/js/netsoltrademark.php?d=http://cialissi.com/#">can you buy viagra in mexico without a prescription</a> <a href="http://wt.sj.17qiqu.com/home.php?mod=space&uid=237364&do=profile&from=space">generic cialis without a doctor prescription</a> <a href="https://electronicfursuits.com/wiki/index.php/User:MalcolmEricson6">ed drugs without a prescription</a>

an hour ago
 
<a href="http://canadianpharmacyies.com/#">online pharmacies</a> canada drug <a href="http://canadianpharmacyies.com/#">canadianpharmacyies.com</a> canadian online pharmacies legitimate <a href=http://canadianpharmacyies.com/#>http://canadianpharmacyies.com/</a> pharmacy uk http://canadianpharmacyies.com/ <a href=http://canadianpharmacyies.com/#>drugstore online</a> п»їhttp://iluvglhec.biz/__media__/js/netsoltrademark.php?d=canadianpharmacyies.com <a href="http://patentlawyer.us/__media__/js/netsoltrademark.php?d=canadianpharmacyies.com#">pharmacy times</a> http://microcontract.ru/bitrix/redirect.php?event1=&event2=&event3=&goto=canadianpharmacyies.com <a href="http://avtobusmaz.ru/bitrix/rk.php?goto=http://canadianpharmacyies.com/#">north west pharmacy canada</a> <a href="https://www.crypto-oc.com/vb/member.php?u=133115">online pharmacies india</a> http://fujinopromotion.com/userinfo.php?uid=1213977

Leave your comment



M. Wolski
Marcin Wolski, PhD
Economist
European Investment Bank
E-mail: M.Wolski (at) eib.org
Phone: +352 43 79 88708

View my LinkedIn profile View my profile
View my IDEAS/RePEc profile  IDEAS/RePEc