Wednesday, September 09, 2009

Tried out a new distribution: Fedora

I've used Fedora for the first time now. Like Ubuntu and Debian relationships, Fedora is a distribution that started after RedHat release 9 for home-users. RedHat sponsors Fedora heavily, but has put RedHat Enterprise Linux after the Fedora developments. So basically, the community is expected to innovate on the platform and RedHat sits around these developments, sponsoring Fedora where required and streaming those developments back into the enterprise product.

I'm now using a couple of Linux distro's actually. Some of the servers are running on CentOS, where CentOS is basically the opensource distribution of RHEL, as RedHat is required to release the software under the GPL license. So in a sense, CentOS == RHEL without the support contracts.

It's the first time I've been using SELinux as well. I can't say I'm truly happy about it, it's a bit invisible to the first-time user. I've managed to get things started ok and some nice things are coming out of Fedora, but I do think that Ubuntu support for many desktop tasks is slightly better. It's probably because of the widely visited Ubuntu forums. All-in-all, Ubuntu is slightly friendlier for using the platform, but Fedora has some great and innovative features and probably contains things I haven't even discovered yet.

From the software perspective, they seem to have more or less the same availability. RedHat systems use "yum" for package management though and Ubuntu (+Debian) use apt, that's the difference. Personally, I slightly prefer apt still. Install-wise, things are pretty easy nowadays. It all installs without a hitch.

Monday, September 07, 2009

Truth about Amsterdam

Apparently some guy called Bill O'Reilly from Fox News has painted a very untrue and wacko picture about Amsterdam. Now some people from Amsterdam set up a website to show people what it is really like. I worked right in the center of Amsterdam for the last year, my uncle and aunt lived there for their entire lives, I've studied there for five years and it's really just great. What drugs? What violence? What weapons? What crime?

Come to Amsterdam and see for yourself! I promise you'll have a great time!

Saturday, September 05, 2009

Distributed Hash Tables

I've looked shortly at DHT, als called Distributed Hash Tables. DHT is not only a way to store data in some cloud of computers, it can also serve as a resilient, robust cloud of storage. It's basically a technology that has a very simple manipulation interface (get, remove, set). The differences between specific DHT's relate to geography and oriëntation of nodes, data versioning, hash generation, language of implementation and so on. If you want a clean version, look for projects like bamboo, openchord, opendht, and the likes. Other projects already put in some more functionality, like Project Voldemort.

There are some disadvantages to the use of DHT:
  • It doesn't provide absolute guarantees on data consistency and integrity (but doesn't necessarily make a total mess either, check Amazon's paper on "Dynamo").
  • It's not very useful for "group" queries, range queries or other kinds of data lookups.
  • It doesn't natively support events or triggers very well.
  • There is no authority in the network. So nodes have to cooperate between them in case certain decisions need to be made.
  • Lookup of data is O(log(n)) and may take 2 or more seconds, depending on the real location, how many nodes there are and individual latencies between nodes.
There are clear advantages too:
  • It's highly resilient to network leavers/joiners or other big changes around the network. Most implementations handle node changes very well.
  • Data is automatically distributed, according to specific configuration options. The specific way how data is eventually organized depends on the chosen strategy in the design. For example, the way how nodes are organized (-ing) together is very important.
  • Data is replicated across nodes, so it's difficult to lose it.
  • The removal of any single node doesn't impact the network overall in any way.
Now, if you read the wikipedia page, you'll also see products that use this technology. BitTorrent is a protocol that is very effective in the distribution of file parts, but before you can start sharing a file, you need a way to find it. Finding files works by creating hash keys of them, which is basically an alternate key. By setting up a server where you can browse contents and which has an index of files that are in the network, you can find the content you're looking for and then by downloading a .torrent file, you get the hash key used to find peers in the network that can serve the content you're looking for. From that point onwards, you can communicate with the individual peers to start downloading.

Because keys allow multiple values, you can add yourself as a peer to share the file as well, so that others can negotiate with you on the file parts you may have that they don't. So, DHT in this context is used as a very effective mechanism to find peers to communicate with.

There are other uses of DHT once you start building some logic on top of this simple interface. You could create a virtual file system for example. A key with "/" can be loaded with a set of values, which are the 'subdirectories' that are valid under /. Then you just keep going until there are no more files. To get a file directly, you should be able to look for a key : "/work/myfiles/important-document", in order to get information about the location of that file.

Because projects like Hadoop have different ways for large file replication (blocks of X MB) across a huge cluster, using a DHT layer under this system could store the locations of each replicated block. Nodes themselves can manage their own files this way. This could possibly remove the need for the authoritative and centralized HDFS file directory server and make the network overall more robust and resilient (the HDFS central server is a single point of failure).

It's also possible to store files in two formats: the /x/y/z way, which is meant for finding information and the /nodeX/files way, which indicates the files located on a single machine. If each node itself manages and maintains that information, the rest of the network can react to node crashes by just looking up this information from somewhere and act on this.

The above method for storing information doesn't deviate much from Prefix Hash Trees. A complication in DHT is that you cannot access data by parts of the key (a search) because they are all hashed and unreadable, so you can only find data when you have the key in its entirety. You could create a database in this network as a kind of directory, but that introduces a single point of failure again. The schemes above make this slightly more accessible. This is also the reason why DHT's are not the right solution for every problem. It works when you access lots of data by the same primary key. Facebook uses it for showing entire user profiles, slashdot for storing and retrieving rendered comments. The only thing you need next is a method for expiring entries.

DHT's are generally stored in memory, making them really fast for lookups. Most of the times this is acceptable, but sometimes you want a bit more persistence by having individual nodes store their bits around this network. The biggest problems are faced once a node goes offline for a longer period of time and then reconnects. It is possible that the data it stores is now partly expired and you don't want those bits of information to get back on the network overall. It is also possible that certain updates have changed the information, so that it is newer, which the old keys do not contain. Amazon's Dynamo has more or less solved this by the use of "vector clocks". At some point, you need reconciliation.

Virtually, you could store everything in this network, but you need to know of course what something is as you retrieve it. If you're only looking at non-binary data, an efficient method for storing the data could be JSON. I doubt you'd need "protocol buffers", as they're designed for streaming access to large amounts of data. But possibly you could use the compiler in the project anyway to store it in the described format. That allows you at least to have the storage part covered, so that later you can create apps on top of DHT in python, C or Java.

What is so nice about DHT? The design allows you to work on top of a distributed system, if designed right of course, where you need not worry about fault tolerance within the application. Basically, once you are connected, you just write and read to your heart's content and it should work.

Friday, August 28, 2009

Android: Piggy-backing on the WebKit browser

