## Machine learning for hackers

Which way do you prefer to learn a new material – deep theoretical background first and practice later or do you like to break things in order to fix them? If latter is your way of learning things, then most likely you will enjoy Machine Learning for Hackers.

The book has chapters on machine learning techniques such as PCA, kNN, analysis of social graphs hence even advanced R users might find something interesting. So I want you to show you my example of visualisation of similarity between parliamentarians in Lithuania which idea is taken for chapter 9.

In most of the cases you should be able to get access to voting results of legislative body in your country. Nevertheless the data can be buried in "wrong" format such as html or pdf. I use Scrapy framework to parse html pages, however I have faced a problem, when my IP address was blocked due to many requests (10 000) within 2 hours. But in cloud age the problem was quickly solved and I made a delay in my crawler. Here is the examples of the data in CSV format.

With data in hand it was easy to proceed further. To find similarities between parliamentarians I took voting results of approximately 4000 legislations and built a matrix, where rows represent parliamentarians and columns – legislations. "Yes" votes were encoded as 1, "No" as -1 and the rest as 0. R has a handy function dist to compute the distances between the rows (parliamentarians) of a data matrix. The result of the function is one dimension data of the distance between parliamentarians, however to reveal the structure of a data set we need two dimensions. Once again, R has a function cmdscale which does Classical Multidimensional Scaling (CMS). I found this document very useful in explaining Multidimensional Scaling. Here is the final result:

Click on the image to enlarge.

The plot above reveals, that right wing party TSLKD has a majority in parliament and LSDP (socialists) are in opposition and liberals (LSF, JF, MG) are in the center. You might argue, that that is already known, however the plot is based on actual data, therefore differences in voting support outlooks of the parliamentarians(right, central, left).
The map shows which members of the party are outliers and which one from the other party can be invited while forming a new parliament (second tour of the election is on the way).
Members of the left wing are mixed up and it would make sense to them to merge or form a coalition.

## Garmin data visualization

People go on rage, when governments initiate surveillance projects like CleanIT, nevertheless share very private data without a doubt.

I have to admit, that some data leaks are well buried in the process. Take for example Garmin which produces GPS training devices for runners. In order to see your workouts you are forced to upload sensitive data on internet. In response you are given a visualization tool and a storage facility. What are alternatives? It seems, that in the past there was a desktop version, however I was not able to find it. So, we are left with the last option – hack it.

First of all you need to transfer data from Garmin device to computer. I own Forerunner 610 with relays on ANT network and I found Python script with takes care of data transfer. Once data is transfered there is another obstacle – Garmin uses a proprietary format FIT. In order to tackle this problem I use another Python script which I have adapted to have csv format.

Once data is in CSV format R can be used to plot data.

I had a lot of fun by trying to understand Garmin longitude and latitude coordinates. Here is a short explantion by Hal Mueller:

The mapping Garmin uses (180 degrees to 2^31 semicircles) allows them to use a standard 32 bit unsigned integer to represent the full 360 degrees of longitude. Thus you get the maximum precision that 32 bits allows you (about double what youâd get from a floating point value), and they still get to use integer arithmetic instead of floating point.

## Building a presentation, report or paper in R

If you need to build a presentation, obviously you have following options:

• Powerpoint alike presentation
• Online engines
• LaTex

The first two are beloved by business people and the third one is widely used in academia. The objective of the first group is shiny presentation, contrary to the second where asceticism and demand for automation are top priorities. However, if you are data scientist or any other data specialist with a need to build an automated report, then you know, that LaTex is just wrong.
LaTex allows you to build a shiny presentation or outstanding paper, however it can take light years to build something useful for beginners . If you never tried LaTex here is an example of the monster – you literally have to code a document or presentation:

\documentclass{article}
\title {Investment strategy}
\author {Dzidorius Martinaitis}
\begin{document}
\maketitle

So, what do you do, if you need only 1% of all LaTex features and a report/document needs to be build automatically? Turns out, that HTML little brother Markdown is saving the world. Markdown(.md) source files are easy to read and easy to write and you can convert it into .html, .pdf, .docx, .tex or any other format. There are many ways to do conversion, however I use Pandoc utility. By the way this post was written in markdown in Vim and you can check the source file.

However, the nicest thing about Markdown is integration with R. You can build your report in one file, where R code would be embed in Markdown. Knitr package will help you to convert R code into Markdown simply by calling this piece of code:

require(knitr);
knit('workshop.Rmd', 'workshop.md');

Below you will find an excerpt of .Rmd file which is mix of R and Markdown:

Get the data
===

{r results=asis,comment=NA, message=FALSE}
names=sapply(tweets,function(x)x$screenName) rez=(aggregate(names,list(factor(names)),length)) rez=rez[order(rez$x),]
colnames(rez)=c('name','count')
options(xtable.type = 'html')
require(xtable)
xtable(t(tail(rez,6)))


Plot top10 tweeters
===
{r topspam, figure=TRUE,fig.cap=''}
barplot(tail(rez$count,10),names.arg=as.character(tail(rez$name,10)),cex.names=.7,las=2)


Here is a workshop presentation which contains the example above – I built it for Haxogreen hackers camp and source code can be found on gitHub.

## How to track Twitter unfollowers in R

I have Twitter account and it is relatively easy to see new followers or subscribers. However, I was looking for ways to know who are the unfollowers. I have noticed, that some (un)subscriptions happen in bulks, which made me thinking that either I tweeted some bullshit and upset bunch of people or spam bots work in sync. With that in mind I have created a simple R script, which produces Markdown and html reports about unfollowers. You can find an example of such report below.

The advantage of this script is that it does not require you to sign or share your data. You just have to install twitter package and you ready to go. Nevertheless, if you want to create Markdown report, you need to install markdown and knitr packages.

