Showing posts sorted by date for query jensen. Sort by relevance Show all posts
Showing posts sorted by date for query jensen. Sort by relevance Show all posts

Friday, March 26, 2021

Unsupervised nearest neighbours

Interesting problem: we have 33 thousand 'areas' in the UK for the purposes of health. People would like to compare one health area with another that has similar demographics etc. We'd like to find these peers automatically using machine learning but nobody really knows what makes a neighbour in feature space an actual neighbour. 

This is an unsupervised ML task. We cannot use the go-to clustering algorithm KNN (where a class is elected given k nearest neighbours as calculated with some arbitrary distance metric) as this is a supervised learning algorithm and each vector is its own distinct class. That is, there is no class with more than one data point in it.

So, how do we measure how good our algorithm is? We might like to use hypothesis testing where we compare the 10 nearest neighbours (k=10 for us) from our algorithm against 10 randomly chosen feature vectors (null hypothesis). For both these samples, we follow this process: take, say, 200 other vectors randomly chosen (synthetic data) and for each feature for each of the 200, calculate whether it's within the min/max range of the sample (test statistic). With this we can calculate whether we're getting results better than chance (p-test). So, we have fulfilled all of Downey's criteria for a hypothesis test in "There is still only one test" blog post. 

Of course, we would jolly well hope that our results are better than chance but this introduces another problem: when every combination of feature engineering scores 100%, which is the best? We could take the difference between the test statistic for the null hypothesis sample and the actual sample. This is what we did in the end but it is one of any number of metrics.

Another metric we tested was the Pearson correlation statistic in measuring each feature vector in a sample with all the others. If the average score for our actual sample is greater than the null hypothesis then we know we're on the right path. Unfortunately, this proved to be not great. Thinking about it, it's not too surprising since the vectors are not random numbers but the demographics within (roughly) equal sized regions in the same country.

The Algorithm

Having established a test statistic, we then need to choose an algorithm and features.

Using the Freedman Diaconis algorithm to generate optimal bucket sizes from which probabilities could be calculated, I then used the Jensen Shannon to calculate nearest neigbours. However, our data was Zipfian so this meant almost everything fell into the same bucket. With some hacking, I resized the buckets so that there were many around the sharp peak and few at the edges. However, the score from using JS was still not great. I'm told because JS is better for finding outliers, which also jives with my experience.

Instead, the algorithm we used was L2 Euclidean distance. Bearing in mind that  Euclidean distance is not a good metric in high dimensions [SO], our test statistic looked good when we applied it to bucketed (!) and scaled data. What's more, it was computationally cheap (remember that to compare all nodes is an O(N2) problem) and easy to explain to the client.

Palantir

For this work, I was asked to use Palantir technology which was pretty easy since it seems to be a thin wrapper around Spark. Qualms aside about the selling at high prices open source technology (with some features actually crippled), some best practices I came to acquire:

  • Don't have multiple tabs open on the codebase. Apparently, you can download the code into your favourite IDE but you won't have the data. So, at some point, you'll be coding in the browser. If you have multiple tabs open, Palantir gets confused and overwrites versions. Not a great user experience.
  • Create a pyspark file for each combination in the pipeline that is only a couple of lines long which delegates to shared code. This way, it's easier to explore lineage with the Monocle tool. This is actually quite a nice feature of Palantir giving you a graphical representation of your pipelines.


Thursday, June 13, 2019

The data science of cyber-squatting


The Apache Metron project has an interesting approach to detecting cyber-squatters that can be found here. Briefly, it generates lots of names that are similar to your domain using a tool called DNS Twist.

They then use Bloom Filters to check each domain name coming through in the stream is not on this black-list. Bloom Filters cannot say that something definitely is in a collection but can say when something definitely is not. The trade-off is that they consume very little memory. And for this use case, we're not interested whether our domain is not on a black-list, only whether it is.

Bloom Filters do this by using k algorithms that given the data generate a number between 0 and m. All of these numbers then becomes indices in an m-sized bit map and we flip that but to 1. Now, we have some new data come through and we ask, have we seen this before? Well, we run those same k algorithms and if each one gives us and index that has 0 in the corresponding array, we know that this datum is definitely not on our black-list.

My approach was different. Given the domains we own (over 900  of them), I generate n-grams of characters and create a distribution of their frequency. For me, n for is {2,3} but your mileage may vary.

The same calculation is performed on each domain as it flies by and compared (using Jensen-Shannon) with the 900 or so distributions representing our real estate. A score of 0 obviously means that it's one of ours. A score much greater means it's very different. But a score close to 0 is worrying.

How close before you raise alarms depends on your data and your tuning. During testing, the smallest, non-zero domain was "www-OUR_DOMAIN" rather than "www.OUR_DOMAIN". This was a known spear-phishing scam so clearly our algorithm works to some degree. What's more, DNS Twist does not seem to have anticipated this attack.

Thursday, April 4, 2019

Master of your domain name


Introduction

I've had moderate success using neural nets to distinguish between good domain names and domain names generated by an algorithm, something you often find in malware. However:

  1. Tuning neural nets is hard and requires esoteric knowledge.
  2. They're computationally expensive both to train (OK) and to use (not OK).
  3. The results I have so far are at best reasonable and no better.