I've been looking for ways to not store or request username/password combinations for an Android app. The application I'm developing basically needs to get some data from a Google AppEngine application that is deployed, but that app uses authenticated users for doing some queries. I am actually reluctant to request username/password for the application to login, since I don't want people to even believe the combinations can be misused.

Ideally, I want the users to log in using some login provider on the android platform, or reuse login capabilities for gmail/calendar synchronization services, but I don't think that may be possible.

The objective is to just sync some data from the web, after the user logged in with their credentials. The login is then used to perform the query with. All this without needing to have another app register precious login details in its own space, which may get lost or recovered somehow by others.

Webkit to the rescue!

WebKit on Android can be used to show HTML help pages that were bundled along with the app. Also, you can programmatically construct a browser view then use events on the webkit browser to detect when a user finished its conversation (the login process) and then recover the cookies and use that to call the actual service with. The following snippest show how this can be used in practice:

WebView webview;

private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
CookieManager mgr = CookieManager.getInstance();
Log.i( "HelloAndroid", url );
Log.i( "HelloAndroid", mgr.getCookie( url ) );
}
}

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);

webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new HelloWebViewClient());
webview.loadUrl("http://yourapp.appspot.com");
}

That's a good start for temporarily using the browser to do the login. The advantage is that username/password combinations never travel through your app and the standard web mechanism is used to obtain a set of cookies to use for navigating further. The username/password remain very volatile in this entire process.

Since I am sort of running the application in a browser, there are ways for this android app to 'step out' of the browser through one of the events and call local services. As a matter of fact, there is a very nice addJavascriptInterface call, which can register a specific interface in Javascript, which can be called by downloaded HTML pages. Certainly, care must be taken security-wise not to have any other pages loaded in the same browser instance that could also call the javascript interface.

class Logger
{
public void log(String content)
{
Log.i( "HelloAndroid", url );
}
}

..... setWebViewClient(new HelloWebViewClient());
webview.addJavascriptInterface(new Logger(), "Logger");
webview.loadUrl( ........

If then your remote HTML file contains:


window.Logger.log( 'hello Android!' );


You basically have a way to let your android phone do things through the remote server app. The WebViewClient should probably contain a couple of safety controls to disallow browsing to foreign destinations.

Why is this so interesting? because you can now create a server-based GWT app and create a nice-looking browser-based interface (generated or stored server-side) and possibly avoid a good deal of code for native interfaces.

It should even be possible to finish up the browsing part if the server dictates so and continue with some intent on the handset device (and possibly return later).

My intention is to just sync some information for another app and then use that data for other purposes locally. The browser allows me to use GWT all the way, so I can use that to do the very effective GWT-RPC calls to communicate data across effectively. The GWT client code can then call the pre-meditated interfaces in the android app, and we're done!

On towards the next phases... :)

Monday, August 17, 2009

Confabulation and how it relates to SVD?

I've been reading up on this confabulation theory. It's pretty interesting work, the theory, but the practical implementation isn't as nice as the ideas behind the theory :). The use of matrices in the implementation seems to basically make this a problem of statistical analysis. The difference with Bayesian theories and other probability frameworks is that this theory assumes a "causal" relationship between one and the other, not in the way that Bayes does, but through cogency maximalization.