The source code and build scripts can be found here.

 {r echo=FALSE,message=FALSE} require(twitteR) setwd('~/git/twitTracker/') usr=getUser("dzidorius") tmp=sapply(usr$getFollowers(),function(x)x$screenName)   if(!file.exists('users.csv')) { ## when file doesn't exist - take users list and add some artificial user write.table(c(as.character(tmp),'dzidorius'),'users.csv')   }   old_list=as.character(read.table('users.csv')$x) users=lookupUsers(old_list[which(!(old_list %in% as.character(tmp)))]) if(length(users)==0) { ## stop() doesn't work under knitr cat('no one left you') }  {r comment=NA,echo=FALSE,message=FALSE,results='asis'} for(i in 1:length(users)) { cat(paste("**",users[[i]]$name," @",users[[i]]$screenName,"**", "\n===\n",sep="")) cat(paste("![](https://api.twitter.com/1/users/profile_image?screen_name=",users[[i]]$screenName, "&size=bigger)",sep='')) cat(paste(" \n**Created:** ",users[[i]]$created, " \n**Spam rate:** ",round(users[[i]]$followersCount/users[[i]]$friendsCount,digits=2), " \n**Activity:** " , users[[i]]$statusesCount, " \n**Location:** ", users[[i]]$location," \n",users[[i]]$description," \n", "**Last status:** ",(users[[i]]$lastStatus$text),"\n\n",sep="")) }    {r comment=NA,echo=FALSE,message=FALSE,results='asis'} write.table(as.character(tmp),'users.csv') 

# Dzidas @dzidorius

Created: 2010-02-18 13:09:29
Spam rate: 0.98
Activity: 315
Location: Luxembourg
Java, C++ and R developer & data junkie
Last status: It is rainy summer in #Luxembourg but there is a party! http://t.co/FZ7eZq6u

## Data mining for network security and intrusion detection

In preparation for “Haxogreen” hackers summer camp which takes place in Luxembourg, I was exploring network security world. My motivation was to find out how data mining is applicable to network security and intrusion detection.

Flame virus, Stuxnet, Duqu proved that static, signature based security systems are not able to detect very advanced, government sponsored threats. Nevertheless, signature based defense systems are mainstream today – think of antivirus, intrusion detection systems. What do you do when unknown is unknown? Data mining comes to mind as the answer.

There are following areas where data mining is or can be employed: misuse/signature detection, anomaly detection, scan detection, etc.

Misuse/signature detection systems are based on supervised learning. During learning phase, labeled examples of network packets or systems calls are provided, from which algorithm can learn about the threats. This is very efficient and fast way to find know threats. Nevertheless there are some important drawbacks, namely false positives, novel attacks and complication of obtaining initial data for training of the system.
The false positives happens, when normal network flow or system calls are marked as a threat. For example, an user can fail to provide the correct password for three times in a row or start using the service which is deviation from the standard profile. Novel attack can be define as an attack not seen by the system, meaning that signature or the pattern of such attack is not learned and the system will be penetrated without the knowledge of the administrator. The latter obstacle (training dataset) can be overcome by collecting the data over time or relaying on public data, such as DARPA Intrusion Detection Data Set.
Although misuse detection can be built on your own data mining techniques, I would suggest well known product like Snort which relays on crowd-sourcing.

Anomaly/outlier detection systems looks for deviation from normal or established patterns within given data. In case of network security any threat will be marked as an anomaly. Below you can find two features graph, where number of logins are plotted on x axis and number of queries are plotter on y axis. The color indicates the group to which points are assigned – blue ones are normal, red ones – anomalies.

Anomaly detection systems constantly evolves – what was a norm year ago can be an anomaly today. The algorithm compares network flow with historical flow over given period and looks for outliers with are far away. Such dynamic approach allows to detect novel attacks, nevertheless it generates false positive alerts (marks normal flow as suspicious). Moreover, hackers can mimic normal profile, if they know that such system is deployed.

The first task when implementing anomaly detection (AD) is collection of the data. If AD is going to be network based, there are two possibilities to collect aggregated data from network. Some Cisco products provide aggregated data as Netflow protocol. However, you can use Wireshark or tshark to collect network flow data from the computer. For example:

tshark -T fields -E separator , -E quote d -e ip.src -e ip.dst -e tcp.srcport -e tcp.dstport -e udp.srcport -e upd.dstport -e tcp.len -e ip.len -e eth.type -e frame.time_epoch -e frame.len

Once you have enough data for mining process, you need to preprocess acquired data. In the context of intrusion, anomalous actions happen in bursts rather than single event. Varun Chandola et al. proposed to derive following features:

• Time window based:
Number of flows to unique destination IP addresses inside the network in the last T seconds from the same source
Number of flows from unique source IP addresses inside the network in the last T seconds to the same destination
Number of flows from the source IP to the same destination port in the last T seconds host based – system calls network based – packet information
Number of flows to the destination IP address using same source port in the last T seconds
• Connection based:
Number of flows to unique destination IP addresses inside the network in the last N flows from the same source
Number of flows from unique source IP addresses inside the network in the last N flows to the same destination
Number of flows from the source IP to the same destination port in the last N flows
Number of flows to the destination IP address using same source port in the last N flows

Below you can find an example of feature creation in R. The dataset was created by calling tshark script, which is specified above.

#get rid of everything below min. in timestamp
tmp[,10]=as.integer(as.POSIXct(format(as.POSIXct(as.integer(tmp[,10]),origin=‘1970-01-01’),‘%Y-%m-%d %H:%M:00’)))
#fix some rows
tmp=tmp[-which(sapply(tmp[,1],function(x) nchar(x)>15)),] tmp=tmp[which(!is.na(tmp[,4])),]

#aggregate date by 5 mins. it assumes, that flow is continuous
factor=as.factor(tmp[1:5000,10])

feature=do.call(rbind, sapply(seq(from=1,to=length(factor),by=4),function(x){ return(list(ddply( subset(tmp,factor==levels(factor)[x:(x+4)]),.(V1,V4),summarize,times=length(V11),.parallel=FALSE ))) }))

After preprocessing the data we can apply local outlier detection, KNN, random forest and others algorithms. I will provide R code and practical implementation of some algorithms in the following post.

While preparing this post, I was looking for the books, I found only few books covering data mining and network security. To my surprise Data Mining and Machine Learning in Cybersecurity book includes both topics and well written. However, if you are security specialist looking for data mining books, you can read my summary of “Data Mining: Practical Machine Learning Tools and Techniques”

## My first competition at Kaggle

For me Kaggle becomes a social network for data scientist, as stackoverflow.com or github.com for programmers. If you are data scientist, machine learner or statistician you better off to have a profile there, otherwise you do not exist.

Nevertheless, I won’t bet on rosy future for data scientist as journalists suggest (sexy job for next decade). For sure, the demand for such specialists is on rise. However, I see one big threat for data scientist – Kaggle and similar service providers. You see, such services allows to tap high end data scientists (think of PhD in hard science) at minuscule fraction of real price. Think of Hollywood business model – top players get majority of the pool and the rest is starving. If you try the same service model on IT projects you will most likely get burned. My reasoning can be wrong, but I suspect, that project timespan is the issue – IT projects can take for while to finish (1-10 years), but main stream ML project won’t take that long.

Notwithstanding these obstacles, machine learning, information retrieval, data mining and etc. is a must with ability to write code for production, deal with streaming big data and cope with performance of intelligent system. Then, in programmers parlance, you will became “data scientist ninja” and every company will die for you. There is a good post on the subject on mikiobraun blog, but I mind you, that it is a bit controversial.

Although for last 4 years I often has been working on financial models and time-series, this competition added a new experience to me and hunger for the knowledge. During competition I found this book very practical and plentiful of ideas what to do next: Data Mining: Practical Machine Learning Tools and Techniques. As complimentary book I used Data Mining: Concepts and Techniques, though most of information can be found in one of them. I will try to summarize some chapters in my own story.

Understanding the data. “Online Product Sales” competition metadata (data about data) is miserly – there are three types of the data – the date fields, categorical fields, quantitative fields and response data for next 12 months. However metadata is most important element in all ML projects, which can save you a lot of time once you understand it better and it leads to much better forecast if you have “domain knowledge”.

Cleaning data. There is famous phrase: “garbage in garbage out”, meaning, that before any further action you have to detect and fix incorrect, incomplete or missing data. You have many possibilities to deal with missing data – remove all rows, where the data is missing; replace it with mean or regressed value or nearest value and etc.  If your data is plentiful and missing values are random (meaning, that NA values do not bear any information) – just get rid of them. Otherwise you need impute new values based on mean or other technique. Mean based replacement worked best for me in this competition.
Outliers are another type of the troubles. Suppose, that variable is normally distributed, but few variables are far away from the center. The easiest solution would be to remove such values – as many do in finance by removing “crisis period”.  When next crisis hits, the journalists are rushing to learn a new buzzword- black swan. Turns out, that outliers can’t be ignored, because the impact of them is huge.  So be precautious while dealing with outliers.

Feature selection. It was surprising to me that too many features or variables can pollute forecast, therefore you need to do feature selection. Such task can be done manually be checking correlation matrix, co-variance and etc. However, random forest or generalized boosted methods can lead to better selection. In R you just call randomForest() or gbm() and job is done.

Variable transformation - a way to get superior performance. “Online Product Sales” competition has two date fields, however these fields encoded as integers. By transforming these variables into date and retrieving year and month led to better performance of the model. In most of cases taking logarithm for numeric fields gives performance boost. Scaling (from 0 to 1 or from -1 to 1) and centering (normal distribution) might be considered when linear models are in use.  It is worth to transform categorical variables as well, where 1 would mean, that a feature belongs to the group and 0 otherwise. Check model.matrix function in R for latter transformation and preProcess function in caret package for numerical variables.

Validation stage - helps you to measure performance of the model. If you have huge database to build a model you can divide you set into two/three parts – for training, testing and cross validation and you are ready to start. However, if you are not so lucky, then other methods come to play. Most popular method is division of the set into two groups, namely “training” and “test” and rotating it for 10 times. For example, you have 100 rows, so you take first 75 for training and 25 for test and you check the performance ratio. In the next step you take the rows from 25 to 100 for training and you use first 25 for test. Once you repeat such procedure 10 times, you have 10 performance ratios and you take average of it.
Stratified sampling is a buzzword, which you should know when you do a sampling.
Keeping all this information in mind I wasn’t able to to implement accurate cross validation and my results differ within 0.05 range.

Model selection and ensemble. Intuitively you want to choose the best performing algorithm, however the mix of them can lead to superior performance. For regression problem I trained four models (two random forest versions, gbm, svm), made the predictions, averaged the results and that led to better prediction.

## GitHub data analysis

Few weeks ago GitHub announced, that its timeline data is available on bigquery for analysis. Moreover, it offers prizes for the best visualization of the data. Despite my art skills and minimal chances to win beauty contest, I decided to crunch GitHub data and run data analysis.

After initial trial of bigquery service, I found hard to know, what price, if any, I’m going to pay for the service. Hence, I pulled the data (6.5 GB) from bigquery on my machine and further I used my machine for analysis. Bash scripts have been used to clean up and extract necessary data, R for data analysis and visualization and C++ for text extraction.

GitHub dataset is one table, where each row consist of information about repository (i.e. path, date of creation, name, description, programming language, number of forks/watchers and etc.) and action, which was done by user (i.e. username, location, timestamp and etc.).

As a result, we can check how GitHub users actions are spread over time during the day. The X axis on the graph below is labeled with the hours of the day (GMT) and the Y axis represent median values of the actions for each hour. From it, we can make a deduction, that highest load for GitHub can be expected between 15:00 and 17:00 GMT and lowest to be expected between 05:00 and 07:00 GMT. The color of the line indicates how busy was the day based on quantiles: green are calm days (20% of days), blue – normal days (50% quantile) and red are busy days (80% quantile). I should to mention, that auto-correlation or serial correlation is high (70% for following hour), which means, that busy hours tend to be followed by busy hours and calm hours tend to be followed by calm hours. Moreover, busy days tend happen after busy days.

Second graph below shows median of actions divided by weekdays. There is not big surprise – weekends are more slow than weekdays, nevertheless the programmers are slightly less productive on Mondays and Fridays.

The analysis of creation of new repository shows, that the pattern of busy or calm hours remains over the years. This can be attributed to the fact, that majority of the users comes from North America and Europe.
Another hypothesis can be drawn from this information, that number of creation of the new repositories grow exponentially. However, I mind you, that the graph below is biased – most likely, GitHub users update recent projects, consequently more recent projects appeared on timeline. Even though, 2009-2011 years show exponential grow.
The X axis of the graph below is labeled with the hour of the day, the Y axis – log of median values of new repositories.

Following graph shows the number of forks per project (the X axis, log scale) versus number of watchers (the Y axis, log scale). As expected, there is linear correlation between forks and watchers. Even so there is something interesting about outliers, which are below bottom line – the projects, where number of watchers is low, but number of forks is high. These are anomalies and worth to check.

The next thing to do is to look at the repository description. Let’s group the repositories by programming language and count most dominant words in the description. The graph below has C++ word cloud on the left and Java – right . C++ projects are about library, game, simple(?), engine, Arduino. Java is dominated by android, plugin, server, minecraft, spring, maven.

Ruby (left) vs Python(right ):

“Surprise”, “surprise” – R projects (left) are largely about data analysis, however “machine” word, which corresponds to Machine learning is very tiny. Shell (right) is dominated by configuration, managing, git(?).

GitHub dataset includes location field. Unfortunately, the users can enter whatever they want – country, city or leave it empty. Nevertheless, I was able to extract good chunk of actions, where location field has meaningful value.  The video below shows country based users activity, where dark red corresponds to high activity and light red – minor. Only 30 most active countries are included, the rest are grey.
The same pattern persist over the days – activity in Asia increases around midnight, Europe wakes up around 8:00 or 9:00, where America starts around 15:00. Who said, that hackers and programmers work at night?

What else can be done with GitHub dataset? Most repositories have description field, which can be used to find similar projects by implementing tf-idf method. I tried that method and the results are satisfying.

Most of the graphs shown above are reproducible (except word clouds) and the code can be found on GitHub.

## Machine learning for identification of cars

There are plenty of data on internet, however it is raw data. Think for a second about public surveillance cameras - useful to check the traffic on the route or busy place, but anything else? What if you want to know how many cars are on the route? How many car were yesterday at the same time? Given so many cars on the route, how much polluted air in the area?
While working on the road map for data dive event, I started to wonder, how feasible is to use data of public surveillance cameras. So I quickly built a pilot project and now I would like to share my experience.

First step – data acquisition. At beginning I was thinking to plug my smartphone somewhere and collect data of the busy route.  Nevertheless, I quickly found surveillance cameras in Vilnius and started to collect images. Run a search and I’m sure, that you will find them in your city:

Here is bash script, which I use to collect images:

 #you need full path for crontab cd /home/git/carCount/img a=date +%s b=${a}_4.jpg wget -O$b -q "http://www.sviesoforai.lt/map/camera.aspx?size=full&image=K7742-1.jpg&rnd=0.15417794161476195"

Data preparation. After while you will have enough data to train your machine (for beginning more than 30 images should be O.K.).
How do we train the algorithm? The goal is to identify the cars in a given image. That means, that we have to provide the examples of positive images (clear image of the cars) and negative images (no car, parts of the car and etc.). Important note – we don’t feed whole image, but we cut a chosen image with sliding window (100×100 in my case). 4 examples of positive images:

Meanwhile, it is worth converting each image to portable grey format PGM. For this specific task, we can sacrifice information about the color of the car – it won’t improve prediction. Besides, PGM images can be loaded into R and easily transformed into matrix. Here is bash script, which converts jpg to pgm and slices each image:

 #remove image duplicates find . -maxdepth 1 -type f -exec md5sum {} \; >test.txt awk 'a[$1]++ {gsub(/^\*/,"",$2); print "rm ", $2}' test.txt |sh rm test.txt #convert jpg if [ -d "out" ]; then rm -r out fi mkdir out for k in$(ls *.jpg); do convert $k out/$k.pgm; done   cd out mkdir slide for filename in $(ls *.pgm); do w=convert$filename -print "%w" /dev/null h=convert $filename -print "%h" /dev/null let "ww=$w/100" let "hh= $h/100" for((y=150;y<=250;y+=50)) do for((i=100;i<=400;i+=50)) do echo "slide/$i.$filename" let "h_slide=$i" convert $filename -crop 100x100+$i+$y slide/$y.$i.$filename done done done

Training, predicting, cross validation. Now is time to open R, load 100×100 images from “train/out/slide” directory and train the algorithm. Important note – each image is a matrix, however you have to feed a matrix of all images to learning algorithm (support vector machine in my case). What you have to do is to “unroll” each image matrix into a vector, get 1X10000 vector and build a new matrix, where each row is an image.
Once training is done, load unseen data from “crossval/out/slide” directory and check “result/” directory, where you will find  images of the cars. R script, which does all above:

?View Code RSPLUS
 setwd('/home/git/carCount/')   ######read positives############ files=list.files('test/pos/') pos=matrix(nrow=NROW(files),ncol=100*100)   for(i in 1:NROW(files)) {   gray_file=read.pnm(paste('test/pos/',files[i],sep=''))   pos[i,]=c(gray_file@grey) } outcome=vector(length=NROW(files)) outcome[which(outcome!=1)]=1   ########read negatives############# files=list.files('test/neg/') neg=matrix(nrow=NROW(files),ncol=100*100)   for(i in 1:NROW(files)) {   gray_file=read.pnm(paste('test/neg/',files[i],sep=''))   neg[i,]=c(gray_file@grey) } tmp=vector(length=NROW(files)) tmp[which(tmp!=0)]=0 outcome=c(outcome,tmp) forecast=svm(rbind(pos,neg),outcome) cross_val=pos[84:90,] pred=predict(forecast,cross_val,decision.values=TRUE)   ##########################unseen data###################### files=list.files('crossval/out/slide/') cross=matrix(nrow=NROW(files),ncol=100*100)   for(i in 1:NROW(files)) {   gray_file=read.pnm(paste('crossval/out/slide/',files[i],sep=''))   cross[i,]=c(gray_file@grey) } pred=predict(forest,cross,decision.values=TRUE)   ###############copy positives into result directory############### dir.create('result') file.copy(paste('crossval/out/slide/',files[which(as.double(pred)>0.6)],sep=''),'result/')

Classified as positive by algorithm:

Classified as negative by algorithm:

Conclusion. It is truly amazing how well algorithm is able to separate wheat from the chaff without additional tuning. Mind you, my impression is biased after so many fails with financial data, which is noisy and good predictions are scarce.
Nevertheless, this project is far away for ideal – it doesn’t take into account weather condition, traffic jams, perspective view, movements of the camera and etc. But I leave this fun for data-dive event.

Fork the codehttps://github.com/kafka399/carCount/

## Levenshtein distance in C++ and code profiling in R

At work, the client requested, if existing search engine could accept singular and plural forms equally, e. g. “partner” and “partners” would lead to the same result.

The first option – stemming. In that case, search engine would use root of a word, e. g. “partn”. However, stemming has many weaknesses: two different words might have same root, a user can misspell the root of the word, except English and few others languages it is not that trivial to implement stemming.

Levenshtein distance comes as the second option. The algorithm is simple – you have two words and you calculate the difference between them. You can insert, delete or replace any character, but it will cost you. Let’s imagine, an user enters “Levenstin distances” into search engine and expects to find revalent information. However, he just made 2 errors by misspeling the author’s name and he used plural form of “distance”. If search engine accepts 3 errors – the user will get relevant information.

The challenge comes, when you have a dictionary of terms (e. g. more that 1 mil.) and you want to get similar terms based on Levenshtein distance. You can visit every entry in the dictionary (very costly) or you can push dictionary into the trie. Do you need a proof for the cost? There we go:

Red color indicates the performance of the search, when all terms are in the trie, green – simple dictionary.

Now we come to the second part of the post – why to bother and plot such graphs, if we could check few entries to determine average time and the winner? The reason is simple – we trust in God, all others must bring data. To say it differently – while profiling the code, you should be interested in average time AND variation. As you can see in the graph above, variation of the blue color is very small – it takes approximately the same time to scan whole dictionary. However, red has higher variation – the result can take for while or it can finish just at the beginning, but overall it works faster.
Now, imagine, that a programmer wants to define, which implementation A or B for volatile cache is much faster. Let’s assume, that big O notion is not going to help and she conducts 2 test for A and 2 for B. While running test A, cache size expands, while B – shrinks. As the result, B wins over A and she makes wrong choice. However, her colleague claims, that despite A has greater volatility, it is much faster and she tried with 500 queries! Whom should I trust?

I use this piece for code profiling:

?View Code RSPLUS
 1 2 3 4 5 6 7 8 9 10 11 12 13   simple=read.table('simple.txt') node=read.table('node.txt')   simple=cbind(simple,as.character(c('simple'))) colnames(simple)=c('time','type') node=cbind(node,c('node')) colnames(node)=c('time','type')   rez=data.frame(rbind(simple, node))   require(ggplot2)   ggplot(rez,aes(time,fill=type))+geom_density(alpha=0.6,size=1.3)+scale_x_log10()

The data, C++ code for Levenshtein distance and trie can be find on GitHub.

I found this source very useful: http://stevehanov.ca/blog/index.php?id=114

## Vectorized R vs Rcpp

In my previous post, I tried to show, that Rcpp is 1000 faster than pure R and that generated the fuss in the comments. Being lazy, I didn’t vectorize R code and at the end I was comparing apples vs oranges.

To fix that problem, I built a new script, where I’m trying to compare apples against apples. First piece of code named “ifelse R” uses R “ifelse” function to vectorize code. Second piece of code is fully vectorized code written in R, third – pure C++ code and the last one is C++, where  Rcpp ”ifelse” function is used.

name seconds
ifelse R 27.50
vectorized R 10.40
pure C++ 0.44
vectorized C++ 2.24

Here we go – vectorization truly helps, but pure C++ code still 23 times faster. Of course you pay the price when writing it in C++.
I found a bit strange, that vectorized C++ code doesn’t perform that well…

You can get the code from github or review it below:

?View Code RSPLUS
 `#Author Dzidorius Martinaitis #Date 2012-02-01 #Description http://www.investuotojas.eu/2012/02/01/vectorized-r-vs-rcpp   bid = runif(50000000,5,9) ask = runif(50000000,5,9) close = runif(50000000,5,9)   x=data.frame(bid=bid,ask=ask,last_price=close) rez=0   ########### ifelse R ################# answ=as.vector(system.time( { rez = ifelse(x$last_price>0,ifelse(x[, "bid"] > x[, "last_price"], x[, "bid"], ifelse((x[, "ask"] > 0) & (x[, "ask"] < x[, "last_price"]), x[, "ask"], x[, "last_price"])), 0.5*(x[, "ask"] + x[,"bid"])) })[1]) ########### end ifelse R ################# ########### vectorized R ################# answ=append(answ,system.time( { lgt0 = x$last_price > 0 bgtl = x$bid > x$last_price agt0 = x$ask > 0 altl = x$ask > x$last_price rez = x$last_price rez[lgt0 & agt0 & altl] = x$ask[lgt0 & agt0 & altl] rez[lgt0 & bgtl] = x$bid[lgt0 & bgtl] rez[!lgt0] = (x$ask[!lgt0]+x$bid[!lgt0])/2 } )[1]) ########### end vectorized R #################   #C++ code starts here   library(inline) library(Rcpp)   ########### pure C++ #################   code=' NumericVector bid(bid_);NumericVector ask(ask_);NumericVector close(close_); int bid_size = bid.size(); NumericVector ret(bid_size); for(int i =0;i0) { if(bid[i]>close[i]) { ret[i] = bid[i]; } else if(ask[i]>0 && ask[i]

Next Page »