Search code examples
sqlalgorithmsimilaritynearest-neighbor

How to find similar users using their interests


I am trying to create a system which would be able to find users with similar favourite movies/books/interests/etc., much like neighbours on last.fm. Users sharing the most mutual interests would have the highest match and would be displayed in user profiles (5 best matches or so).

Is there any reasonably fast way to do this? The obvious solution would be to create a table with user ids and interest ids and compare a user with all the other users, but that would take forever on a table with ... say million users each having 20 interests.

I assume some efficient solution exists, since last.fm is working quite well. I would prefer using some common SQL database like mySQL or pgSQL, but anything would do.

Thanks for your suggestions.


UPDATE:
As it turns out, the biggest problem is finding nearest neighbours in SQL databases, as none of the open-source ones supports this kind of search.
So my solution would be to modify ANN to run as a service and query it from PHP (using sockets for instance) - having even millions of users with say 7 dimensions in memory is not so much of a big deal and it runs unbelievably fast.

Another solution for smaller datasets is this simple query:

SELECT b.user_id, COUNT(1) AS mutual_interests
FROM `users_interests` a JOIN `users_interests` b ON (a.interest_id = b.interest_id)
WHERE a.user_id = 5 AND b.user_id != 5
GROUP BY b.user_id ORDER BY mutual_interests DESC, b.user_id ASC

20-50ms with 100K users each having ~20 interests (of 10 000 possible interests) on average


Solution

  • You want to solve the approximate nearest neighbor problem. Encode users characteristics as a vector in some space, and then find approximately the nearest other user in that space.

    What space exactly, and what distance metric you want to use are probably things to evaluate experimentally based on your data. Fortunately, there is a C++ package you can use to solve this problem with various metrics and algorithms to fit your needs: http://www.cs.umd.edu/~mount/ANN/

    Edit: Its true that the running time here is dependent on the number of features. But there is a handy theorem in high-dimensional geometry that says that if you have n points in arbitrarily high dimensions, and you only care about approximate distances, you can project them down into O(log n) dimensions without loss. See here (http://en.wikipedia.org/wiki/Johnson-Lindenstrauss_lemma). (A random projection is performed by multiplying your points by a random +1/-1 valued matrix). Note that log(1,000,000) = 6, for example.