In the end though, and reading the word "matrices" somewhere inbetween, it all sounds a bit like singular value decomposition with a twist, rather than something entirely new. I've been looking for ways to replicate their results somehow. I came up with the following:
  • Using Hadoop as an underlying platform for simple tasks (like counting words, ordering them, etc.), you take out a lot of complexity out of a program. So I'm using Hadoop to count word frequencies and the frequencies that words are seen together and at which distance.
  • Hadoop provides a platform where I'm mostly using files, intermediate results stored in files and reducers to bring back some sanity. If I'd had to program that myself, I would be more concerned about stability and reliability than the core of this little research, statistical analysis (in short).
  • The results are used to train a couple of SVD's á la Netflix - gradient descent. Because I've got a good 1GB file of frequencies, I don't need to process text anymore, it's all ready for learning. (text processing required 5hrs to process and get the results together. The problem in learning is that the statistical significance is only apparent after the entire lot was processed, or you'd have to heuristically make estimates).
  • The SVD's are about 60M in size. On my machine with memory left, I could theoretically get to 33 SVD's, working together.
  • The pre-processed files allow me to process the entire "frequency" file line by line, one after the other. I post-processed it to take out any words I did not recognize.
  • Since I know the statistical significance of each word, how it relates to another and by what distance, I can just keep on training the features of each SVD. Not knowing that beforehand makes training slightly difficult (doh!).
I also thought about possible results of confabulation if it were implemented as a chat bot. Suppose that the technology were ready to produce sentences as if a chat session was going on. The Turing test is one important test, where judges need to make clear distinctions between humans and computers. Since this is a subjective test, I can't help but think that there's also an element of expectation involved. The judges know what a computer does, how it operates and what its limitations are. Now, if someone invents something really cool that breaks that barrier, the judges may temporarily be baffled and come to incorrect conclusions. But as soon as they learn about the research, they may adjust their expectations, raising the bar for the future.

In short, *can* the Turing test ever succeed? Because what if a computer OVER-performs, giving away its true nature? It seems that for a Turing test to succeed, the computer must be on the exact cognitive level of a human being, not higher or lower.

Anyway... Hadoop is really cool and useful. Having another computer in the network would half processing times. Hadoop + custom programs + post-processing scripts sound like really useful ways to pre-process huge amounts of text before you let a machine learn days on end. Since the end product are files that are in a more "edible" format, it should be a lot faster to do the research cycle.

Thursday, August 13, 2009

Confabulation theory

Confabulation theory is a theory from Robert Hecht-Nielsen about the cognitive function of the brain, or in other words the working of thought. It's a theory, not an explanation. Confabulation theory basically works by processing lots of information and then from this information, find out which symbols belong together. Those symbols that are often seen together (and in cases by which distance) is information contained within the network. Confabulation can now produce new sentences by continuously generating possible phrases based on the context that is seen prior to that.



In effect, the confabulation theory uses an architecture that can produce entirely new sentences, which are plausible in the context. The interesting thing is that these sentences are also grammatically and syntactically correct. Thus, the rules of a language seem to be embedded within this network.

This does not mean that the machine 'understands' the language, or that it is conscious of the sentences it produces. I think the results should be considered the production of a thought-less brain, which only has the capacity to produce sentences without understanding what they mean. It's probably comparable to the chinese room producer, where it looks at streams of chinese symbols. At some point, the machine understands the order in which the symbols may appear and which symbols are often seen together. When asked to produce a sentence on its own, it uses this knowledge to produce a sentence.

What interested me in the theory is how this network differs from other networks that can fantasize, like the RBM. The RBM is a network that stores knowledge by looking at things and can then complete the signal it is receiving. This confabulation network is slightly different, in the sense that it can project continuations (say, a hypothesis) that are very plausible. So, if you were building a network that can produce responses to sentences, the confabulation network is likely to perform better. But if you ask a confabulation network to recognize a face, it might have good difficulty and the RBM might be better.

The RBM is a flatter network (judging the entire system) in comparison to the confabulation network. The confabulation network just competes between symbols and modules and always takes the highest value of all, but since the signals proceed from those results towards other networks, it's in a sense hierarchical.

It'd be really interesting to be able to identify specific properties of each network and then see if they can be used together. It's also possible that we're thinking about this the wrong way. The continuous processing of the confabulation network is quite different from others. We like to think from static situation to the next, perhaps the entire thing is more dynamic than that and we should focus on generating states, looping back and reprocessing the results, thus continuously adding more results to some hypothesis.

Since A.I. is also a lot about search in search spaces (think chess!), a neural network could be used to generate a hypothesis step-by-step, until it is deemed that a particular branch isn't going to produce a good result, so that it can be terminated.

Monday, August 10, 2009

Philosophy of mind and innovation

In this post I'm going to talk about a possible measure of success for creating new innovations in software. To start off, I'll put some links to put this more into context: Here's a semi-graphical timeline of the development of the GUI. Here's one of my posts made in 2007, where I'm talking about how working with computers becomes more of a conversation than it has been before. Mainframes and the likes just accepted batch jobs and you'd type the command, hit enter and that's it. In web 2.0, the computer is more or less looking over your shoulder what you type, point at and do on the screen and then if it thinks it can help you out with something, it'll pop up some helpful hint or thing next to your focal point. It is related to what we know about and how we think about our bodies and minds.

And all of this started with philosophy, thus it started with the Greek: Aristotle, Plato and Socrates. The first thoughts there however were meta-physical. What is the world made of? What does it mean to be alive? In this context, the most important thought is the separation of body and soul. The years after that, most thinking is based on the philosophy of the greeks. The middle ages turned this around a bit with the introduction of religious thought into philosophy itself. Many people tried to explain things through the use of religious ideas. And then came the others to found modern philosophy, amongst them René Descartes.

Descartes is one of the founders of modern philosophy. In his discourse about the philosophy of mind, he introduced the concept of dualism. He also considered ideas about the working of the human body. The interesting thing here... the explanation used mostly analogies and was inspired by the progress of machinery, tools and things in real life that existed at the time. In that time, the functioning of nerves and blood vessels wasn't entirely clear. For 1,500 years, people thought that "animal spirits" governed the human body. However, during the time of Descartes, certain developments were underway, like the start of hydraulics. Basic, mechanic machines could be built. Descartes knew about those and imagined the body as a kind of automaton as well. To the best of his knowledge, he tried to explain how the body worked, and used the concepts that he had available to him. After Descartes, the thinking about psychology, the mind, the brain and how it all worked together really set off. In a sense, you could also say that the way how we started thinking about things just notched downwards one level.

At this time, the thoughts about the mind didn't really go further then: "there are mechanics at work that bring sensation to a central point somewhere in the brain". This central point was imagined to be a mystic piece of the puzzle [the soul?], where thoughts occur and what can be said to be the 'I, self', when you think. So, in that time, since people observing the machines in those days clearly understood that such a machine was not alive, they didn't (perhaps not all) imagine that the machine could actually produce human thought. But, some people that did not understand its function did say that the machine can be made to do anything we ask it to do.

The function and design of the machines were still used as analogies to explain how other processes could work in the human body. Physics and mechanics research has thus certainly helped the developments in medical science to better understand the function of the heart as a pump and the fluid dynamics of blood in the vessel.

This is just a tiny grasp from everything that's happened in thinking about the mind, surely, but there's not a lot of space left on this post to continue :). It's best to read it from this excellent source I found here: Courtesty Dr. C. George Boeree.

So, philosophy started with the Greek, seeding a new science called psychology along the way and in the 20th century already at the start, we started building computers.

Why is all this "philosophy stuff" relevant?

Well, if you look at the developments in philosophical thinking and the developments in machinery, they seem to go pretty well in step. This is not because they are directly tied together, but because other developments in neuroscience, psychology, electron microscopes and imaging techniques need to be developed in order to .... start asking the right questions. And philosophy, psychology, design, artificial intelligence and sciences are the most important scientific research sources for finding those questions and hopefully the answers.

Analogous to the comparison of the mind to the technology of every age, we also see that we (re)construct our ancient tools into newer technology available. But hold on there... Shouldn't this be new tools in new technology?

Consider the desktop for example. The GUI timeline at the top is a resemblance of how we introduced the computer to the general public. The GUI works great, I don't say it should never have been developed, but there are very old concepts still present in there. Take the desktop and its applications for example:
  • The trash bin is literally there and even called the same.
  • MS Powerpoint is basically a digital slideshow projector with edit functions.
  • MS Word is clearly inspired by writing on paper, thus the typewriter.
  • The "file manager" looks like a filing cabinet in the older GUI's, but this is slowly being replaced by "explorers". The explorer still has a hierarchical view of files however.
I think one of the reasons why this was done is to make it easier for users to familiarize themselves with the environment in which they were 'operating things'. But now that everyone is accustomed to the use of a computer, more or less, there doesn't seem to be a reason to maintain this ancient set of tools in this new environment.

So, one of the problems in software innovation is related to imagination, it's certainly not about technology. A good example for starting to get rid of powerpoint is prezi. Prezi is reminiscent of the concept of mindmapping, but that is great. What is the most important difference between prezi and powerpoint?

Powerpoint is a digitalization of the slideshow projector. Mindmapping is an attempt to convey thought and their relations between them. The first is putting an old thing into a new jacket with more features. The other is understanding the mind, understanding cognition, knowing your mind and how it works, how we consume information better, what allows us to make proper distinctions, what allows us to make better judgements, communication and what allows us to easily derive the correct context and then developing a method to enable that process.

So, to finish off my post in 2007: "Conversation with the machine" with the question:
"How can/will/should user-machine conversations evolve from this point onwards?"
I think innovation should focus on following and enabling the natural flow of cognitive processes, not on the reconstruction of ancient tools of communication and processing, like mail becoming e-mail. Before you feel the urge to send out a mail to someone, there is a reason, a motivation. What if we start from there instead and just consider the computer the ultimate tool in visualization and computation? Oh yeah, and it has connectivity as well.

( footnote: There are certainly other tools like keynote+iMovie and Adobe flash that can be used to produce a prezi-like presentation. Prezi is just mentioned, because I think it is a good example of how to think "out of the box" ).

Wednesday, August 05, 2009

SFTP transfer scripts

I've made a set of scripts to send files from one server to another in a secure and reliable way. The idea was to use the standard UNIX/Linux tools as much as possible, because this allows admins to customize the entire process to their hearts content. A new program using libraries would certainly be more limiting.