So, using the same raw data I used in my neural net work, I tried to do better.

Jensen-Shannon, bigram population distribution

I used the SMaths library to create the Jensen-Shannon scores comparing the character distribution for both good and bad domain names against the distribution for all good names using 1-hot character encoding. Unfortunately, the results are poor:

JS scores for good (green) and bad (red) domain names

Just Shannon Entropy

What do you do when there the probability for an n-gram is zero? The common answer is "ignore the zero probabilities, and carry on summation using the same equation" (StackExchange).

But I found penalizing zeros gave me better powers to differentiate the two categories. The value of this penalty was empirically derived but roughly optimising it with a crude binary search gave me a much better spread of the distributions:

Penalized Shannon entropy scores for good (green) and bad (red) domain names
and consequently a great ROC curve:

The Data

There is, however, a sting in the tail. Some of the good domain names appear to be bad!

If we look at that ROC curve in 3d:
The same ROC curve in 3d showing the threshold's relationship with the curve
And we estimate that the best value for our threshold is roughly -0.018 to maximise catching bad domains with the minimum disruption from good domains that just look a bit suspicious.

Looking at the false negatives was illuminating. Here is a small sample:

dynserv
bowupem
ikrginalcentricem
gentlemanwritten
qmigfordlinnetavox
jfbjinalcentricem
osbumen
vxheellefrictionlessv

These show a level of sophistication greater than those generated by a DGA. They contain normal (or normal-sounding) words. Words like frictionless appear in a number of these domains, adding an air of authenticity. Indeed, gentlemanwritten.net sounds positively respectable.

The false positives were even more interesting. Here is a very small selection:

95a49f09385f5fb73aa3d1e994314a45b8d51f17
mhtjwmxf
wlhzfpgs
kztudyya

These look awfully suspicious. In fact, attempts to look them up with whois reveals nothing at all - which is odd.

Conclusion

Although we're getting better results with a less computationally expensive solution than neural nets, we always assumed that the training data was clean. In fact, it appears to be reasonably clean but not pristine. On the upside, this means that if we clean the data we can reasonably expect our false positive rate to go down even further.


Tuesday, March 19, 2019

Spotting Dodgy Domain Names


These are various approaches employing machine learning to differentiate between good domain names and bad ones. By bad, I mean domains that are used to trick people into thinking they're clicking on a legitimate address (www.goog1e.com, for instance).

Data

The data is the top 1 million domain names as recorded by Cisco. You can find it here.

The data was stripped of the top level domains to remove elements that were not useful.

Then, what is left was one-hot encoded converted to bigrams of characters leading to vectors of length 1444 (that is, 38 x 38 possible ASCII characters). The code for this lives here.

This data set was then split down a 95/5 ratio of training to holdout.

We created test data from this holdout data when we deliberately corrupted it. This was done by changing either a single 'o' to become an '0' or a single 'l' to become a '1'. If there were no such characters to corrupt, the data point was discarded.

Kullback-Leibler Results

We actually use a variant of KL divergence in these results that handles zeros in the data - the Jensen Shannon metric.

In the following histograms, red indicates bad domains and green good ones.

The tables represent the entire holdout ("Good") and the entire test ("Bad") data sets with their Jensen-Shannon metric calculated against the training data.

Note that these metrics are calculated by summing the columns of the data sets. This leads to something of an unrepresentative description of the data since the original is one-hot encoded. Therefore, in any subset of 38 elements of a real vector, only one can be 1 and all the rest must be 0. That is, the elements in a vector for a given domain are not independent of each other.

No normalisation

KL Score Histogram with no normalisation
Note that "+4.914e6" in the bottom right hand corner. Indeed the KL scores are close:

ClassKL Score
Good4 319 810.24
Bad4 169 380.40

There's a hair's breadth between them so this is probably going to be hard to differentiate the classes.

L1-Normalise everything

Here, the control group's KL was 6370.17 and the bad domains scored 6370.92 - very close. The histograms unsurprisingly look similar:

KL Score Histogram with all vectors L1-Normalised
Hmm, still not much to work with, so let's try combinations of the two. First:

Normalised Baselines, No Normalisation for Others

In this trial, the baseline is L1-normalised but the other vectors are not.

ClassKL Score
Good97 285.45
Bad139 889.62

The histogram for the holdout and bad domains now looks like:

KL Score Histogram with the baseline L1 normalised; all other vectors unnormalised
This is good. There are now two distinct distributions with separate peaks.

L2-normalisation gave very similar KL scores and a graph that looked like:

KL Score Histogram with the baseline L2-normalised; all other vectors unnormalised
Let's try:

Unnormalised Baseline, L1-Normalisation for Others

... and it looks like we're back to square one. The KL scores are amazingly close:

ClassKL Score
Good4 914 404.73
Bad4 914 407.38

so, not surprisingly are the distributions of the holdout and test data:

KL Score Histogram with the baseline unnormalized; all other vectors L1-normalized
Again, note that: +4.9144e6 in the bottom right hand corner.

