[ July 2012 ]

Powered by glolg
Display Preferences Most Recent Entries Chatterbox Blog Links Site Statistics Category Tags About Me, Myself and Gilbert XML RSS Feed
Tuesday, July 31, 2012 - 23:42 SGT
Posted By: Gilbert

Ignominious Failure

Having just gotten home from campus, I was taken aback to find Mr. Robo laid out before the front door.

Me: Erm, why are you prostrating yourself, Mr. Robo?

Mr. Robo: *Not raising his head* I'm sorry! I'm sorry! It failed! Please don't euthanize me!

Me: Huh? Wait... did Mr. Ham have anything to do with this?

Mr. Ham: Hey, I was just tryin' to motivate our research asset 'ere to greater pro-duct-i-vity levels, see.

Me: Bad hamster! Bad hamster!

Mr. Ham: 'ell now, I was jus' helpin' out. 'M being nice all'dy, ain't even pulled out my Cult Leader techniques like threatening 'im with what e's gettin' after 'e dies.

Me: Great, you've even picked up the accent from your overseas Sect Expansion Exchange. Shoo now, go find something else to do. *Turns to Mr. Robo* And what's the matter?

Mr. Robo: *sniffles* Well, I was just following on from our character recognition investigations. I first finished coding the distortion correction as mentioned a month or so ago. That bit was rather successful, if I say so myself:




The next step was to verify whether the SVM model we built was adequate, and to check that, I manually segmented 50 Google CAPTCHAs into their individual characters, like this:




I then ran the 450 characters gathered thus through our SVM model, and the results weren't good enough:




*Nervously* What this basically says is that the recognition success rate is only around 45% for distortion-corrected characters (about 40% without), and that this varies by letter - for example, "i" and "r" have a relatively high success rate, while "b" and "d" are predicted especially poorly.

I've generated a 38-page compilation with the details, but my reading of what has happened is that despite our efforts in introducing distortions into our training data, they were still insufficient to encompass the actual CAPTCHA variations.

Me: In a way, this can be understood - MNIST for instance used 6000 training instances for each digit, there were only ten digits in total, and as far as I know the digits were not deliberately made less legible, as for CAPTCHAs; in contrast, we used only 1000 training instances for each of 26 letters, with a relatively small selection of fonts which might not have reflected those actually used in the CAPTCHAs.

But from another perspective, 45% isn't completely out of whack - it's roughly what we got on testing on the decorative fonts, and about ten times better than pure chance (3.8%), or four times better than guessing the most common letter. Heck, I ran the suitably-resized characters through Tesseract, which gave like 36%.

Mr. Robo: Well, if you put it that way...

Me: But yes, it isn't good enough. You might as well reveal what the next step would have been, since it's kind of obvious anyway.

Mr. Robo: Yes, about that. I would then have attempted to extract letters from the CAPTCHAs, using an idea which has had many names in its various forms - scale-space representation, pyramidal decomposition, hierarchical modelling... but basically it's just examining many subdivisions of the CAPTCHA, discovering the most plausible letter candidates, and stitching the findings back into an answer.

Mr. Ham: I call it Shoot-Shoot-Shoot, because what it does is just shooting lines down to cut the image apart. Catchy, yes?




Mr. Robo: It did make some sense.

Me: Don't be influenced by him!

Mr. Robo: Sorry. Here's an example, using our actual model results:




Where the subimages correspond to high recognition probability scores, they are coloured, in red for probabilities greater than 0.9, and purple otherwise for probabilities greater than 0.75. Testing speed, mentioned before, is important due to the number of subimage checks required - for now, it is still manageable, with the 700-odd subimages taking just a couple of seconds to run through (the animation is slowed for viewing purposes)

As can be seen, most of the actual letters do result in high probabilities, other than "i", which is consistently mispredicted as "j" here. The problem is that quite a few non-letters have high probability responses too:


Well, ok, there's the shadow of a "u" there...


These rather unreasonable false positives mean that it is unlikely that the method will work as of now, since it would be extremely hard to distinguish between true and false letter candidates, though some of the CAPTCHAs were nearly solved, but always tripped up by the stray letter or two; our search for a black box that, when given a candidate image, either rejects it as a non-letter or correctly identifies the letter it represents with extremely high probability, thus continues.

Me: I might as well mention here that I did manage to get a second set of Google Captchas which exhibit the characteristics as mentioned here, i.e. they contain between 5 to 8 letters only (average 6.48, strongly suggesting that number of letters is uniformly distributed), and not the 8 to 10 letters we got for our first dataset. Spent most of Saturday afternoon solving the 2000 of them twice.

The intra-rater reliability was 97.75% this time, up from 92.85%, as expected with fewer letters, with the estimated single-letter recognition rate also increasing from 99.18% to 99.65%, though that's not saying too much. Maybe we should help the research community by making both datasets publicly available, maybe as GROBO-1 and GROBO-2?

Mr. Robo: There's a small problem with that...

Mr. Ham: I've bought over the rights to them.

Mr. Robo: I was hungry, and he had some very tasty-looking sunflower seeds, so...

Me: ...I suppose that's about it on this for now. There're a couple of things we could do, including simply adding more data with more varied distortions to the model (which might however adversely affect prediction time), but all this will have to wait. Got a thesis to start thinking about seriously, along with other interesting challenges - the CAPTCHAs aren't going away, and the general problem has stymied some of our best minds for a long time, after all.

Mr. Robo: Um, on this note, Google Handwrite for smartphones has just launched.

Me: Great, one more idea scooped. Not that it was that new actually, Palm OS has had Graffiti for years. In any case, they're still limited to block letters for the most part, so there's still space to explore. Onward and upward!



comments (0) - email - share - print - direct link
trackbacks (6) - trackback url

Back to top


Monday, July 30, 2012 - 00:21 SGT
Posted By: Gilbert

Lelong Lelong

Bookmark a.k.a excess material clearance once again:



Also:




comments (0) - email - share - print - direct link
trackbacks (0) - trackback url

Back to top

Thursday, July 26, 2012 - 02:44 SGT
Posted By: Gilbert

Double Tap


I'd Tap It

The first of Mr. Robo's deliberations towards reliable blind texting is: if it ain't broke, don't fix it (and don't let an existing tech giant buy it out)! Millions are using multi-tap and T9 happily enough one-thumbed, and may well wish to keep to the familiar instead of putting their faith in miniscule keys. Apparently some developers have also recognized that - an iPhone multi-tap app has been released barely more than a month ago, while various Android apps also offer the old-school keypad as an option.

Clearly, a direct port is quite easily accomplished; however, as mentioned, the smartphone interface departs significantly from old cellphones in having no tactile feedback - therefore, for blind multi-tapping, the app would have to infer the keys by the relative movement of the thumb.

We might expect this process not to be perfect without physical keys as guidance, though, and it may be that ambiguous input is then the norm - for example, when a user moves down and to the right from after pressing the "2" key (which corresponds to the letters a, b and c in multi-tap), his actual intention might be to reach any of "4", "5", "8" or "9". One approach would then to try and dynamically estimate the position and size of the user's imagined keypad from input, as the creators of BlindType did, but before that it should be asked if this would be reliable - or even necessary.

A little background now: users of the T9 system should well be aware that certain words require the same input pattern, and are thus textonyms. Wikipedia conveniently supplies the example pair "home"/"good", which both arise from the sequence 4663. Obviously, this is a quite unavoidable consequence of the setup, which might be resolved in several ways, some of which will be discussed later.

Mr. Robo's proposal is then to adapt multi-tap, for two good reasons - firstly, T9 and the like are patented, and secondly, while maintaining directionality on a featureless touchscreen while typing blind may be iffy, entering the correct number of taps, even without looking, can be relied upon much more confidently. Recall the number of taps needed for each letter, in the traditional multi-tap system:

TapsLettersTotal Frequency*
1a, d, g, j, m, p, t, w30.562%
2b, e, h, k, n, q, u, x30.790%
3c, f, i, l, o, r, v, y32.568%
4s, z6.407%

[* From Wikipedia - adds up to 100.327% (shrugs)]

Therefore, 2.15 taps are required for each letter, averaged over many text messages. Note that this alphabetical arrangement is likely not the most efficient for true multi-tap entry, which would be faster if the eight most popular keys were assigned single taps, then the next eight most popular, double taps, and so on (in the spirit of Huffman coding) - the average number of taps per letter would then fall to about 1.47, and the separation of the most popular letters might moreover aid predictive algorithms (slightly)