The project is published here:

http://code.google.com/p/sftp-transfer/

It is using SFTP to transfer files from A to B and the configuration is written with Ubuntu systems in mind. The entire setup can optionally use a chrooted sftp setup. The project demonstrates full design details and a complete installation manual.

Friday, July 17, 2009

Mapping demographic data, aggregated by geographic regions

Bit of a post for the Dutch, but you may have some data that is similarly detailed and cool (AND FREE!)... Together with a colleague I've been working on mapping demographic data of Holland on Google Maps for marketing purposes. The result is here:


There is a data dump from the CBS that you should be able to find with Google called "Districts and Neighborhoods" or "Wijken en Buurten". This data contains some demographic data about a region ( municipality, district and down to neighborhood ), as counted by the CBS. As well, there is a data set called "Core figures", which translated to "kerncijfers" also supplied by the CBS.

The core figures go down to the postal code level, which does two things:
  • Finer grained information than you already have (which is not very useful for marketing purposes)
  • Establish a correlation between postal code and the neighborhood it is in, thus allowing you to map groups of people to neighborhood level, which is probably a good aggregation level for marketing.
The district- and neighborhood data is delivered in the form of ESRI shape files. This allows you to convert the data into Well Known Binary format (WKB) using the shp2pgsql utility. This builds a table from the data in the SHP file and outputs this into sql into a file. Then you can simply < href="http://code.google.com/eclipse/docs/getting_started.html">Google plugin) + Hibernate. To be able to query the postgis database, you need the vivid solutions extensions.

Then I use a query to get the polygons out that I need through the postgis query API:

String wktFilter = getFilter( bounds );
WKTReader fromText = new WKTReader();
Geometry filter = null;
try{
filter = fromText.read(wktFilter.toString());
filter.setSRID( -1 );
} catch(ParseException e){
throw new RuntimeException("Not a WKT String:" + wktFilter);
}

Session s = HibernateUtil.currentSession();

Criteria testCriteria = s.createCriteria(Buurt.class);
testCriteria.add(SpatialRestrictions.intersects("theGeom",filter));
List buurten = testCriteria.list();

As such, I get the neighborhoods or other regions back that I want, based on my Google maps viewport :). That's already an important step, but doesn't finish there. Since the data in the Wijken en Buurten is RijksDriehoeksmeting (RD), it needs to be converted to the Datum that Google Maps uses. They're using WGS-84, a datum, which is basically a geoïd generally used for (probably) older GPS's. I'm using this code for now to convert between the two:

public static double[] rdtowgs( double X, double Y ) {
double dX = (X - 155000) * Math.pow( 10 , -5 );
double dY = (Y - 463000) * Math.pow( 10 , -5 );
double SomN = (3235.65389 * dY) + (-32.58297d * Math.pow( dX, 2)) + (-0.2475d * Math.pow( dY, 2)) + (-0.84978d * Math.pow( dX, 2) * dY) + (-0.0655d * Math.pow( dY, 3)) + (-0.01709d * Math.pow( dX, 2) * Math.pow( dY, 2)) + (-0.00738d * dX) + (0.0053d * Math.pow( dX, 4)) + (-0.00039d * Math.pow( dX, 2) * Math.pow( dY, 3)) + (0.00033d * Math.pow( dX, 4) * dY) + (-0.00012d * dX * dY);
double SomE = (5260.52916 * dX) + (105.94684d * dX * dY) + (2.45656d * dX * Math.pow( dY, 2)) + (-0.81885d * Math.pow( dX, 3)) + (0.05594d * dX * Math.pow( dY, 3)) + (-0.05607d * Math.pow( dX, 3) * dY) + (0.01199d * dY) + (-0.00256d * Math.pow( dX, 3) * Math.pow( dY, 2)) + (0.00128d * dX * Math.pow( dY, 4)) + (0.00022d * Math.pow( dY, 2)) + (-0.00022d * Math.pow( dX, 2)) + (0.00026d * Math.pow( dX, 5 ));
double ret[] = new double[ 2 ];
ret[ 0 ] = 52.15517d + (SomN / 3600);
ret[ 1 ] = 5.387206d + (SomE / 3600);
return ret;
}
public static double[] wgstord( double Latitude, double Longitude ) {
double dF = 0.36d * (Latitude - 52.15517440d);
double dL = 0.36d * (Longitude - 5.38720621d);

double SomX= (190094.945d * dL) + (-11832.228d * dF * dL) + (-144.221d * Math.pow( dF, 2 ) * dL) + (-32.391d * Math.pow( dL, 3) ) + (-0.705d * dF) + (-2.340d * Math.pow( dF, 3 ) * dL) + (-0.608d * dF * Math.pow( dL, 3 )) + (-0.008d * Math.pow( dL, 2 ) ) + (0.148d * Math.pow( dF, 2 ) * Math.pow( dL, 3 ) );
double SomY = (309056.544d * dF) + (3638.893d * Math.pow( dL, 2 )) + (73.077d * Math.pow( dF, 2 ) ) + (-157.984d * dF * Math.pow( dL, 2 )) + (59.788d * Math.pow( dF, 3 ) ) + (0.433d * dL) + (-6.439d * Math.pow( dF, 2 ) * Math.pow( dL, 2 )) + (-0.032d * dF * dL) + (0.092d * Math.pow( dL, 4 )) + (-0.054d * dF * Math.pow( dL, 4 ) );
double ret[] = new double[ 2 ];
ret[ 0 ] = 155000 + SomX;
ret[ 1 ] = 463000 + SomY;
return ret;
}


So there goes that! Any data coming back from the UI needs to be converted into RD first (the bounds), before querying the data on the viewport.

We're still working on refining things, like encoded polygons and possibly some caching, but in compiled form the app is a lot quicker than in the GWT shell. At the moment we're simply forwarding the individual points, but that's not as efficient and probably not as precise. That shouldn't take too long to get done however. Well, the rest of the application is just using the Google Map Library and putting that little map on the screen. That means using the proper events, hooks and scriptlets, to use the old MS word inbetween.

The figures are from 2004 and have been slightly updated for 2006, but probably not too much. The real figures about inhabitants are from 2009 and are based on the GBA, but some effort has been made to change things where problems could ensue regarding privacy.

What's the use? Well, together with the postal code, which is often requested, or with the customer's IP through geo targeting, you can start data mining. Marketers can quite easily develop certain profiles of what they're selling. By the IP the region can be quickly discovered, which may then give clues about preferences if the person is not known otherwise by login for example (any preferences or login that you have is far more useful than this silly method of customer targeting).

Based on the region/IP/postal code, you can find out what kind of products are more likely to suit the visitor. Thus, it provides a way to adjust the web content to the person that's visiting. Any other smaller clues like the first three clicks could theoretically tell you the rest of what the person is trying to do, or why your site is visited.