So, we seem to be going backwards.

Aside: Normalise then sum baseline, all others unnormalised

I tried a few other variations like normalising then summing, first with L1:

ClassKL Score
Good773 262.74
KL Score Histogram with the baseline L2-normalised then summed; all other vectors unnormalised

Bad704 254.41

then L2:

ClassKL Score
Good94 506.53
KL Score Histogram with the baseline L1-normalised then summed; all other vectors unnormalised

Bad83 559.17

But their summed distributions didn't give me a difference in KL scores as good as the "Normalised Baselines, No Normalisation for Others" results, so I stuck with those and I discuss just that distribution in the next section.

The ROC

Running our model against the test data, the ROC looks likes somewhat underwhelming:

ROC for "Normalised Baselines, No Normalisation for Others" KL

Or, in 3d where we can see the threshold value:


where a threshold value of about 10 is the closest the curve comes to the top, left hand corner.

It seems clear that out tool cannot with great confidence determine if a domain name is suspect or not. But then could a human? Which of these domain names would you say are bogus and which are genuine?

mxa-00133b02.gslb.pphosted.com
m7.mwlzwwr.biz
live800plus.jp
lf.wangsu.cmcdn.cdn.10086.cn
x10.mhtjwmxf.com
mailex1.palomar.edu
3gppnetwork.org
mimicromaxfinallb-1513904418.ap-south-1.elb.amazonaws.com
mkt4137.com
modt1thf4yr7dff-yes29yy7h9.stream
jj40.com

This is of course a trick question. They're all genuine URLs that Cisco have logged.

However, if our tool is used as part of a suite of metrics it might identify nefarious activity.

Conclusion

Our tool is definitely better than the monkey score but can we improve it? I have a neural net that looks promising but is computationally very expensive. The KL calculations (and variants of them) are very fast and cheap. I'll compare them to a neural net solution in another post.

Saturday, September 1, 2018

Extrapolation of an ML model


Introduction

We have a data set that we need to classify. About 1% has already been classified by our users and our model looks pretty decent when splitting this into testing and training subsets. However, how can we be sure that it will work on the other 99%?

Approaches

One approach might be to see what it is that makes a model decide which class to classify an object. There is a technique for this called Local Interpretable Model-agnostic Explanations (LIME).  The authors original paper make a very good point that accuracy during the testing/training phase can be misleading. "There are several ways a model or its evaluation can go wrong. Data leakage, for example, defined as the unintentional leakage of signal into the training (and validation) data that would not appear when deployed, potentially increases accuracy" erroneously, they say. They demonstrate this danger by using the 20 Newsgroups data set and observing classifications that were correct but for the wrong reason.

We will probably return to LIME but for this job we chose Kullback-Leibler as this was very easy to implement efficiently in Apache Spark.

Kullback-Leibler Divergence

What is it? Well, we want to know how our 1% data set approximates the 99%. "It is no accident that Cover & Thomas say that KL-Divergence (or "relative entropy") measures the inefficiency caused by the approximation" (from SO).

KL has a simple equation:

D(P|Q) = Σi pi ln (pi/qi)

where pi is the probability of element i in data set P and qi is the probability of element i in data set Q. You'll quickly notice that it is not a metric as it does not satisfy the triangle inequality nor symmetry. (The probability that the two distributions mimic each other is given by user Did in this SO post).

You might also quickly see that this equation blows up if there is an element in P that's not in Q or vice-versa. What to do?

You might try "smoothing" by replacing values of 0 with a "very small value" (see here). How large this value is can be quantified here.

[Aside: this SO post mentions "the number of atoms in the discrete distribution" which was a term I was not familiar with and prompted me to ask my own question on SO. In the context of a normal word count, an atom would be a word. But in other contexts we might note that a word is not atomic. For instance the English word "other" has the English word "the" inside it. What is an atom appears to be use case dependent. I also thought this SO post which compares the support of a distribution (ie, where P(X) > 0) to the set of atoms. Its example looks contrived but is quite neat as it's saying the rational numbers make up the set of atoms but the irrational numbers in [0,1] make the support].

Or, you might ignore items for which q or p is zero, that is "employ heuristics throwing out all the values that do not make sense... While I acknowledge that [this] is a convention, it doesn't really fit with the nature of these distributions... the invalidity of the formula in the presence of zeros isn't just some unfortunate hack, it is a deep issue intimately tied to how these distributions behave."

Finally, you might solve the problem by using a slightly different variant of KL like Jensen-Shannon divergence. This is simply "the sum of the KL-divergences between the two distributions and their mean distribution" (Reddit).

Having coded the algorithm, I then ran it on our data. The methodology we chose was to take 10 samples of 1% from the 99% that is unclassified and calculate their convergence metrics with the remainder. Then, the human-classified 1% was compared to this remainder. Interestingly (and annoyingly) the samples had an average Jensen-Shannon value of 0.02 (with a standard deviation of about 10^-5) while the score for the human-classified data was 0.12. So, quite a difference.

The differences seem to be based not on the missing data in each data set but due to the differences in probabilities for the data they shared. Quite why requires further investigation.