While this might suggest that multikey input would then take twice as long as standard QWERTY keyboard smartphone input, which assigns one key, and therefore one tap, to each individual letter, Mr. Robo posits that this may not be the case. For one, he suspects that there will be time savings in not having to maneuver fingers over tiny keys, or alternatively backspace furiously after mistakes made in haste (for more theory behind this, see Fitt's Law)

We now come back to the problem of ambiguous direction, and Mr. Robo has a quite outrageous suggestion - why not completely disregard the direction moved, and concentrate solely on the number of taps? Therefore, for example, "home" would be input as tap-tap-[move]-tap-tap-tap-[move]-tap-[move]-tap-tap-[swipe], where [move] denotes moving the finger off the screen for some minimal distance in any direction (possibly corresponding to the keypad, if that helps the user), and [swipe] denotes swiping the finger on the screen, again for some minimal distance in any direction.


Taking even the dashes out of Morse!
(Original source: flickr.com; Font: fontspace.com)


Obviously, this would then mean that a multi-tap sequence becomes a one-to-many mapping, from a one-to-one. "kite", among other words, would have the same sequence as "home". It is easily seen that there are in practice only slightly more than 3n unique sequences available to cater for all words of length n. For n=4, that would be barely more than eighty.

First, the bad news. There are clearly far more than eighty four-letter words (Mr. Ham can rattle off that many impolite ones without thinking) - common dictionaries tend to list at least around 2000 of them, though this is thankfully still far less than the over 450000 possible theoretically.

Next, the slightly better news. In general, language models follow Zipf's Law, which states that the frequency of a word will be approximately inversely proportional to its rank, i.e. the second most common word will only be seen about half as often as the most common one, and even the tenth most common word will be seen only 10% as often; if this law holds, then even with 2000 possible four-letter words, a mere 34 of them will comprise half of all observations, a magnitude bearing far more resemblance to the number of available sequences.

The situation improves further with more letters - while the most common word length in dictionaries seems to be about nine, there would be about 20000 unique sequences to describe words of that length, whereas even generously assuming 64000 possible nine-letter words would imply that just 190 of them would comprise half of all observations - a tiny fraction of the available space! [N.B. As a rule, the longer the word, the easier it is for a predictive algorithm to fill in, despite it appearing more impressive at first to guess a huge word than a short one - watch out for this in promo videos]


Word count stats from the Normal and Reverse English Word List


So, the major challenge remains with recognizing shorter words correctly, and unfortunately (but fortunately for texters), short words are quite common - the average length of an English word in actual usage is about five (but it depends). Apparently, we need more data - can we get it?

Happily, yes, and as it happens all links lead to Google. Back in 2006, they released a one trillion word corpus, following the dictum of data is king, which completely dwarfs the Gutenberg (~10k words) and Jones (from ~100 million words) corpora we have tried. Put into perspective, it's as if each word in Jones was multiplied by each word in Gutenberg.

Among other yummy data, it has a complete list of bigram (all 676) and trigram (all 17576) frequencies, with even the least common bigram ("jq" here) appearing nearly three million times! The differences are minor as expected, though there is a maximum disagreement of over 900% (for "qi") in relative frequencies and "in" (2.02%, from 2.36% in Jones) overtakes "th" (2.00%, from 3.02%) as the most popular bigram, as 94% of the bigrams differ by less than 50%.


Mr. Ham isn't too big on spellcheck
(Original source: wikimedia.org)


Mr. Ham: *rushing in* No! No trigrams!

Me: *sighs* What is it this time, Mr. Ham?

Mr. Ham: Have you heard what they are saying about us? "The hamster is greedy as well as cowardly; it has five skills but all are inferior". Well I never! Esquire Pants will take the progenitors of such libel for every last penny they've got! Where is the justified outrage when you need it?

Me: Ignore him.

Mr. Ham: And did you know they borrowed the whole thing from Morse code? If you take the first eight trigrams you get "owkugrds", an anagram of "gud works", clearly an inside joke, as my lecturer told us in HIT!

Mr. Robo: I'm impressed! You were at the Hamster Institute of Technology?

Mr. Ham: What? No, no, it's HIT101, a course where we learnt how to solve problems by hitting them, again and again, until they are rectified. One of my favourites, got an A in it.

Mr. Robo: ...You're right. I should have ignored him.



So back to the tapping. With a single tap before a space, we might suspect that it almost certainly means "a". Two taps is more complicated, with "b", "k", "u" and to a lesser extent "e" all used in texting shorthand, while three taps has two main challengers, "c and "i. On to two letter words, with the most popular 333333 words of the Trillion Word corpus (henceforth, 333333-T) as the dictionary:

1234
1 [5.55%]
at - 50.92% (50.92%)
pm - 13.55% (64.47%)
am - 12.92% (77.39%)
ad - 1.77% (79.16%)
pa - 1.40% (80.56%)
[5.53%]
an - 34.16% (34.16%)
we - 31.29% (65.45%)
me - 12.75% (78.20%)
de - 7.08% (85.28%)
tx - 1.36% (86.64%)
[19.70%]
to - 76.60% (76.60%)
my - 6.69% (83.28%)
do - 6.00% (89.28%)
go - 2.66% (91.94%)
tv - 1.01% (92.95%)
[3.05%]
as - 91.59% (91.59%)
ms - 2.79% (94.37%)
az - 2.00% (96.37%)
ds - 0.88% (97.25%)
ps - 0.83% (98.08%)
2 [2.14%]
up - 48.27% (48.27%)
et - 6.06% (54.33%)
hp - 3.82% (58.15%)
eg - 3.76% (61.90%)
ed - 3.01% (64.91%)
[4.99%]
be - 59.78% (59.78%)
he - 21.00% (80.78%)
uk - 5.80% (86.58%)
en - 2.31% (88.90%)
un - 1.21% (90.11%)
[6.14%]
by - 67.84% (67.84%)
no - 18.98% (86.81%)
ny - 1.54% (88.35%)
hi - 1.37% (89.72%)
el - 1.20% (90.92%)
[1.69%]
us - 90.58% (90.58%)
es - 2.30% (92.87%)
ks - 1.30% (94.17%)
nz - 1.14% (95.31%)
ns - 0.98% (96.29%)
3 [5.12%]
it - 68.32% (68.32%)
cd - 4.64% (72.95%)
la - 3.84% (76.79%)
ca - 3.17% (79.95%)
id - 2.91% (82.87%)
[16.44%]
in - 64.06% (64.06%)
on - 28.37% (92.43%)
re - 3.26% (95.69%)
oh - 0.61% (96.31%)
ok - 0.52% (96.83%)
[22.10%]
of - 73.99% (73.99%)
or - 14.57% (88.56%)
if - 6.38% (94.94%)
ii - 0.75% (95.69%)
co - 0.64% (96.34%)
[6.09%]
is - 96.09% (96.09%)
os - 0.91% (97.00%)
vs - 0.76% (97.76%)
oz - 0.61% (98.36%)
rs - 0.57% (98.94%)
4 [0.31%]
st - 41.23% (41.23%)
sa - 14.96% (56.19%)
sd - 11.55% (67.74%)
sp - 9.36% (77.10%)
sw - 7.11% (84.22%)
[0.15%]
se - 33.20% (33.20%)
su - 13.79% (46.98%)
sb - 11.28% (58.26%)
sh - 10.50% (68.76%)
sk - 6.22% (74.98%)
[0.97%]
so - 84.69% (84.69%)
sc - 5.14% (89.83%)
sf - 2.45% (92.28%)
si - 2.42% (94.71%)
sr - 2.07% (96.78%)
[0.04%]
ss - 75.69% (75.69%)
sz - 13.86% (89.55%)
zz - 7.45% (97.00%)
zs - 3.00% (100.00%)


For each tap sequence, the top five corresponding words are shown, with individual probabilities, and cumulative probabilities in brackets. It can be seen that for almost all tap sequences of length two, the most probable translation is at least twice as likely as the second most probable one. The glaring outlier is "12", which is almost as likely to mean "we" as "an", with "me" quite plausible too. Further, just the top five options will suffice for prediction at least 65% of the time, with "21" the most ambiguous in this respect.

This applies also to the distribution of the tap sequences themselves, with three of them, "33" (of, or, if...), "13" (to, my, do, go...) and "32" (in, on, re, oh, ok...) making up more than half of all tap sequences of length two (though one might suspect that a specialized texting dictionary would put "ok" at higher than just 0.52%). As a crude measure of serviceability, the top option will be correct 66.06% of the time, with a standard deviation of 19.49.

LengthMeanStddevWordsSeqsRatio
266.06%19.496761642.25
347.75%24.281297764202.77
448.78%22.3431140256121.64
557.20%25.303993394342.35
664.83%25.7149040302816.20
772.99%24.955011782866.05
882.71%21.7544551170872.61
991.49%16.2435447232991.52
1096.32%11.0626100219201.19


As foreshadowed, prediction becomes surer the more letters there are - with three letters, over 12000 words have to squeeze into just 64 sequences, a ratio of over 200 words per sequence, while for ten letters, the 26100 words fit into 21920 sequences, or 1.19 words to a sequence, many of which can be attributed to forms of the same word taking suffixes like "le" and "ly", which transform to the same sequence.

Unfortunately, we suspect that many text messages are, indeed, short with short words, and therefore many more inferences have to be made, and/or a custom dictionary slowly built up. For example, the sequence "2121" has a raw 49.1% probability of being "hand" from the corpus, and just 1.71% of being "haha", though in the texting context, "haha" should probably be the far better bet if it were the first word.

There are a couple of ways out of this. The first would be to simply revert to using directionality information by keeping an estimate of the user's vision of the keypad. One standard approach would be the iterative one, where the starting grid-based model is re-estimated as input comes in, and updated by estimating its accuracy online with further input. This is the approach taken by Findlater and Wobbrock in their recent 2012 paper, though that is targeted more towards two-handed normal-sized virtual keyboards.

The other would be to to use more corpora information. Consider two phrases with identical tap sequences, "I bet him at" and "I met him at" - it seems that the second should be the right interpretation nearly all of the time, but how can this be substantiated? Well, we might note that the former only returns about 700 thousand results on Google (which might be thought of as the biggest corpus on Earth), while the latter returns 11.3 million results.

This does however require a reliable, fast Internet connection (or incredible advances in storage) to be feasible even with the number of phrasal candidates winnowed down with various algorithms, and therefore might be a little ahead of its time.

One possible adaptation would then be randomized sampling, where the probabilities are approximated using word pairs within some distance. For example, if "win" were to appear soon after the phrase, we might think "bet" more likely, in the hope of learning from enough weak hypotheses (think Adaboost). Explorations along this line will have to wait, though, as Mr. Robo moves on to his next, more promising work, born after some fruitful discussion with yours truly.


One Move Ahead

One observation made is that currently popular virtual keyboards incorporate probability information, but tend to correct after the fact, as demonstrated last week. In a way, they might be thought of as adjusting the size of the keys behind-the-scenes if the noise modelling is not discrete, which Gunawardana et al. explain in a 2010 paper.

Now, obscuring the input mechanism goes against the WYSIWYG principle and may lead to frustrated users trying to second-guess the system, which some are better at than others. The obvious-as-dirt extension is to actually reflect the increased size of keys visually, which many authors have indeed suggested over the years under different names - BigKey, CATKey, FloodKey and SpreadKey, among others, whether by prior customization or active prediction.

However, we believe that we have some novel contributions - let us get this out of the way first. Unlike BigKey, there is no fixed bound on the number of suggestions, and there is no occulsion. Unlike FloodKey, adjustments are made in a regimented manner instead of utilizing a less-structured Voronoi diagram, thereby retaining a cleaner interface and restricting visual search by the user along one fixed dimension (the rows), which is also not obeyed in SpreadKey.

The basic idea remains that over the course of typing, letters can be predicted, and as a consequence precious space on small touchscreen keyboards can be safely reallocated from unlikely keys to likelier ones. How well can predictions be made? Well, in the spirit of the tap sequence analysis above...


Mr. Ham: Wait! Here's a napkin, do your calculations there.

Mr. Robo: Huh?

Mr. Ham: I tell you, this is a must - nobody ever accomplished anything great on letter-sized paper in all of the movies and television shows that I've watched! Look, at the minimum, use the back of this envelope, I carry a stack of them around nowadays just in case.


It's slightly used, but I'm sure there's enough room left
(Source: flickr.com)


Mr. Robo: Get thee away from me!

How large should the keys become ideally? A relevant study back in 2006 suggested that keys about 0.92cm each side would be optimal. Touchscreen research goes far further back, though, and a review by Sears et. al back in 1992 reports a consensus of about 2.2cm a side for two-handed input, and unsurprisingly notes a falloff in accuracy and slowdown in typing speed with decreasing key size.

More recently, Apple's iOS guidelines suggest a minimum of 44 pixels square for each item, which translates to about 0.71cm, or some 58% larger than our 0.4cm-wide Android keys. Personally, I almost always miss to the left or right only, and would further suspect that this width is dangerously close to where accuracy falls off into unusable territory, but filler empirical tests will have to wait. Either way, the conclusion seems inescapable - bigger equals good.


Mr. Robo: *looks around* Is Mr. Ham gone?

Me: Looks like it.

Mr. Robo: Okay, continuing...


The newly-available trigram data further allows us to get an idea of how greatly a letter can affect the probability of the second letter after it. It can first be noted that the bigram count is always greater then the combined trigram count with that bigram as prefix, indicating that there are unaccounted-for trigrams involving punctuation - this does seem more common with the less-popular bigrams, though, with "hz" not followed by a letter about 57% of the time, for instance.

We can quantify the value added by noting that in a pure bigram model, the probability of a three-character string xyz has to be estimated as P(xy)*P(yz), whereas with trigram data, P(xyz) is given directly. These values can be starkly different - while "tr" (0.40%) and "rt" (0.47%) are fairly common bigrams, their combination "trt" occurs only 0.0002% of the time in reality, ten times less than what we might expect from multiplying bigram probabilities.

Put another way, in a pure bigram model, our expectation of receiving a "t" following "tr" is exactly that of receiving a "t" after an "r", which is P(rt)/[P(ra)+P(rb)+...+P(rz)]=0.070, i.e. more likely than the average letter. However, with a trigram model, this is refined to P(trt)/[P(tra)+...+P(trz)]=0.00044, which is far more in keeping with reality.

There is, of course, nothing to stop us from generating quadgrams, quingrams, etc from the corpus, excepting storage space concerns, since single-character lookup time should be constant. As a precomputed optimized table would require just one byte for each n-gram (probabilities stored at about 0.4% resolution using that byte; memory address computed on the fly), a full quadgram table would take up just 0.5MB and a quingram table, 12MB, which should still be within acceptable download sizes even for mobile apps.

More quantification, using n-gram data inferred from the 333333-T corpus (excluding words with non-letter characters), and used to predict the same; note that there are necessarily always more (n-1)-grams than n-grams for every n, with some 2.16 million individual bigrams, but only about 1.17 million quingrams:



As is expected, with more information about the preceding letters, the confidence of guessing the next letter increases assuming a fixed lexicon. Knowing only the immediately preceding letter (a bigram model) gives only about 20% confidence on average for predicting the current letter, but knowing four preceding letters (a quingram model) raises this confidence to over 70%!

Additionally, even using just a bigram model, the most likely 13 letters account for 93.63% of usage, which strongly suggests that we can increase the display size of around half the letters, and be quite confident of helping the user, and this rises to 97.04% with a trigram model. The reality is for once probably even more promising, since the 333333-T corpus appears not to have been winnowed for misspellings.

A minor obstacle would be that the keyboard rows are not utilized equally - the top row is used about 46% (333333-T) to 52% (Concise Oxford) of the time, the middle row some 35%, and the bottom row just 15% to 19%, which can however be partially explained by the different number of letters on each row; still, crowding should not be a huge issue, with the most probable predicted letters seldom clustering - with the trigram model, having all top five predictions on the same row occurs only about 0.6% of the time, with an about 77% chance that at most three of them are on the same row.

Now, the nasty question - what about those rare occasions where the user actually wants to input an unlikely letter (e.g. some proper names, codewords)? There are quite a few ways of resolving this, but we shall reserve what we think as the best one for now, and present another idea: for the cases where the desired key is shrunk, we can use a drag-selection system, where the user drags his finger across the row and gets the secondary keys highlighted. These keys can then be selected by releasing then, but this should be rare.

But enough of the yakking, behold, the prototype:



[N.B. An earlier attempt with keys resizing more aggressively was abandoned, since additional effort was required to search for keys which may have moved some distance from their standard position]

As can be seen, the keys have become far larger, with the most likely primary letters in white; each of these letters occupy a space at least 50% wider than the default, often much larger, making them easier to hit. The less likely letters are in grey, and as mentioned can be selected by dragging and releasing a finger (mouse here) when over them.

The current procedure is as follows: using quadgram information (including spaces, computed from scratch from the 333333-T corpus), the probability of the next letter is retrieved. Then, from most to least likely, the letters are assigned as primary if and only if the primary letters thus far do not together comprise over 99% of the probability, and the addition of this primary letter will not form a sequence of three primary letters (since that would mean that the middle letter would not have space to grow)


Me: Well, it's not perfect, but might get some love; even the top keyboard apps tend to have about 10% of users rating them as one-star, can't please everyone. About the name...

Mr. Robo: Oh, Mr. Ham has already taken care of that.

Me: What? Why?

Mr. Robo: Well, he was so enthusiastic about his suggestion - positively grinning from ear to ear - and it sounded rather appropriate, "reflecting the underlying technology", as he said...

Me: I'm prepared for the worst.

Mr. Ham: *pops up* Presenting...



Me: No, just no.

Mr. Ham: It's too late, I've printed all the publicity material!

Mr. Robo: Actually, is it wise to expose the idea just like this?

Me: Well, as is so often heard, ideas are cheap, execution is everything; one might be surprised to discover how often an app is panned simply because it doesn't provide pretty skins. In any case, I'm not particularly short on ideas.

Would it be that these days of dread bringing me ever closer to what I am extremely unwilling to see happen be over, such that my darkness might lift, and yet I would have time stop instead. Ah, what will be, will be. Back to other research.



comments (0) - email - share - print - direct link
trackbacks (2) - trackback url

Back to top

Wednesday, July 25, 2012 - 02:28 SGT
Posted By: Gilbert

Least Publishable Unit

Mr. Robo's keyboard development has unfortunately hit a snag or two, but the combined writeup was getting a bit long even by usual standards; I thus figured that the mostly-unrelated first half might as well go out by itself:


Mr. Robo's Mailbox

A statement has recently arrived from a fellow academic ham, hailing from another field, but without supplied proof:

Hamming distance; if there are n binary switches, then given any point x in the n representational space, i.e. any random representation of switch states, most of the space lies d=n/2 bits away from x.

Mr. Robo's opinion is to respectfully disagree. Let S(x,d) be some arrangement of n switches that lie a distance d bits away from some point (valid arrangement) x. Then let x0 be the arrangement where all n switches are off (or zero), for simplicity. The Hamming distance of any arrangement of length n from x0 is then exactly the number of switches that are on (or one) in that arrangement.

Consider now some random arrangement xA that lies more than d bits away from x) in the Hamming distance metric, i.e. has over n/2 switches that are on. Then by symmetry, every xA uniquely corresponds to another random arrangement (n-d) bits from x, which is obtained by flipping the bits.