Some other sites like funda.nl use similar databases, although I believe they've probably paid around 7,000 EUR for a postal database which is slightly more precise. The CBS borders are those borders established by the government.

This little thing that you see on the page is interactive, only loads what it needs based on the viewport bounds and was hacked together in 16 hours.

Sunday, June 28, 2009

Can computers become conscious?

This is a post to contemplate about a paper I wrote, available here. When discussing the possibility whether machines can become conscious, reference is made towards the necessity to localize memory, cognition and all these other factors. In short, to have a discrete description of the system we call the Brain. Should we not understand it in full, then all hope is lost.

I'm taking a different view on things. "Emergence" for example shows that many, many small actions that are discrete in nature and often very simple, interact together to eventually become a massively complex system that no single, descriptive, general rule can describe. It is easy to describe the simple behaviour from a single agent, but it's impossible to understand the actions and consequences of the system as a whole. I reckon that we may not need to understand this entire system, but can start from the bottom by replicating certain behaviours and look at certain clusters in the detail that is still fathomable. Then attempt to replicate those clusters and move upwards in the chain.

Oh well, to prevent a rant on the same, on to the whitepaper then:
This whitepaper draws a comparison between Restricted Boltzmann Machines and human consciousness using a quantitative analysis of the capacity for the integration of information. The probability that computers can become somewhat conscious of their inputs is discussed. Consciousness of computers implies the capacity to interpret data, understand it, manipulate it and possibly to produce new data based on previous examples.

The same neurons activated by observation are also activated when dreaming or imagining. Restricted Boltzmann Machines work in a similar way; [....] This makes it plausible to construct computers that have some kind of imagination, [....] the type of consciousness isn't necessarily equal to our own [...]
Happy reading!

Tuesday, June 23, 2009

Pro log

No, I'm not in favor of forest logging. Prolog is a declarative language, part of the fifth generation of programming languages. I'm following the final course for this academic year, for which 2 assignments need to be created. The first assignment was a game basically with heuristics for intelligence. The other assignment is an artificial reasoning thing, where it needs to reason about the types of relations between countries. The questions and facts are written in natural language, then stored in alternative format in a more workable representation for the computer. It can be stored to and re-read from disk. It can also derive relations between two regions that have no direct relation declared, but because X has a relation with Y and Y has a relation with Z, the program can derive the possible relations (a set) between X and Z. It's coming along quite nicely at the moment, reasoning is pretty much working. There are some types of questions that are not entirely answered yet however, but it should be possible to complete them pretty quickly.

Both assignments had very interesting elements in them, whilst at the same time generating quite a bit of frustration. Prolog is a language where you're not necessarily directly in control of memory and so on. When programming a couple of years in procedural languages (most are: C/Java/PHP/C++/Python/Perl). Well, about Java and C++, opinions are divided. They don't necessarily call it procedural, since in smart cases it's about objects reacting to events. In my view though, a C++ class can be considered a whipped up C struct with a virtual table of function pointers (except that the compiler lacks other capabilities and the STL and so on).

Cool thing about prolog are the recursive abilities that usually accompany list manipulation. The interpreter does the backtracking basically, so you just tell the environment what you want to achieve. That's why it's declarative.

The main goal of prolog is: "achieve truth". Never forget that when programming in prolog. The only thing that the interpreter is ever trying to do is find paths and instantiations that, through the declared end-goal, achieve a "true" condition. Whenever a false condition occurs, the interpreter starts backtracking and will start to search for different combinations of instantiations and paths, basically other candidates.

The thing that is not very easy for beginners in prolog is branching. If you're used to the programming of 'if-trees', those if X then Y kind of structures, then prolog doesn't give you lots of tools to handle these. The good thing is that you start to think about many problems as a very generic problem, thus your approach to solving it also becomes very generic. The bad thing is that when you really need it, the amount of code may start to rise a bit.

Well, luckily the language allows modules and there are quite some internal predicates available for making programming easier, but it isn't yet as easy (for me) as programming Java or anything else.

Part of that, I think, is related to finding the correct approaches to doing things in a certain context, also called patterns. For prolog, the practice of programming prolog isn't very well documented or discussed, where the techniques that prolog allows has a lot of examples. The main examples are "knight's tour" and "sudoku".

Scheduling optimization is a topic that is more and more important for larger companies as well, or finding "a" best solution to a set of constraints and a configuration of entities. Think of DHL and timing of getting deliveries in time, think optimization of a pick-up route in logistics (travelling salesman?), think optimizing the order in which tasks need to be executed (and by whom?) across a set of resources, think developing the order in which ships may travel down a channel to take berth, having an anchorage at the outside.

These problems should not be under-estimated. With 3-4 or less constraints, procedural languages probably allow you to find a good solution within milliseconds. But when constraints are > 5 and it is possible that these increase, the procedural language solution becomes too complex, testing the solution is too complex and time-consuming and the confidence of the developers that the solution is *right* starts to decrease.

So, prolog can be pretty cool. It's pretty much crap for web development or general systems development, but once you get into that difficult problem with >4 constraints, have a look at it and see what it does, it's pretty powerful.

Friday, June 05, 2009

The wedding was yesterday, it was absolutely amazing. The people that were present were all very special to the couple and we had a great time to get to know one another. One of the ideas of the couple was to mark the poolside with a set of decadent towels with a W on it, for the last name of the family. Here's a great shot from the pool side.

So, the wedding took place on the roof of the middle building, overlooking the ocean. It was a well-timed, proper ceremony.


After the ceremony, of course there is a reception. And in Cancun, you'd typically do that on the beach at sunset.

And then the professional photographer was making shots of the couple.

The day ended in a dinner and dance more at the center of this resort.

Thursday, June 04, 2009

Chichén Itzá

Yesterday we had the opportunity to see Chichen Itza. From the coast of Mexico in the Cancun resort zone, it takes about 2.5 hrs driving by car to get there. The road is very reasonable and easy to drive. Almost no traffic whatsoever. The scenery though is a bit boring, just trees, more trees and then some more. It's cutting straight through the jungle, if you could call it that. This is one of the trees that you see frequently with red blossoms / flowers:

There's a great ballcourt on this site as well. Ths is the largest in ancient mesoamerica:


And of course the most famous and visible monuments of them all, the temple of the feathered serpent:


I think it was really worth the drive over there, but since it's in the middle of the jungle, you need to bring lots of water and be able to walk a few meters in the heat and enormous humidity. Sweat keeps pouring down your forehead in general. Getting closer to the more remote areas like the market, things become a bit quieter what tourists and merchants is concerned. Sitting down in that area listening to the birds is a bit of a spiritual experience.

The other thing is getting back to the coast :). There are two roads that both have the same number 180 and it's not always clear which is which. The old 180 road goes through all little towns and takes you into the center of Cancun. I don't think you want to go there. When you exit the site, don't take the 180 road directly to Cancun, but go exactly the way you came through that little village, then take the road from there. You'll be saving yourself 2-3 hours of travel :).

So, yesterday after we got back late, we sat down for dinner and then joined into a large mojito party with the entire family, with dancing, music and talking. Great fun! Today I don't notice any of the drinking of yesterday and am just about to head off to the beach for some relaxation and possibly some more pictures.

Wednesday, June 03, 2009

Sunburn, easy day, dinner

Yesterday was a very beautiful, great day. It started with some easy time at the beach, then a lunch on the beach where they were serving barbeque, paella, etc. in an area with wooden benches and some protection from the sun. Then some time at the pool and near a caribbean restaurant. In the evening, the entire group went to a restaurant on this resort, which offered new-style mexican food. It means about 10 plates of little bites and tastes, where the plates change somewhat rapidly. This was great, it gave us an opportunity to meet some other people.

So, Heidi and Jorge invited family and friends from various parts of the US and from Brazil, Holland and the UK. I may have forgotten one there. Dinner was finished by going to the lounge bar, where some extravagant, really weird magic act was taking place. Today, we're going to Chichen Itza to see the temple and will be back in time for dinner and wedding rehearsals.

Monday, June 01, 2009

Arrival at Cancun

Well, we've arrived in Cancun, after an easy flight from MC to this place. We've had to wait just a little bit, but it's worth it if this is the place you're going:

King size bed, 16:9 TV, and a jacuzzi in the back there with a door that opens up to the swimming pool area right on the ground floor. Very, very nice all...

This whole trip is because we've been invited to a wedding party over here in Cancun. Jorge and Heidi are getting married in a couple of days and the entire party is slowly gathering to full strength, just under 40 people n total as I've heard today. The wedding itself will take place on the roof of the building, 5th floor. The roof has a glass railing, so standing there, the sea breeze goes through your hair and the sea greets you wave after wave with water that's probably been all over this world already. Just a couple of days away!

So, what's the beach like in Cancun? It's got what most beaches have... SAND! but of course, there are nice touches. Some thing I haven't seen are these types of chairs and complete setups:

These are really good things. It's a kind of mattress under a reed roof kind of thing with two chairs and a small table in the middle. There's about 15 of these or so around this area. Because of the swine flu, a lot of cancellations were made, so you're sure of a spot there every day. Oh, and of course, what's the view like on the other side? :)

Great huh? Water must be about 27 degrees, there are people walking around the entire time to serve food and drinks... And the room is just a stone-throw away if you prefer to get back to some airconditioning and cool off.

Tomorrow is probably jus going to be a lazy day, not sure if there will be another post then. There might just be a chance for us to see Chichen Itza some time this week, but that remains to be seen.

Sunday, May 31, 2009

Ciudad de Mexico

Well, our day started early. I had expected to sleep really long well into the morning, but for some reason it was impossible to get some good sleep. The hotel does offer a great breakfast here in Santa Fé. It's mostly suited for business people. Santa Fé is quite new in Mexico City and is hosting a couple of high-rise buildings to support the high-tech companies that are setting up shop here. Very close by, there's the largest shopping center in MC right now, Centro de Santa Fé. It has a couple of very fashionable and expensive shops around there, e.g. a boutique of Ermenegildo Zegna, Armani, just to name a few. Anyway, after breakfast, we managed to get a taxi sorted and drove through MC on the avenue of Reforma to get to the city centre. Reforma and just before Polanco, the area in the city with fancy restaurants, expensive clubs, etc., is also the avenue with a lot of houses for government officials, embassies, you name it. So the expensive house or two can be seen on the left and right. Just after this area is the park with an auditorium and Chapultepec. Due to time constraints, we haven't been able to visit that. We arrived soon on Zolaco. It's a large plaza in the middle of the city with already some of the most well known buildings around. So take out your camera and shoot. The golden hour had just passed sadly, so lighting was already creating some difficult situations. Right on the Zocalo is the Catedral Metropolitana, the oldest cathedral of the Americas:

It's impressive. The glass in the windows is not leaded or coloured, which is a bit of a shame, otherwise it'd be great to bring a tripod next time for an High Dynamic Range session. The altar and other views are equally amazing.

The other buildings around the square are very old, this area of the city is very appealing and certainly to be recommended. You do get the occasional nagger for taxis or other tourist stuff and possibly there is some pickpocketing going on, but I don't get the idea the area is unsafe. Matter of fact, you do see a plenty of mexicans, other tourists walking with their camera in full view, walking around this area of town. Police is also in abundance.

Well, taking a little stroll from the plaza towards the west, we're passing some very old houses and streets. A tower called Torre LatinoAmericana is in the city, which goes up to 43 floors or so, built in 1957. It isn't the prettiest tower in the world :) (don't mention this blog whilst I'm up here), but it provides a superb view of the city. This also shows the immense size of it. Wherever you look, the faintest houses in the distance fade into the horizon mist. Mexico City is huge and the metropolitan region is roughly the same size of that in Sao Paulo.

And standing on top of that tower, we spotted another beautiful building just next to us, the palace of fine arts, an opera house. A place of great architecture, something to definitely see in more detail. Since we're trying to see as much as we can, we've decided to come back another era.
So we moved on through the park towards other places. I've enjoyed that little walk. There are plenty of shops, restaurants and things on the sides to grab some water or some food. Other than that, it's quite stereotypical, although I found this park to be nicer than many other parks I've seen in other metropoles/cities.

At the other end of the park was a taxi stand and since we needed to prepare for the rest of our journey, we decided to check out the shopping center in Santa Fé. This is the largest in the city now and very well developed. There are three floors spanning the entire area with everything you'd generally expect in a mall, so I won't digress too much.

We'll be travelling out to Cancun tomorrow, which I think is a bit of a shame. This city offers so much to visit and see. And if you visit the really interesting villages and temples around Mexico City as well, I'm sure it's possible to stay for at least a month. Anyway, not to worry. Can't complain about Can Cun, Can you?

Saturday, May 30, 2009

unas papapas, unas pepeiras


Just arrived in Mexico City after a long 11hr flight. This was taken on the way from the airport to the hotel. Tomorrow I should have time to go around the city, take cool pictures. Tonight, just getting some good food from the restaurant over here, turn on the tele, enjoy some wine and get ready for the day tomorrow.

Haven't seen face masks around the city here, only paranoid tourists just arriving at the airport use them. Some general precautions are necessary to reduce chances of infection from the virus:
  1. Don't stay around sneezing people that look sick :). Don't get into crowded areas or public transport.
  2. Wash hands regularly.
  3. Don't touch your face with your hands when going through public places.
  4. Eat healthily and loads of vitamins. Make sure to sleep properly.