Then, if n is odd, the number of possible Hamming distances is even, corresponding to the integers between 0 and n inclusive. Since the number of arrangements of distance (n/2)-1 or less is exactly equal to that of distance (n/2)+1 or more, the statement does not seem to hold in its given formulation. Consider the concrete example of n=3 and its eight possible arrangements: H0(000)<->H3(111) and H1(001,010,100)<->H2(110,101,011), with half the space lying a distance of 1<1.5=n/2 or fewer bits away from x0.

Of course, this may just be a quibble after all - the statement would be true if the terminology were adjusted to refer to the remaining space (not including x itself), which may have been implicitly assumed to be understood; Mr. Robo can however be anal in these matters, given how little power he has in other respects. Please do understand. He does also take the opportunity to apologize for a prior oversight.


By The Shades

Coming across the most recent fiction bestseller list of perhaps the preeminent broadsheet in the world, I was taken slightly aback by the novel of the times being basically about a lady getting with an asshole, whose main redeeming factor is being stupidly rich (if still creepy, but with refined style - important!); lest this be dismissed as a fluke, it's been a fixture on the list for five months, and if that were not enough, Number Two and Number Three are its sequels.

It gets no better. Continuing down the absolute pinnacle of contemporary literature by consensus of the paying public, the top non-Shades book has the leading man being a doubtlessly dapper vampire geneticist, and then proudly features, in no particular order and four-fifths by female authors (and devoured by, I strongly suspect, female readers):

  • An excitingly rugged New York detective who has also adopted ten kids; (we'll begin with the benign fantasies)
  • A lady who runs out on her wedding to find an exciting new man; (also recommended: Eat, Pray, Love)
  • A lady who considers an exciting year-long sham marriage for (enough) money; (also recommended: Indecent Proposal, the Playboy Mansion)
  • A lady who may have been murdered by her husband (but he was probably exciting, so it was worth it);
  • Yet more sympathetic lady protagonists who go for... exciting mates; the poor, poor things.
  • The Shades trilogy in one convenient bundle of exciting wealthy mysterious asshole concentrate;
  • One of the greatest Presidents of all time, who emancipated entire peoples, reduced to an exciting wannabe Buffy racing about in tophat and tails cleaving B-list vampires with an axe; (at least it's only 28th)
  • And by far the worst of all, "...a Midwestern matron... experiencing a feminist awakening."


Sadly, he lost his re-election bid to a ripped werewolf
(Source: geekpeeks.com)


This clear signal of preferences and reaffirmation of Ham-Bag Theory has led to what can only be compared to grave desecration, as venerable centuries-old classics are coerced - weeping and battered - into "new-generation reimaginings". As I look into the skies above, I am saddened by the realisation that this must indeed be the end of days.

Even if all falls apart, however, my calling remains, and one of today's questions is - how many shades of grey are there really? It pains me to report that fifty may in actuality not be too far off, from just-noticeable difference in the Lab colour space (giving ~43). More in-depth answers exist but do not disagree by too much, ranging from about 30 to 60, to about a hundred, and in any case the human eye is fooled easily.

Colour theory, so prevalent in image processing, does get applied when coordinating a wardrobe, a task which I accepted for the first time ever with the ongoing Great Singapore Sale and online retailers. Although academics are generally not known for their predilection for dressing well, I suppose it's not too much against the norms to give it a go, especially in the stickler for formality that is Japan. All knowledge does, in the end, flow into the same stream.

While I'm on the subject of appearances, The New Paper on Sunday has just revealed that, gasp, many bodybuilders here are using steroids, following Today's call for the SNOC to send a strong anti-doping signal. Well, this may still be understandable in endeavours like cycling, where the more innocent might reasonably hold on to hopes that some of their champions are drug-free, but competitive bodybuilding?!

Without naming any names, the most desultory search throws up physiques of such muscular development that it is difficult to imagine their owners not having, ahem, ridden a bicycle if they have not yet put in decades of work, further reinforced by the wink-wink nudge-nudge going on in forums dedicated to the lifestyle; you know, when a sport finds it necessary to hold events explicitly for natural practitioners, it may be time to drop the pretense and just come clean and do it openly.

Still, when it comes to cosmetic makeovers, the South Koreans are but rank amateurs compared to the media here. Recall my doubt in January when the pain of the upper crust was trumpeted under the subheading "Well-off bear biggest brunt of the price increases, figures show". Well, ok, whoever's in charge has the prerogative of kneading them figures, but when it becomes impossible to gloss over the reality that poorer folks get hit harder by rising prices using artistic statistics, that fact gets buried so deep that it doesn't even appear in the preview. Woffles would be proud.

Oh, and it seems that professionals have to give up their rights to creative expression (unless you're on the right side of the tracks) and medical confidentiality here. A vibrant city - but all the moves must be choreographed.


Almost There





comments (0) - email - share - print - direct link
trackbacks (2) - trackback url

Back to top

Wednesday, July 18, 2012 - 02:34 SGT
Posted By: Gilbert

Robo Goes App

As my main line of research has gotten a little bogged down, I resolved to clear my mind by applying it to a new challenge, inspired by how #%*@! frustrating entering even relatively short sentences on a smartphone virtual keyboard can be.

A few first measurements: the HTC One V's screen is approximately 4.8cm by 8cm, but with only about 6.8cm of the length available for icons; this works out to 2.04 square cm at a maximum for each of the sixteen icon slots, which is not all that much to begin with (whip out a ruler and take a look). As unappealing as that is, the size of individual keys on the default virtual keyboard is far worse - just 0.4cm by 0.8cm each, or just 0.32 square cm.

Now, let us face it, mashing keys that tiny with any sort of speed and accuracy and without any tactile feedback is a right chore; whatever else one might say about traditional handphones, their raised keys at least made multitasking input possible, which has moreover brought some measure of fame to our nation. Sure, it still can't quite match up to a real keyboard (41 seconds for 160 characters [or 32 words using the standard five-character-per-word translation], making it only about a third as fast as the best typists), but it could be done. Such feats are no longer possible... or are they?


Fast or correct; choose one
(Source: damnyouautocorrect.com)


Given the ubiquity of smartphones nowadays (around a billion exist either now or in a few years, depending on who you listen to), any way to input data more quickly (and comprehensibly) onto them must have enormous potential market upside, both for the creator of the method and the platforms that adopt it - and these miserable 0.32 square centimetre things are the best we have?

Examining the currently-available options:

  1. Voice-to-text
    (e.g. Default speech-to-text, Vlingo, etc)

    I haven't tried it myself, but I'm sure that most will agree that it has its inherent limitations, earning a reputation for talking to oneself among them.

  2. Bigger keys
    (e.g. Big Buttons, Cellular, etc)

    Pros: The most straightforward approach.

    Cons: Layout may no longer be QWERTY-standard, obscures more of the underlying app.

  3. Predictive
    (e.g. SwiftKey [demo], A.I.type, etc)

    These focus on predicting subsequent words, so that the frustrating tapping of individual keys is no longer that necessary.

    Pros: It does help, so much so that the Android 4.0 default keyboard works almost like that (well, not quite, since SwiftKey learns very deeply indeed), with three suggestions shown for each input, and they're the top paid app on Google Play.

    Cons: Still have to look at the screen while typing. Depends on user's texting patterns staying mostly constant over time (which is probably true), which does not carry over to new or shared devices. Privacy concerns as personal history is mined.

  4. Swiping
    (e.g. Swype [demo], SlideIT, etc)

    With these, the user swipes his finger over the letters making up a word without having to raise it. There is some overlap with predictive types, since some paths travelled can have multiple interpretations.

    Pros: No tapping required, fast.

    Cons: Again, have to look at the screen. Also, Swype for one seems to be pursuing a strategy of getting itself preinstalled as the default (going for broke?)

  5. Custom
    (e.g. MessagEase, 8pen, etc)

    The traditional keyboard layout is dispensed with.

    Pros: Potentially very fast - may not have to look at the screen.

    Cons: Steep learning curve - how many Dvorak users are there? Similar (if reduced) problem of portability if most devices don't come with the app. Indeed, MessagEase has been around for some time but not quite caught on.

  6. Blind Typing
    (e.g. BlindType [demo])

    Pros: Ah, finally a method that does not presume that users want to look at the screen! Note that it's not particularly new, having been bought by Google in October 2010. Despite that, however, it appears to have mostly vanished.

    Cons: Can't take advantage of predictive input when typing blind - but that's no reason not to offer this option, if nothing as a secondary option. Phones with front-facing cameras might then offer predictions when it detects the user looking at the screen. Some phones, anyway (ahem)


For the following explorations, Mr. Robo has gathered some resources. The full bigram statistics are gathered from the supplementary material to "Case-sensitive letter and bigram frequency counts from large-scale English corpora" (Jones, 2004, maybe free to access someday?), Usenet column. The statistics on the ten thousand most popular English words (making up 80.59% of all word occurances) were gathered from the Project Gutenberg list on Wiktionary, and while slightly dated should be good enough for our demonstrations.

While we have messed about with bigrams here before, a complete overview has yet to be presented. This deficiency shall be made up now:


All bigram frequencies
Each row represents the bigrams starting with the same letter;
the darker the green, the more often the second letter follows the first.
Note "ju" and "qu", of especial interest to Scrabble players,
as well as the columns corresponding to vowels.


Notably, bigram statistics inferred from the Gutenberg corpus have far less detail than Jones', with a full 221 of the 676 bigrams not represented at all in the 10000 words, though it should be said that a similar proportion of Jones' bigrams have negligible counts (<0.005%), with "qz" taking the prize for rarest bigram. This discrepancy may underline the need for a truly comprehensive corpus in production apps.

It should also be called to attention that the highly-popular "th" occurs more than twice as often in practice as a small corpus might suggest (1.52%), making up 4.56% in Gutenberg and 3.01% in Jones' Usenet count. This might be attributable to the small corpus not taking into account the relative frequencies of the words contained within.

So might this information be exploited for autocorrection? Quite possibly. We can cast input as a classical noisy model, where the user's actual intention may not be captured properly by the touchscreen. While actual readings are more complex, involving irregular shapes, we simplify each touch to produce a circular margin of error, with the screen then randomly picking any point within the circle. To reflect rapid typing being less precise, I together with Mr. Robo have further set this margin of error to diminish over time to some minimum in the simulation to follow.


But first, some intro music

Reverse Hamgineering

But how then is correction of text achieved? While we do not pretend to replicate current professional implementations, we believe that some basics are sufficient for a workable demo, for which only two kinds of probabilities need be considered:

  1. Bigram probability

    As just seen, many bigrams have an extremely small chance of appearing in intended text - how often do, say, "sx", "ih" or "wk" occur in proper English? Therefore, these bigrams should be weighted against when they are input.

  2. Spatial probability

    Here, we assume that the user generally does not miss his intended key by too far; mistyping "s" as "a" is not too uncommon, but mistyping it as "k", all the way to the other end of the keyboard, should be very rare especially given the one-fingered pecking style generally used with smartphones.

The theory then is very simple. Consider a hasty, fat-fingered user inputting "yhud", which can reasonably be assumed not to be what he actually intends, unless he has just fallen down a flight of stairs and wants to describe the sound made.

When the first letter is entered, we do not a priori have reason to suspect it is not correct, since single letters all have non-negligible probabilities of appearing - the user might well intend to begin his word with "y", yes, y not?

However, once the second letter is entered, we do have a much better idea of what is going on. "yh" happens to be seen very infrequently - about 0.002% of the time only, to be exact. We might then try to find more plausible alternatives, and "th", as it happens, has a far greater 3.01% probability.

But is "th" in fact acceptable? Well, "t" is right next to "y" on the keyboard, and we may apply a small probability, say 10%, that a received "y" is meant as a "t", instead of a 70% probability of actually being "y". With this, the joint probability of "th" becomes 0.1*0.0301=0.00301, which is still much bigger than the 0.7*0.00002=0.000014 of "yh".

This idea can be extended to longer strings by basic dynamic programming, and as a finishing step, the most probable candidates obtained after this can be polished up with a dictionary, since bigrams represent only extremely local information. The live Javascript demo follows - to use it, center the green circle over the intended letter and click, and errors simulating the fat finger effect will be introduced automatically.



The demo is, of course, limited - for one, it uses only a static and slightly archaic 10000-word dictionary, so good luck trying to correct for words like "processor". Also, it was designed only to check with words of the same length as the input, instead of predicting. For example, the input "th" gives alternatives "ty" and "ti", which while reasonable guesses are probably inferior to offering "the" and "this". Incorporating such predictions is not that difficult - just one more layer of probabilities - and is left as an exercise to the reader.


Blindly Hammering Away

Now, this is old news, and I gather the autocorrect in some word processors may do something like this. What about some of the more exciting newer inventions? Take blind typing: how can a user just press at approximate positions, perhaps not even on any keys, and get his word correctly predicted?

While we have no idea how the makers of BlindType and the like really do it in their apps, we can offer at least one suggestion. Note that even when a user is typing without looking, assuming he has memorized the QWERTY keyboard layout (not too unlikely for most), there are still certain invariants that can be exploited.

Let us say that he touches some roughly central point - then, if we assume he is blind-typing, we cannot guess what letter that represents with any confidence. However, say that he then presses a point at a roughly four o'clock position, down and to the right of the original point. This immediately tells us that the second point is probably not on the top row, and also that the first point is then probably not on the bottom row.

As the user continues marking more points, assuming that his internal vision of the keyboard is roughly correct, we can thereby get an increasingly better idea of what he is trying to input. For example, consider the word "this" again. It has four letters, and therefore three moves: "t" to "h", "h" to "i" and "i" to "s". Each of these moves can be represented by an angle, or bearing, for which we follow standard mathematical practice of zero degrees to due east, and going counter-clockwise. Then, the bearings are 311°, 47° and 197°.

It is easy to see that every word has a corresponding bearing signature; then, assuming that the user has touched the screen a correct number of times (as many as there are letters), it remains only to match the signature he has generated with a dictionary of precomputed signatures. There are of course many minor enhancements and considerations, such as having near-enough touches assumed to be the same letter, but this is the gist of it.



The algorithm may be tested with the prototype above. The three closest matches will be displayed once two or more clicks (touches) are made. The efficacy of typing blind can be tested by clicking the "Do it Blind!" button, which removes the keyboard display. You should note that it is not necessary to click anywhere near the actual keys for good predictions to be made - as long as the angles are right, large movements are not required.

Clearly, this method does have its limitations too. For one, many words (particularly shorter ones) may share very similar signatures, in particular those with letters all on the same row, such as "try" - currently, it is mispredicted as "has", since we consider only the angles, and not the relative distances, for now. This should however be a fairly trivial fix to add. Have a try?

A bigger issue for blind typing is that the top prediction should be very highly accurate, since the user is assumed to continue typing new words without stopping to correct them. Therefore, probability considerations at the word and sentence level should be a given, in actual products.

Finally, it can be observed that this idea can be adapted to swipe-type input; the problem is complicated by there not being distinct touches to indicate the number of letters, but this is mitigated by being able to rely on actual key positions once more. Some letters can then be distinguished by a change in direction of the swiping motion, and the trick then would be to decide which letters to keep when they are passed over in a straight line - for example, "pit" and "pot" would result in exactly the same path traced, so again additional context has to be used to distinguish them.

Mr. Robo has informed me that he has a couple of promising new methods for keyboard input, which however will take a bit more time to come to fruition. More to look forward to for the weekend!



comments (0) - email - share - print - direct link
trackbacks (3) - trackback url

Back to top

Monday, July 16, 2012 - 00:09 SGT
Posted By: Gilbert

Getting Phoney

I will be the first to admit that I have not been keeping up with smartphone trends - computer science is no more about (extra-small) computers than astronomy is about telescopes, after all - but after realising that I had been eligible to recontract my mobile line for over a year, and that this meant that I could get one for next to nothing and at no increase in my monthly phone bill (after booting autoroaming and voicemail), I figured that it was time to hop on.

So what should be my first smartphone? My uncle and cousin have apparently been bitten by the iPhone bug, though the latter did have good things to say about the Nokia Lumia, and my brother got a Galaxy Note that's the size of a small tablet.

I quickly cobbled together a short list of requirements:


On to check out the available goods: of the free options with Singtel's basic 3G Flexi Lite plan, the Nokia 603 is on Symbian, but is out of stock anyway, while the Sony Xperia Neo V fitted most of the bill, but had just 320MB of internal memory, which was a concern from what I had heard about apps. Samsung's Galaxy line had a couple of pretty attractive offerings, but I eventually settled on the HTC One V for S$48, with it coming with the latest version of Android and generous purported standby time tilting me towards it.

The transaction was fully online - having recontracted (with email copies of legal forms) and paid through SingTelshop on Thursday afternoon, a lad came over to my place on Friday afternoon to deliver the phone; it's almost a wonder how knickknacks get sold in brick-and-mortar stores nowadays, with rock-bottom prices and free delivery widespread.

[N.B. This was later confirmed on a detour to Sim Lim Square before a family dinner for a 32GB microSD card (available on Qoo100, or the former Gmarket among other online retailers, but I didn't want to wait), where I had the most befitting ice cream sandwich of my life (and not a moment too soon); offhand, the retailers couldn't quite compete on price or variety, especially on the smaller purchases. 3G surfing was iffy at Bugis Junction, but the GPS worked swell.]


In very appropriate minimalist packaging


Not having touched a smartphone previously (ok, perhaps on a few occasions), I spent the evening figuring things out. While sliding stuff about felt nifty, the setup procedure reinforced my suspicions that inputting text would be a pain (and I don't consider myself to have particularly thick fingertips). Connecting to my router's Wi-Fi did work like a charm.

The simplification of required extras was also very well received, with a single standard microUSB connector handling everything from power (with a compact power transformer, unlike the old days) to data transfer, and all at once! Goodbye forever, old blocky one-use-only power adapters!

My complete newbie self was horrified at the lack of screen real estate, which had space for only 16 icons, after discovering that widgets could be removed by holding a finger down on them, and added by holding down on an empty spot. Happily, I next realised that there were five available screens, accessible by sliding horizontally. Oh, and after searching in vain for a display off/sleep icon, it hit me that that was what the power button was for. Oops.

Pity about how the screen is a fingerprint magnet (not that the iPhone's vaunted oleophobic technology works that well either, from observation), but that should be partly fixed with a good protector (to be obtained); can't knock the glass, which happens to be a happy accident, otherwise. This doesn't affect operation at all, since the smudges are invisible when the screen is lit, but it's still unsightly nevertheless.


Background picture soon changed by sponsor Mr. Ham


Being a cellphone at heart, though, it still needs a contact list to be useful, and I got mine onto it by exporting to CSV from Nokia PC Suite (and culling those contacts for which I had no recollection of), before transferring to Google Contacts (which did a good job of merging duplicates), which was seamlessly integrated with the One V. Too bad about the tons of Facebook duplicates, but it seems that designers nowadays expect users to search for contacts instead of scrolling anyway.

I was taken slightly aback at how tightly services are inter-connected nowadays (as one petty thief discovered to his detriment - this phone does automatically store photos onto Dropbox too), when snooping about for useful apps - apps can be pushed to a phone after being selected from the store, just like that! Okay, I'm an old fogey.

Downloaded WhatsApp (of course), as well as some utilities such as file, storage and battery tools, as well as Chrome and Translate. Shifting it all over to the 32GB SD card, after watching the 2GB free gift fill up at an alarming pace with my music collection, was done by cloning the latter to the PC (a de facto backup) before restoring it to the former (and resizing the resulting partition)

It should be mentioned that the phone came with ribbon earbuds, which while less tangly (though still no match for the dedicated solutions), weren't too comfortable - but for an optional extra, I'm not complaining. It's kind of hard to wind one's head around how smartphones full so many roles nowadays - phone, music player, camera, watch, GPS, personal organizer... did it all start when Jobs looked at an iPod and wondered, hey, why can't I make calls from this?

On the whole, I'm quite chuffed with the phone, and if I had to nitpick it would be the abrupt stop-starting of music as notifications come in, as well as widgets being slow to update, but nothing that prevents it from doing all I expect it to. It may be time to delve into some app programming...


The Pattern Code

While fiddling about, I got to the security preference of setting a lock screen, and after looking through what was available, decided on a pattern lock. For those not in the know, this basically requires the user to trace a preset pattern to enable the phone to be used after some period of inactivity:


Obviously, this [1-6-3-2-5-7] is not my actual pattern


It was then natural to ask: what is the total number of possible valid patterns? Mr. Ham was very quick to rustle up an answer from StackExchange's Math/combinatorics section (which happens to correspond to an official integer sequence), but it turns out that it's not quite applicable for the implementation on my phone, which as can be seen allows diagonal moves as long as the path doesn't touch another node on the way. For example, numbering the nodes from left to right and then top to bottom, node 1 can connect to 2, 4, 5, 6 and 8. The only other rule is that each node can only be visited once, which limits the maximum sequence length to nine.

Mr. Robo, who had wisely hidden away, was therefore able to claim credit this time. After crunching the numbers, he reported that there are 139880 possible sequences - 1400 of (minimum allowable) length 4, 5328 of length 5, 16032 of length 6, 35328 of length 7, 49536 of length 8 and 32256 of length 9, or rather more than the 10000 combinations possible with four-digit PINs. He also confirmed the answer of 576 if only horizontal and vertical immediate neighbours are allowed, and believes that solutions for other rule variants can be swiftly obtained by modifying the linked Perl code.

[Errata 23 July 2012: This paper gives a figure of 389112, which turns out to be correct due to an understandable oversight - a special case exists where previously non-directly accessible nodes can be reached. For example, it was assumed that node 3 could never be reached directly from node 1, but this is in fact possible if the intervening node 2 was already used. Therefore, more sequences like 4-2-5-1-3, previously thought impossible, are possible. The updated code is offered.]

I suppose the restricted version could be solved by hand, but that might be cruel. Heck, even the FBI are not amused, though as it happens there may be a far simpler way to defeat this protection, as also noted on the StackExchange page. All the more reason to get a good screen protector.



comments (0) - email - share - print - direct link
trackbacks (4) - trackback url

Back to top

Tuesday, July 10, 2012 - 23:49 SGT
Posted By: Gilbert

- -
Groundwork

Despite my best efforts at antisocialism, in keeping with state ethos, there were still two classmates' weddings to be attended to over the weekend, which were made far more entertaining by the availability of an extremely friendly baby (also by a classmate) with a taste for table leavings (he was to be repeatedly denied)

Sunday morning was then spent on a community walk-a-jog, which was all that could be managed with the route clogged by a mass of humanity. The three kilometres therefore took twenty-odd minutes, and was perhaps not even that impressive given that I had probably trekked a longer distance in total on Friday, between meetings and a slightly inaccessible hotel ballroom.

After that, it was time to make arrangements for the conference trip and prepare the final version of the paper, which persistently struck me as being too simple, even accounting for familiarity. I eventually resolved to file these considerations away for next time, when a submission gets rejected (which may after all be slightly random)

At the same time, Mr. Ham begged leave to facilitate "transfer of personnel", and I was certainly not about to question a hamster flanked by dozens of wild-eyed fanatics. Meanwhile, Herr Ahm has noted by email correspondence that local luminaries have indeed begun to play nice, with one MP now knowing to say that simply piling on the people is not feasible, while her boss hastened to add that integration is a two-way street, after some lag time. Not only that, the casinos and death penalty have come under review - it's almost as if they read too much into Monsieur Jambon's ramblings!

Despite these promising developments, Herr Ahm was careful to reiterate that, especially in politics, talk is cheap (and intepretations, as to which verbs can be applied to which nouns, definitely inventive) - hard figures, then, should be kept in sight. He was also diplomatically non-committal on a domestic titan of investment taking out huge advertisements to proclaim loudly that it is, in fact, making money, quite sensibly pointing out that known cash-spinners like, say, Apple or Google never bother to hype up the fact.


Took time out for my sister's commencement too


It was therefore left to poor Mr. Robo to handle the grunt work. Before I go into his research, I should note that perhaps the harder part is sometimes not in the doing, but in the having others understand what is being done, i.e. the teaching. Often, when reading a paper, I cannot help but ask myself whether it has bothered to explain itself in the most approachable manner, even considering page limits.

Therefore, I attempt here to present Mr. Robo's results such that it is as widely accessible as possible, with as little prior knowledge or willingness to digest huge chunks of unbroken text assumed as possible.


The Task

Some research is theoretical, in which a model or method is proposed, and argued without reference to actual data (which to be fair may not yet be available) to be a good way of describing or handling a problem for which demand may or may not be existent. This is not that type of research.

I, together with Mr. Robo, and so says himself Mr. Ham, have been striving to make computers read embellished or distorted words known informally as CAPTCHAs for awhile now; a simple (mostly-)working template-matching system for input with lines struck through was detailed last November.

More recently, analysis has been done on 2000 independent samples of the industrial-strength Google CAPTCHA this May, with contributions by several laudable anonymous volunteers. Finally, a follow-up post last month described how the distortions used may be produced, and perhaps reversed.

Today's offerings are in a way a step back, but a necessary one; at the end, a CAPTCHA/word recognition system depends on being able to recognize individual characters (here, we ignore theoretically-possible but in practice less-seen holistic paradigms). Naturally, the success of the system rests heavily on how accurate these individual diagnoses are.


Mr. Robo's current workflow (Diagram by Dia)


But isn't learning this trivial, given how small text images can be? Not necessarily, as even a mere 20x20 image produces an input space of 400 dimensions, with 2400 possible configurations (far more with floating point representation), which as the chessboard story says, is already unimaginably huge. This is the famous curse of dimensionality issue in machine learning, basically the intuition that each additional dimension exponentially increases the number of options.


Example in just two dimensions, ten samples per class;
A possible SVM classification dividing plane is in black,
the nearest-neighbour prediction is shaded in the background.
Knowledge about the green region is especially thin.


Thankfully, this is often not intractable in practice, as we shall see. Additionally, there are at least two often-useful basic strategies to mitigate it - either to generate more data to cover more of the space with confidence, or to inversely map test data such that it conforms to a smaller effective space.


Left: Generating more data; blue arrows are transformation functions
Right: Normalizing data; red arrows are inverse functions


In the case of text recognition, the first strategy would involve deforming some family of characters, which has the advantage of being easy if the scope of possible deformations can be estimated; however, this does have the drawback of generating larger (and slower) models. The other strategy, inverse transformation, is then especially attractive as it would simplify the model. However, as it is not easy to decide on an inverse without having some idea of what the character actually is (in which case the character recognition problem would already have been solved), usage tends to be limited to very simple universal adjustments, such as deskewing.


Perfect recognition accuracy can be achieved - true or false?
(Source: Somewhere on the Internet)



The Background

When attempting something, it is usually proper (if sometimes ego-dampening) to examine what those greater than oneself have tried in the past. One of the cardinal measures in the field of character recognition is the MNIST database of handwritten digits, used by LeCun in 1998 to demonstrate the efficacy of neural networks in this respect. While the dataset is available in text format, Mr. Robo availed himself of Roweis' convenient and easily-visualized JPEG conversion.

Just as importantly, the MNIST database page has been extremely well-maintained (not the norm for academic research), and lists the results of numerous approaches, the best of which currently achieves a mere 0.23% error rate as opposed to the 0.7% (by convolutional nets) and 1.4% (by basic Gaussian kernel SVM) reported by the original paper.

Since the recognition of individual characters is so crucial, I thought it proper to hold a tender, so to say, and decided to pit two of the most well-known approaches - neural networks (NNs) and support vector machines (SVMs) - against each other. This choice was predicated on a requirement to obtain results as quickly as is reasonable, without having to reimplement tons of code, since while fundamental, character recognition is not the actual thrust of our hobby research; happily for us, proven public implementations of both exist: the Fast Artificial Neural Network (FANN) library, as well as LIBSVM, which has already made its appearance here.

Before we begin, which do I expect to be better? Well, there is no easy answer (and I doubt any exists), but we can make some observations by drawing upon various sources:

SVMsNNs
  • Developed from theory, then implementation
  • Pro: Converges to global optimum (but... may not always be suitable!)
  • Pro: Simpler geometrical representation (vectors), sparse solution
  • Pro: Fewer parameter choices - while there is c, gamma and choice of basis function, this is still in a sense more restricted than neural networks
  • Pro: Functions relatively well with less data
  • Pro: Faster to train*
  • Con: Larger model produced*
  • Con: More sensitive to choice of features
  • Con: Very difficult to implement from scratch
  • History was more heuristic and ad-hoc
  • Con: Converges to local optima (may not be the best overall)
  • Con: No ready interpretation of node weights
  • Con: More configuration choices - number of layers and nodes in each layer, as well as how they are to be connected
  • Con: Functions relatively poorly with less data
  • Con: Slower to train*
  • Pro: Smaller model produced* (size bounded by choice of structure)
  • Pro: Less sensitive to choice of features
  • Pro: (Relatively) easier to implement from scratch

  • [*For FANN vs. LIBSVM; your mileage may vary]

    Without further ado, the results by Mr. Robo, LIBSVM first. Note that the parameters (C≈2.83, gamma≈0.00729) were taken from prior blogged research by Mueller, although I did confirm their plausibility through my own crude grid search:



    From top to bottom, the graphs show the classification accuracy (most important), the total training and test times and the model file size for LIBSVM as a function of training set size, for three settings: the red lines indicate the results when the entire 28x28 characters are used, and the green lines when a 4-pixel empty border is cropped. The blue lines occur when instead of using the actual normalized greyscale pixel values, the characters are binarized to monochrome.

    First off, it can be noted that there is a small divergence in accuracy when the strictly-speaking information-less border is removed, which might be put down to the corresponding optimal parameters becoming slightly different; here, Mr. Robo apologizes for having to pick and choose which combinations to consider, which is frankly unavoidable. The 98.58% achieved does about replicate Mueller's findings, which in turn collaborate LeCun's 1998 ones.

    Moving on, both training and testing times seem to scale linearly with the amount of data (the respective graphs are in log scale on both axes). Incorporating the entire MNIST training set of 60000 items takes about 12 minutes tops on my run-of-the-mill desktop, which I suppose is very serviceable; the corresponding test speed is about 50 characters per second, again probably acceptable for now. The model file is however some 111MB large (about 20MB, compressed), which while unwieldy is not an obstacle to deployment.

    LIBSVM can be configured to produce probability estimates (like neural networks do inherently), which happens to be important for our purposes - the following is an illustration of how these estimates vary for different types of predictions:



    It is observed that when the prediction is correct, the estimate tends to be very high - 0.95 and above for 90% of such guesses (in the above graph, it is 99.996% sure for the character "1"). On the other hand, when the prediction turns out to be wrong, LIBSVM knows to be less certain, with 70% of such guesses having a confidence of 0.8 or below. As an example, it is 44.8% sure that the "2" is actually a "3", instead of actually being a "2" (42.5% sure). There are certainly bad assertions, such as being 95.0% sure that the "0" is a "7", though this may be understandable for this case.

    Just for completeness, the grid search visualization for LIBSVM (brighter is better, full dataset rightmost):



    On to the challenger, the FANN neural network:



    The above results were obtained with a single hidden layer of 300 nodes, with accuracy reaching a maximum of 94.24%, not that far off LeCun's claimed 95.3% for this configuration. The training time of some two days was however something of a downer, although I suppose it could have been shorter had proper error thresholds been known and set beforehand.

    Unfortunately, neural networks seem to have no practical guarantees on convergence, as an experiment on a training subset achieved a mean square error of 0.01774 after some 110000 epochs and 0.01457 at some 180000 epochs, but went back to about 0.04 as the 500000 epoch limit approached. That said, I am a novice at FANN and neural networks in general, but at this point it is hard to motivate using neural networks for the next stage. The model files are quite a bit smaller (~2.8MB), but that is scant consolation.

    Note that investigations on tuned single hidden-layer neural networks (building on the local invention of extreme learning machines, which as far as I can tell trains much more quickly than normal neural networks, by fixing the weights - naturally, one expects some form of sacrifice in general for this advantage) just last year have yielded a 1.5% error rate with 2048 hidden units and about 3% error with 256 hidden units, which while somewhat better than the 5.76% error of our admittedly naive attempt, is still not particularly notable especially when compared to the LIBSVM offerings.

    It should be kept in mind that (rather more complex) neural network setups are enjoying something of a renaissance, with convolutional (custom-structured), committee (ensemble?) voting and deep multi-layer networks shown to produce results superior to SVMs and other techniques for some problems. However, we shall not consider these as yet, as improvements of that degree are not critical to our explorations; if required, they can be swapped in later to replace our existing character recognition module.

    While certainly possible for him, Mr. Robo has declined to apply KNN to MNIST (perhaps a snub to Mr. Ham), trusting instead in given results of some 95% for a basic Euclidean (per-pixel nearest distance) implementation, up to above 99% with preprocessing (covered above). His decision is further justified by KNN being generally having poorer performance than SVMs anyway, and perhaps more importantly are slow in usage, as the training set is the model; interestingly, RBF neural networks share commonalities with KNN (which is actually just extended template matching, come to think of it)


    More Doings

    It turns out that there's more from Mr. Robo! Consider that the MNIST dataset, while comprehensive, is in the end still a handwritten collection of digits, while the Google (and many other) CAPTCHAs involve the 26 letters, possibly from multiple distinct fonts. It would therefore be remiss for him not to take all of this into consideration.

    As such, Mr. Robo went to the trouble to (again) cook up his own data. To begin with, he selected ten extremely common web-safe fonts as a baseline, and then went on to find ten normal-looking (of the sort that people wouldn't mind reading for long periods) Google web fonts. Finally, as a control, he found ten decorative fonts to round it all up. The entire collection follows:


    Top row: Web-safe
    Middle row: Google
    Bottom row: Decorative

    [N.B. Many more examples from
    Douglas Hofstadter's Metamagical Themas]


    Mr. Robo then first began by attempting to classify the trusty Times New Roman (undistorted, at a size of 21x21 pixels) by LIBSVM. Unsurprisingly, he achieved 100% classification accuracy on the same.

    [N.B. when the -b flag is enabled in LIBSVM to enable probability estimates, the training data has to be duplicated for classification to work - a (maximum) estimate of some 0.107 is then achieved. This can be increased to about 0.138 by tripling the data, and probably even further by repeated copying, as a consequence of how the estimates are computed; while it was noted that SVM does relatively well with little data, the results still tend to be poor when the number of features is much greater than the number of training samples, which applies here]

    Classification accuracy however falls to 72.2% when this very basic model is applied to the nine other web-safe fonts. Now, at this juncture, Mr. Robo asked himself two questions: Firstly (while pulling on a toga to honour Plato), what is the true form of a character, and can it be usefully described? Secondly, how much information is actually required for classification?

    After some discussion and overconsumption of wine and huffing of fig leaves, a high Mr. Robo determined that while the true form is ineffable and sublime, man, an attempt to approach it might be made by skeletonizing the font and dilating to a uniform stroke thickness to reduce variability, give me another hit of that. The outcome is shown below:



    This observation was then further quantified by computing the total pixel difference between each font and the overall mean, for each letter. As seen below, the difference is reduced somewhat (~12%) for the web-safe and Google font classes. Mr. Robo then generated a larger 2600-item Times New Roman training set by adding rotations and distortions, and got 81.19% accuracy on the other nine fonts without this skele-dilate procedure, and 88.89% with. Therefore, unless otherwise noted, it will be employed from this point onwards.



    What then is the required amount of information, i.e. how large does the character image have to be, to produce good classification results? To answer this, Mr. Robo varied the size of the character images from 1 pixel to 31 pixels square, and tabulated the accuracies. Not unexpectedly, 1x1 and 3x3 are just too small to predict anything much better than random chance. However, there is also no significant improvement once the size hits about 15x15. For some reason, 19x19 produced the best results (perhaps due to the fixed width of the skele-dilate procedure?), and was chosen to proceed with.



    Next was to try and create a practical omni-font model by not including just a single font, but many of them. To this end, Mr. Robo tried a leave-one-out method on the web-safe fonts, each time picking one font as the test set, and using the remaining nine fonts to train a model of size 23400 (with 100 variations of each of the 26 letters for each font). A test set of size 2600 was also produced using the same range of deformations.

    Encouragingly, the results were not too bad, with an average classification accuracy of 94.06% for all ten fonts, 96.67% if Impact, which got only an understandable 70.54% given how different it looks from the others, is excluded. In this vein, the over 99.5% accuracies for Tahoma and Verdana might be explained by how alike they are (which means that when they are being tested on, there is nearly bound to be something very similar-looking already in the trained model)

    When all ten web-safe fonts were used to train a model and the model applied to the ten Google fonts, a classification accuracy of 95.85% is achieved. For the decorative fonts, the accuracy was pretty poor at 38.58%, but this is only to be expected given how distinct their appearances tend to be. These findings are summarized below:



    Just for fun, Mr. Robo also ran the generated set of 2600 distorted Times New Roman characters using vanilla untrained Tesseract-OCR (resized to 190x190, with the -psm 10 flag, and configured to the set of 26 valid characters); 1324 out of the 2600 (50.92%) were correctly recognized, which he supposes is fair given the circumstances. While Tesseract can be trained, Mr. Robo will not be trying that for now.

    Mr. Robo stopped here for a deserved break, affected by news that Google's massive artificial neural network brain prefers cat videos, which more seriously probably reinforces the big data paradigm (example application covered in computational photography). This may be a relief, coming as critical thinking's standing plummets further - someone, ham or machine, has to take up the slack. Happily, identifying when such assistance is appropriate may not be that hard.


    Mr. Ham: Ah, I see my research is coming along well.

    Mr. Robo: Your research?!

    Mr. Ham: Ok, our research. I am a magnanimous scholar, after all. On top of that, I levelled a new Diablo 3 Wizard to Level 53, and found two artifacts on the way:


    That's Chiangmail and Saffron Wrap


    Mr. Robo: Can somebody please stop him from continually stealing my thunder? He's not even doing anything remotely practical!

    Mr. Ham: Ooh, not so fast, companies are already conducting interviews in Diablo 3!

    Mr. Robo: ...

    Mr. Ham: Don't feel so bad, I'm always here to give you some tips on building up some characters that matter, if you know what I mean. And oh, the Gods and Kings expansion for Civilization V came out. Guess that's why Mr. Human is more engaged than usual!



    comments (0) - email - share - print - direct link
    trackbacks (1) - trackback url

    Back to top

    Sunday, July 01, 2012 - 23:12 SGT
    Posted By: Gilbert

    Quick Week

    As Mr. Ham insisted that I watch The Dictator with him, having held the hard disk containing my research findings hostage, I was left with no option but to take him along to the newly-refurbished GV Jurong Point. AXS-printed ticket in hand, I took my seat (plenty of legroom there), and Mr. Ham was soon cheering wildly as the dedication to his idol The Kim came up. Fortunately, I managed to muffle him in time. There were some good laughs there, though there were moments when I thought it went slightly too far - but hey, it's Sacha Borat Bruno Cohen.

    Mr. Ham: I say! There was a disgusting lack of respect towards figures of authority throughout! What would this world be if people didn't cower before bearded chaps with bad tempers wielding a self-appointed extraworldly mandate?

    Me: Better?

    Mr. Ham: See, that's the trouble with you pitiful misguided sinners. That said, it has been a trying time for decent Cult Leaders as of late - can't splurge a mere few tens of millions without bringing soon-to-be-roasted-down-there secular busybodies down on your head nowadays, after expending all that effort persuading fine folk to part with their savings! "Concerted efforts to encourage entrepreneurship"? Pah!

    Well, the Association of Cult Leaders is certainly not going to stand by and watch idly when our membership is threatened. Although we may have our differences in execution, we will always band together when our fundamental tenets come under siege, much like our friends the corporate directors, many of their clubs to which we offer reciprocal hospitality.

    To this end, I have expressed my most heartfelt commiserations to the unfairly scrutinized, and taken the initiative to send a very fat envelope that shall go towards their legal fund. I am confident that they will be exonerated in due time, though hopefully not before the soon-to-be-instituted local branch of my organization can poach some members. Yes, we've been doing swimmingly in Hamerica.

    Me: How do you even manage to sleep at night?

    Mr. Ham: I'll not kid you, it was tough transitioning from all-around ruffian to Cult Leader, but after awhile you do start believing in some of the things you say. And before that, there's always Valium and a soundproof bedroom.

    Me: Huh?

    Mr. Ham: For when you wake up screaming unintelligibly in the middle of the night, silly. It worried me for a bit, till I visited the Association doctor, who cheerfully informed me that it was not uncommon at all, and diagnosed me with glossolalia; he advised me to incorporate it into my routine - it has indeed become a very popular recurring feature.

    Me: Mr. Ham, you really can't go on like this.

    Mr. Ham: Look, I'm simply meeting market demand. You don't see me whining when vacuous girls of uncertain taste toss cash and assorted undergarments at Bieber concerts instead of appreciating true art, do you? The way I see it, some are just born to be fleeced; I supply the shears, that's all.


    Ahhh... that feels so good! By the way, you missed a spot over there.
    (Source: flickr.com)


    Me: That's... that's unspeakable!

    Mr. Ham: *pats hand* Don't worry, I believe you will eventually come around to seeing it our way. I will remember to close my eyes and plead vaguely on your behalf regularly.


    Queue Cue

    At that point, Mr. Ham began to approach me unsteadily, almost like a zombie, with both hands raised to place over me, and I decided that I had to scoot. Figuring that I had better get back in running shape, with both Mr. Ham and the IPPT now after me, I signed up for a bunch of running events.

    Yesterday, I discovered that collecting the race pack could take longer than the actual run (or, more realistically, walk-a-jog) itself. It took over an hour from start to end, with the queue snaking from the ground floor to a second-storey hall, and I am pretty sure that I won't take that long to cover three kilometres despite my current condition.

    I was suspecting that the organizers had set up a single station with some poor guy trying to find names to mark off on scattered sheets of paper, combining the worst of ICT outprocessing and wedding receptions, and was pleasantly surprised (if not by too much - I had been standing for about an hour, after all) to discover that there were no less than ten stations, each equipped with a laptop and barcode scanner. Then why did it take that long?

    I was soon to find out.

    Waved on to Counter Ten, I was served by a young lad, who exhibited an exemplary attitude given the circumstances. First, he scanned my identity card, confirming that I was, in fact, eligible to collect the race pack, and then asked for my vest size (which I had actually specified during online registration) and preferred bag colour (white, red or black). I was considering replying truthfully that I frankly didn't care, but he looked earnest enough that I said "white".

    He then attempted to get the attention of a "runner", or one of the kids who would receive orders, then disappear off backstage to fulfil them, dodging other incoming runners on the way. Through their combined efforts, my correctly-coloured bag arrived, in pristine white, with my vest and personalised running bib - after several long minutes.

    Surely there has to be a better way to do this?

    From what I could observe, there were several independent requirements to be satisfied:

    • Race pack (uniform contents) - no less than three colours available, mind you
    • Running vest, several sizes, let's say S to XXL
    • Running bib (personalised)

    One possible idea: Fulfil each of these separately and cut out the middlemen runners.

    In the first stage, everyone queues for a station according to the last digit of their NRIC number. These stations, for their part, have the corresponding running bibs arranged in numerical order to minimize search time (for once, a touchscreen with appropriately-designed inferface may be better than a laptop). They hand out the bibs and two intricately-photocopied coupons, one good for one vest, and the other good for one race pack (any colour).

    The participant then saunters to the vest collection area, and approaches the counter corresponding to his vest size, where a runner-turned-stationer takes his coupon and hands the vest to him in a three-second operation. Next stop is the race pack collection area, where he again goes to the counter of his favourite colour, and directly exchanges coupon for pack. Finito. No thinking or training required, one-for-one only.

    A few more metres of walking? Perhaps - but it is for a run...

    Mucho time saved waiting? Probably.



    comments (0) - email - share - print - direct link
    trackbacks (1) - trackback url


    << August 2012June 2012 >>

    Copyright © 2006-2026 GLYS. All Rights Reserved.