Weather in Mexico is cloudy at the moment. Actually, it's better weather in Holland at the moment... The temperature is 27 degrees or so and constant, so that's cool. Not as hot as Brazil however, plus that Recife is seaside and this is more into the country. The city is huge here, there are not too many high-rise buildings, so just like London, the city expands across the country in ridiculous proportions.

Tuesday, May 12, 2009

Why RBM's are so strangely weird

I'm getting quite obsessed by RBM's for some strange reason. There's a very strange simplicity to the RBM, a very elegant method for learning through contrastive divergence and a very strange ability for an RBM to model many things. The current science shows and understands that RBM's certainly have limitations, but here we go to try to expand on that.

An RBM is a very strange kind of neural network. Artificial neural networks the way we know them generally work the signal in a forward direction, but RBM's work in a forward and backward direction. In a sense, you could say that it's a little bit similar to our minds in that, when we observe something, we both use the details from the input signal to enrich the actual observations, but at the same time use the information from our experience to enrich or expect what is being observed. I reckon that if we were to only rely on the observed state, that state wouldn't nearly be as rich as our mentally induced state, which blends our experience with our observations.

Here's a video that might blow your mind or not... It's a presentation from Giulio Tononi, which I found very compelling. In this theory, it's not a search about the quantity of neurons required to become conscious, or the localization of consciousness within the brain, but it's more of a theory of the most effective organization of neurons within a network for such a network to exhibit consciousness. (text)

Here's where I paid huge attention. Apparently, having a network that has all neurons connected together is total crap. And a network that is very large and has a high number of local connections can be good at something, but it doesn't have the right properties for consciousness. The best thing is a network with specialized neurons, connected in patches, with long connections now and then to other parts of the entire mesh. Much of the work there is related to quantifying consciousness. By quantifying consciousness, and if this quantification is in step with actual consciousness, one can continue to search for more effective methods of building neural nets or machines.

The property about "patchy-ness" suggests that blindly connecting neurons together isn't the most effective way to build a network. A highly regular network makes any system act like a general on/off machine, losing its specificity of function. Neurons that are not connected enough make it work like having a number of independent classifiers, which isn't good either.

Most NN's and RBM's build their theories around having x number of neurons or elements connected evenly together with other layers and then calculate a kind of "weight" from one element to another. Putting more neurons into a certain layer generally makes the network more effective, but improvement is generally asymptotic.

I wonder whether it's possible to develop a theory, complementary to the theory of the quantity of consciousness, which perhaps as some derivative allows a neural network to shape the network itself, or whether such theories provide better rules for constructing networks. One good guess would be to do observations of biological growth and connection-shaping of a brain or simpler parts and then assess the patterns that might be evolving in the generation of such a network.

Finally, the most interesting words of the hypothesis:

Implications of the hypothesis

The theory entails that consciousness is a fundamental quantity, that it is graded, that it is present in infants and animals, and that it should be possible to build conscious artifacts.

This is a huge implication. And in order to understand it, one should go to the start of this post. Consciousness == experiencing things. As said before, it means that our observations carry detail, which are processed by itself, but which are also completed by previous experiences. Thereby, our actual experiences are not just the observations we make, but a total sum of those observations plus memories, evoked emotions, etc. In a way, you could say that what we observe causes us to feel aroused, or have some kind of feelings, and seeing similar things again at a later point in time might cause us to see the actual observations + previous experiences (memory) at the same time. It's very likely that not all experiences are actually consciously lived, in the sense that we're aware of all possibilities of experiences that we could actually experience, very likely there are many experiences just below the surface of consciousness as some kind of potential or stochastic possibility, waiting to be activated by changes in the temporal context.

For example, rapid changes in our direct observations can cause instant changes to behaviour. This implies that next to observing the world like a thought-less camera, consuming light-rays and audio waves, we're also experiencing the world as a kind of stochastic possibility. The easiest example of demonstrating this is the idea of movement, of intent, of impact and likely effect.

The phrase: "I'm standing at a train station and I see a train coming towards me" contains huge amounts of information. The recognition of the train in the first place, the experience that it's moving towards you by the train becoming larger, the knowledge that the train runs over tracks that you're standing next to, the knowledge that train stations are places where trains stop and your intent to get on the train. Just telling here how much knowledge we apply to such a simple situation demonstrates how we're accepting our consciousness as the most normal thing on earth, which it certainly is not.

Well, so why are RBM's so strange in this sense? Because old-school neural networks don't have these properties. RBM's can both recognize things, but also fantasize them back. There are certainly current limitations. In previous posts I've talked about consciousness that we shouldn't perhaps limit the definition by "consciousness == when humans think or experience". When maintaining a broader definition of consciousness, one can also consider machines or A.I.'s which are extremely effective in a very particular area of functioning and might just be consciousness in that relevant area without having any kind of consciousness of things around. The definition of consciousness here however is a dangerous one, since it shouldn't be confused with behaviour, which it certainly is not.

Food for thought...

Sunday, May 10, 2009

If You Liked This, You’re Sure to Love That

An article was posted in the NY Times about the Netflix prize some time ago. It fired some new ideas that I'm investigating right now. It's related to association rule mining.

A bit of lore in data mining is the beer-diapers story. Fathers buying diapers on Thursday or Friday night also bought beer for over the weekend. This apparently caused some supermarkets to put diapers and beer closer together. So far for the lore. In every basket, there are regularities with a certain probability. If there's salad in the basket, there may be tomatoes too, or baskets with milk have a high probability that there are cereals for example.

The association rules for basket research are based on nominal properties: It's there or it's not. The problem of Netflix is more of a continuous problem... It's the question about whether there is a strong correlation, or implication with a level of confidence between ratings of different movies and each movie has five different possibilities. Also, there may be a strong correlation between 1.0f on one movie and 1.0f on the other, whilst there may be little evidence on A@5.0 -> B@4.0f. So, per rating, the support and confidence may differ. What we're trying to find for each movie/rating combination (which is 17,770*5*5*17,770*size(datatype)).

movieA@ratingX -> movieB@ratingY

The idea is also to filter out those correlations that don't have strong correlations. The biggest problem in association rule mining is memory. Because the matrix of 17,770 movies x 17,770 movies x 5 ratings (and sometimes x5 again) is a very large one, you can't really use data types that consume 4 bytes of memory, because that requires 8 GB of memory. So in my current implementation, I squeezed in a float into a single byte, thereby losing lots of precision, and then popping it back in the prediction phase. Since I got 4GB, I can just about run this.

Association rules are highly dependent on frequencies of observation. And it's necessary to take into account the frequency that movies are seen together versus the frequency that a movie is rated in isolation. The higher the ratio that movies are seen together and the stronger the observed rating combination between A and B, the better the predictive strength of the rule.

So, let's say user A rated movie 1 at a 1.0. If he also rated movie 2 at a 1.0 and there are many more users that did this, it means that the rating of movie 2 can be strongly derived from this association rule. It's also possible that many users rated 5.0 for movie 1, but a 4.0 for movie 2. Or rated 4.0 for 1 and 5.0 for 2. These correlations all suggest slightly different things. What I really wanted to do was store the confidence of these rules, but memory doesn't play nicely here and I had to think of something else.

In a sense, association rules are similar to clustering. The differences are mostly in the derivation of strong correlations between some movie A and movie B, whereas in clustering that is never determined. knn and clustering at the moment do produce better results. I'm getting 1.47 for example vs. reported results of 0.95-ish for knn and clustering approaches. Those approaches go down as far as 0.920 with improvements.

The imprecise-ness is very likely caused by incorrect filtering or imprecisions due to the memory space shortage and float compression. Pseudo-code for now looks as below. I've basically loaded all ratings twice. Once grouped by movieId (which customers rated this movie at what?) and the whole set again grouped by customerId (which movies did a customer rate at what?). The most important and wasteful array is the one that maintains compressed floats into unsigned chars (so losing loads of precision there). It's dimensioned by MAX_MOVIES, MAX_MOVIES and NUM_STARS. This means that given movie 1 in the first dimension, find out if there's a strong correlation factor for movie 2 in the second dimension, given that movie 1 was rated at x stars, where x is then another index into this huge array. The retrieved byte is then divided by 63 and 1.0f is added. Thus, each predictor is compressed into a single byte, reducing precision, but allowing everything inside a 1.5GB area of memory or so.

Having the training data twice allows one to access data very quickly. A problematic issue is how to store calculated confidence for each movie.

start:
clearMovieResultArray

for all movies i {
clearMovieConfidenceArray
clearMovieCountArray

for all customers c in i->ratings {
for all other movies k in c->ratings {
if k == m continue;
support[ k->movieId ][ i->rating[c] ][ k->rating ]++;
count[ k->movieId ][ i->rating[c] ]++;
}
}

for all movies m {
if ( freq-movies-rated-together / i->ratingCount ) <>

for all possible ratingstars j (NUM_STARS) {
for all possible ratingstars k (NUM_STARS) {
// Normalize movie support.
support[ m ][ j ][ k ] = support[ m ][ j ][ k ] / count[ m ][ j ];
float sum = 0.0f;
for ( int k = NUM_STARS-1; k >= 0; k-- ) {
support[ m ][ j ][ k ] = support[ m ][ j ][ k ] / count[ m ][ j ];
sum += support[ m ][ j ][ k ] * (k+1);
}
}
MovieResult[ i ][ m ][ j ] = (unsigned char)((sum - 1.0f) * 63 );
}
}
}


predictRating( short movieId, int custId )
{
for all movies m that this customer rated {
if support exists {
genRating = ((float)MovieResult[ m->movieId ][ movieId ][ m->Rating ] / 63 ) + 1.0f;
sum += genRating;
numSupport++;
}
}

if ( sum > 0.0f ) {
sum /= numSupport;
} else {
sum = ALL_DEFAULT_RATING;
}

if (sum > MAX_RATING) sum = MAX_RATING;
if (sum < sum =" MIN_RATING;

return sum;
}

Wednesday, May 06, 2009

Tikhonov Regularization

This post is about Tikhonov Regularization, which is used for statistical and predictive method. For systems where the predictions are nicely along the real values, like so:


Things are swell, because the predictions are on either side of the line. Basically, you have a good chance of finding a very good solution for this, as it looks like a well-posed problem. The (re)estimations are very regular positive and negative, yielding very good values for a linear regression of your found values, such that you can predict new values which you haven't initially trained for (for which you know the actual value).

Well, the netflix prize is facing an ill-posed problem. This basically means that there are a number of different solutions possible, or there are cases where the differences become so small, that it generates numerical instability when calculating that solution. I've basically seen this happen in some of my implementations when doing the blending.

So, what's done is that a regularization factor is introduced, which is giving penalties to larger factors, thereby conditioning the problem better (reducing the number of solutions). See an example what part of a graph might look like:

Okay, so in this case, we may have a prediction function which is pretty complicated and for a large number of values, which are actually connected to other dimensions, it's looking like this for part of the range and domain. If you'd grab this part of the graph and then try to refit this with different approaches into a better estimation overall, then chances are very high you'd have numerical instability here. Notice how many black points are below the line. The red line (the real values) are way above that. Even though the distance between the point and the line aren't necessary disturbing, when trying to do a regression on this sub-space of the graph, you'd end up with some very bad factors. It may be better to just follow the red line along the bottom a bit, because if you'd regress towards different factors, you'd get the same problem elsewhere along the road.

Now, for a little bit of philosophy, read Occam's razor. This basically states: "The simplest explanation for a phenomenon is most likely the correct explanation".
Other methods for inferring evolutionary relationships use parsimony in a more traditional way. Likelihood methods for phylogeny use parsimony as they do for all likelihood tests, with hypotheses requiring few differing parameters (i.e., numbers of different rates of character change or different frequencies of character state transitions) being treated as null hypotheses relative to hypotheses requiring many differing parameters. Thus, complex hypotheses must predict data much better than do simple hypotheses before researchers reject the simple hypotheses. Recent advances employ information theory, a close cousin of likelihood, which uses Occam's Razor in the same way.
Thus, it's better to use models with fewer parameters than it is to use models that are using many, many different parameters. Find those models which describe the problem well, then merge them together.

Back to Tikhonov... If you're also a contender in the netflix prize, check out the following source, which is heavily chopped down in complexity, improved in readability and derived from the source of linalg, which was developed by gravity. This source is not likely usable without the use of their linalg source codes, since it uses PseudoInverse.cpp for example:

Link to main.cpp

The regfactor and regfactorbias also exist in linalg and those are key towards bringing down the rmse. Remember that we potentially have numerical instability, which is why we want to introduce regularization. The regularization conditions the problem, after which better solutions are found. Better solutions provide better fits, reducing error. You'd prefer these regularization terms as close to 0.0f as possible, because when this reg term goes towards 0.00f, you'll go towards the unregularized solution of least squares regression. It'd be great to get there, but the problem itself is ill-posed, so we need some regularization at least.

I did rip out the fancy parts like cross-validation (used to find optimal values) and rmse reporting, such that you can follow the code better. In the pseudo-inverse, it's basically executing the linear least square solver.

The returned array is an array of weights, which are used to multiply with a bias of 1.0f, another weight for algo1, another for algo2... If you like, you could easily add other algorithms and this thing will give you reasonable weights in return.