Pages

Collaborative Filtering : Implementation with Python!

Tuesday, November 10, 2009




Continuing the recommendation engines articles series, in this article i'm going to present an implementation of the collaborative filtering algorithm (CF), that filters information for a user based on a collection of user profiles. Users having similar profiles may share similar interests. For a user, information can be filtered in/out regarding to the behaviors of his or her similar users.

Users profiles can be collected either explicitly or implicitly. One can explicitly ask users to rate what they have used/purchased. Such a profile is filled explicitly by the user ratings. An implicit profile is based on passive observation and contains users historic interaction data.

The most common usage of Collaborative Filtering is to make recommendation. That's why collaborative filtering is strongly correlated to recommender system in literature.

The implementation shown here will be at Python, so if you're not familiar with the programming language you can see more about it here. The pros of using Python is that with so less lines of code you can easily make the things running. Regardless of the underlying implementation, collaborative filters tend to try to solve the same broad problem using much the same data.

Generally you have a crowd of users, a big pile of items and some of the users rated them(what they think). Finally, you want to suggest more items to a user and you'd prefer to make your recommendations relevant to their likely interests. As you will see, that the algorithm suggest that you could use the opinions that people have recorded about items they have bought, to give a good guess as to which items they haven't bought, but might like.


The first thing is to collect the preferences of the users. My Collaborative Filtering implementation stores its data in two 2D matrices. So for each user in a row we have columns for each item that he rated, as you can see at the Figure 01 below.
Figure 01. The 2D Matrix User:Book:Rating

To keep things simple, let's represent our matrices as two levels of Python dict objects (a dictionary is simply a hash table, if you're not familiar with Python). The key of each dict is a userID, so to get the rate which the user "Bryan" gave to the book "Classical Mythology" we look in first-level dict for "Bryan", then the second-level dict for "Lost Symbol". Our problem scope here will be book recommendations. The complete dataset can be found free here at this link for download. Free available for research, the Book-Crossing dataset contains 278,858 users (anonymized) providing 1,149,780 ratings (explicit/implicit) about 271,379 books in a 4-week crawl (August/September 2004).

In this article, we will use only use only the data stored in Bx-books.csv and Bx-book-Ratings.csv, that contain the list of identifiers, titles of the books and the ratings gave by the users respectively. To download the data already pre-processed, click here. If you prefer to do it all by yourself, i also provided some code (loadDataset) in the implementation. It's important to notice that the user represented in this data set is represented by an unique numeric identifier for privacy of the users.

>>>from critics import *
>>>critics['228054']
{'Fortune': 6.0}
>>>

After collecting the data related to the stuff that the users prefer, you need somehow a metric to determine how similar the users are compared to your tastes. To measure this, you have to compare each user with other using a similar measure distance. There are some functions to evaluate this metric, but in this article i will use the euclidian distance and pearson correlation. I am not going to explain the mathematics behind those measure distances, because you can find a lot of information about them out of a hat. The basic idea behind those measures is that the more the users have similar tastes the more they are next to each other in the preferences search space. Which one to use? Depends on your problem, test all and verify which one get better results. Generally, the Pearson correlation gets slightly better results, since it shows how much the variables change together. To play with them, check the implementation of the functions sim_pearson or sim_euclidean. Those functions will be used as parameters of the functions defined in the rest of this article.

>>>recommendations.sim_distance(critics,'98556', '180727')
0.058823529411764705
>>>
>>> recommendations.sim_pearson(critics.critics,'180727', '177432')
0.6622661785325219
>>>

Now that we have the measure distances to compare two users, we now can define other function to classify all users compared to a specified user and find the one that is most similar. In this particular case, the goal is to find users that rated and have the similar taste so i can know who i can ask for advice when i want to choose a book. The function topMatches returns a sorted list of n users with similar preferences to a specified user. Now, with the list, you can see the ratings done by other users that have similar preferences as me. So the idea i should see the books that she rated, then choose new books.

>>> recommendations.topMatches(critics.critics,'98556',10,recommendations.sim_distance)
[(1.0, '69721'), (1.0, '28667'), (1.0, '224646'), (1.0, '182212'),
(1.0, '11676'), (0.5, '4157'), (0.5, '28729'), (0.5, '224650'), (0.5, '199616'), 
(0.5, '189139')]
>>> recommendations.topMatches(critics.critics,'180727', 3) 
[(1.0, '189139'), (1.0, '11676'), (0.6622661785325219, '177432')]


Find someone similar to read recommendations is great, but generally what we really want is to make recommendation of books not users. I could simply look to the user profile and seek for books the user likes and i haven't read yet, but this it's not so clever. This approach could eventually result in a user that haven't done an evaluation on books that i could like. It could also return a user that liked a movie that was badly evaluated (low rates) by all other users returned by the topMatches. To solve those problems, you have to give rates to items using a weighted average that can properly classify the evaluations. The implementation code for this items recommendation is simple and work with both measure distances.



The code of the function getRecommendations looks at each user except the one passed as parameter. It calculates how similar the users are to the specified user and after looks at each item rated by those users. As result you now have a classified books list and also a estimated rate that i would give for each book in it. This report allows me to choose which book i want to read or not, or if i prefer to do other thing than read it. It's important to notice that you can decide not to make recommendations if any result achieves a specified threshold by the user.

>>> recommendations.getRecommendations(critics.critics,'180727')[0:3]
[(10.000000000000002, 'The Two Towers (The Lord of the Rings, Part 2)'),
(10.000000000000002, 'The Return of the King (The Lord of the Rings, Part 3)'),
(10.000000000000002, 'Hawaii')] 

>>> recommendations.getRecommendations(critics.critics,'180727', 
    similarity=recommendations.sim_distance)[0:4] 
[(10.000000000000002, 'Dune'), (10.000000000000002, 'Best Friends'), 
(10.000000000000002, 'All Creatures Great and Small'),
(10.000000000000002, 'A Christmas Carol (Dover Thrift Editions)')] 

Now we know how to find similar users and recommend items to a user, but how about finding similar items ?! You see those recommendations at web stores in the internet, specially when the store hasn't collected many information about your preferences. One of web stores that uses this type of recommendations is the Amazon web store, as you can see it here.


Figure 02. Amazon Web Store Recommendation System


In this case, you can evaluate the similarity, searching for users that liked a particular item and seeing others that appreciated in the same way. To do this, you can use the same functions defined earlier in this article, the only change is to replace the users by items now. So you can find similar items to the specified item.

I provided a function transformPrefs to do that. It rebuilds the new dictionary now with the key value with the book name and as values the pairs (user,rate).



>>> critics = recommendations.transformPrefs(critics)
>>> critics
[(1.0, 'Year of Wonders'), {'Robin Hood (Penguin Popular Classics)': {'81263': 8.0, '128653': 8.0},
 'Collected short stories [of] W. Somerset Maugham': {'180651': 8.0}, 
'Signing Naturally: Student Videotext and Workbook Level 1 
(Vista American Sign Language Series Functional Notional Appr)': {'236948': 9.0}, 
'Looking For Laura': {'98391': 8.0, '255952': 8.0, '5582': 4.0, '250192': 9.0, '72352': 7.0, 
'182085': 10.0, '67775': 7.0}
....


It's not so obvious that changing users to items it will lead to useful results, but in many cases it will make possible to do interesting comparisons. Imagine a web store that collect buying historic profiles with the purpose of recommend products to people in particular. Revert people to products, you can allow the system now recommend users that could buy specific products. It's very useful when the marketing department of your company want to do a great marketing effort to a big cut-off prices sales. Or it could be also be used to check if links recommended show in a web page are really seen by users that have a great probability of liking them.

>>> recommendations.topMatches(critics,'Drums of Autumn')
[(1.0, 'Year of Wonders'), (1.0, 'Velvet Angel'), (1.0, 'Twice Loved'), 
(1.0, 'Trying to Save Piggy Sneed'), (1.0, 'The Zebra Wall')]


If you want to recommend specific people that have done the evaluation about a book. If you want to send invitations to a book launch event ?!

>>> recommendations.getRecommendations(critics,'The Weight of Water')[0:5]
[(10.000000000000002, '92048'), (10.000000000000002, '211152'), (10.000000000000002, '198996'), 
(10.000000000000002, '156467'), (10.0, '99298')]


So that's it. I expect you enjoyed this article. As you can see the recommendation engine using collaborative filtering is very effective when you don't have a great amount of items or users. When you deal with a big store like Amazon, that has millions of users and items - compare one user against all others , then each evaluated item can be extremely slow. An alternative technique to get over this limitation is the Item-based-filtering. It's very useful in cases when you have a big dataset. This technique can give better results and allows that many calculations be done previously before a user ask for a recommendation, consequently, showing the recommendations quickly.

You can download a copy of my sample collaborative filtering implementation as collaborative_recommendation.py. In the next article we will study about the item-based-filtering technique.

PS: I'm planning with other colleague Ricardo Caspirro to develop a library in Python for recommendations. We are very excited and planning great stuff for the python and recommendation systems enthusiasts! Wait for great news soon!

See'ya,

Marcel Caraciolo

References

Introduction to Recommendation Systems

Monday, October 5, 2009


Hi all,

Let's begin another article's series. Now i will talk about recommendation systems and how we can implement some simple recommendation algorithms using information filtering with functional examples. You probably already came into recommendation systems but you didn't know.

There are some examples: Amazon, Netflix, etc. They generally register the user preference and based on this profile, it uses it (the information inside it) to suggest new products that you may like. It's a powerful system and you can use it to build systems that find people that have the same preference as you or make automatic suggestions based on preferences and tastes that other people like.

To start, let's introduce what's a recommendation system.

1 - Recommender Systems

"A recommender system can be defined as "any system that produces individualized recommendations as output or has the effect of guiding the user in a personalized way to interesting or useful objects in a large space of possible options. " (Burke 2002).

The problem being addressed is that "too much information", challenging those in search of something to find that which is interesting within the vast array available.
From wikipedia we can see the following definition:

"Recommender systems form a specific type of information filtering (IF) technique that attempts to present information items (movies, music , books , news images, web pages, etc.) that are likely of interest to the user. Typically, a recommender system compares the user's profile to some reference characteristics, and seeks to predict the 'rating' that a user would give to an item they had not yet considered. These characteristics may be from the information item (the content-based approach) or the user's social environment (the collaborative filtering approach).

Recommender systems have been around since the early nineties and have evolved to meet the needs of e-commerce, research, museums and collections, digital libraries and entertainment. The volume of literature on recommender systems seems to be becoming as large as the problem itself and a high level model was proposed in order to find a path through this array of information and to guide the selection of information about recommender systems. The Figure 1 shows the main elements of a recommender system and describes the nature of the links between the elements.


Figure 01. Recommendation Systems Schemma

Recommendation is carried out by some kind of recommendation engine which employs a set of algorithms to compare a user profile with a set of reference characteristics. There are three types of source for the reference characteristics: Information about the items themselves (content), information about the social environment (collaborative) and information about the web usage (web analytics). Actually many tools use a mix of these techniques and they are a set of the information filtering systems.

Information Filtering System is a system that removes redundant or unwanted information from an information stream using (semi) automated methods in order to present to a human user. In the recommendation systems context, to do this the user's profile is compared to some reference characteristics as the content-based approach or the user's social environment (collaborative filtering approach). In the next section we will see those types of Information Filtering (IF).

2 - Information Filtering (IF)

2.1- Content-based-Filtering

Content based filtering uses information about the items to make recommendations. It will recommend items to a user if the items are similar in content to items that the user liked in the past. This approach allows recommendation of previously unrated items to users with unique interests and can provide explanations for its recommendations. As long as the system has some information about an item, recommendations can be mad even if the system has received a small number of ratings, or none at all. The disadvantage of this mechanism is that each item must be characterized with respect to the features that appear in the user's profile requiring modelling of each user's profile.

2.2- Collaborative Filtering

Collaborative filtering makes predictions about the interests of a user by collecting the choices or expressions of taste from many users. It finds areas of agreement between people and bases recommendations on the assumption that people who agreed in the past are likely to do so in the future. It looks for users who share the same ratings patterns with the active user, a neighbourhood of similar users, and uses their ratings to create a prediction. Unlike content-based filtering, it doesn't need to know anything about the item themselves, only people's opinions about the items.

Collaborative filtering may be based on the explicit ratings of users or on implicit observation of user behaviour. User behaviour is observed and compared to the behaviour of other users, for example, items purchased, queries made, items printed, or music listened to. Predictions can then be made about a user's future behaviour assuming like-mindedness in the past as a predictor for future patterns of behaviour.

There are two problems in this system of users and ratings: the 'first-rater problem' and 'cold-start problem'. The first-rater problem occurs when a new item goes into the system and has not yet received any ratings, preventing it from being recommended. The cold-start problem occurs for new users, about whom there is insufficient information from their active ratings or observed behaviour with which to predict their preferences.

Now that we presented some popular IF techniques, let's go further through those methods and see them in action. In the next article i will present some filtering techniques with their implementation on Python programming language.

Stay tunned!

Marcel Pinheiro Caraciolo

References

[1] http://en.wikipedia.org/wiki/Recommender_systems

[2] http://en.wikipedia.org/wiki/Information_filtering

[3] http://en.wikipedia.org/wiki/Collaborative_filtering

Particle Swarm Optimization (PSO) running on CellPhones (Symbian + 5800Xpress)

Tuesday, September 29, 2009


Hi all,

Have you ever imagined running optimization algorithms like genetic algorithms or particle swarm optimization on portable devices like cellphones ?

So, let me say that it's possible! First of all, one excellent work on running genetic algorithms on devices like Sony PSP and Symbian Phones was done by Christian Perone, author of the PyEvolve Framework (Python Genetic Algorithms Framework) written all in Python!

His work inspired me to port my old undergraduate project, the particle swarm optimization algorithm implementation in Java to Python! I decided to develop it from scratch and now it's almost complete for its first official release: The PyPSO Toolbox. You can take a look at the project and the source at its official home page repository.

Soon, it will be official available! Until there, i am doing some tests with the framework, correcting some bugs, documenting the source code, etc. But i was wondering here if it's possible to run also the PyPSO framework in the cellphone, like the Symbian Nokia 5800 XpressMusic.

Using the new version of the PyS60, the release 1.9.7, which comes with the new 2.5.1 Python core, I've executed the PyPSO toolbox without problems, and i was very amazed by the good performance of the PSO on the Nokia 5800, the problem that i ran was the minimization of one of the De Jogn's test suite functions, the Sphere function. The function is very simple as you can see its plot below at 3-D chart:

I've used particles with 5 dimmensions each with real values between the interval of [-5.12, 5.12], the Constricted Factor and the Global Topology of the PyPSO framework. Also i've set a population size of 30 particles.

After 36 iterations (about 12 seconds), the PSO execution ended with the best fitness of 0.0, representing the optimal solution (the minimum) of the De Jong's Sphere function.

Follow some screenshots of the simulation (click on the pictures to enlarge):





How to install PyPSO on the PyS60 ?

1) First, you need to install the PyS60 runtime for your Symbian platform. You can see more information about how to install it here.

2) Then, you must create a directory on your Memory Card or Phone Memory (Depends on where you installed the Python Script Shell), inside the "Python" directory, named "lib" , and inside this directory, you copy the "pypso" folder. The absolute folder structure will be like this:

C:\Python\lib\pypso or E:\Python\lib\pypso

Some features of the framework will not work, like some report Adapters, however, the PSO core is working really great. I've used the PyPSO subversion release 0.11. Since it's not finished yet, you can download from the subversion repository from here.

Here is the source code I've used to minimize the De Jong's Sphere function (Special thanks to Christian Perone who inspired me to do this work) :


"""
PyPsoS60Demo.py
Author: Marcel Pinheiro Caraciolo
caraciol@gmail.com
License: GPL3
"""
BLUE = 0x0000ff
RED = 0xff0000
BLACK = 0x000000
WHITE = 0xffffff


import e32, graphics, appuifw
print "Loading PyPSO modules... ",
e32.ao_yield()

from pypso import Particle1D
from pypso import GlobalTopology
from pypso import Pso
from pypso import Consts

img = None
coords = []
graphMode = False
canvas = None
w = h = 0
print " done !"
e32.ao_yield()

def handle_redraw(rect):
if img is not None:
canvas.blit(img)


def sphere(particle):
total = 0.0
for value in particle.position:
total += (value ** 2.0)

return total

def pso_callback(pso_engine):
it = pso_engine.getCurrentStep()
best = pso_engine.bestParticle()
if graphMode:
img.clear(BLACK)
img.text((5, 15), u"Iteration %d - Best Fitness: %.2f" % (it,best.ownBestFitness), WHITE, font=('normal', 14, appuifw.STYLE_BOLD))
img.line((int(w/2),0,int(w/2),h),WHITE)
img.line((0,int(h/2),w,int(h/2)),WHITE)

cx = int(w/2) / int(best.getParam("rangePosmax"))
cy = int(-h/2) / int(best.getParam("rangePosmax"))

for particle in pso_engine.topology:
img.point([int(cx*particle.position[0]+ (w/2)),int(cy*particle.position[1]+(h/2)),5,5],BLUE,width=4)
img.point([int(cx*best.ownBestPosition[0]+ (w/2)),int(cy*best.ownBestPosition[1]+(h/2)),5,5],RED,width=4)
handle_redraw(())
else:
print "Iteration %d - Best Fitness: %.2f" % (it, best.ownBestFitness)
e32.ao_yield()

return False


def showBestParticle(best):
global graphMode

if graphMode:
img.clear(BLACK)
img.text((5, 15), u"Best particle fitness: %.2f" % best.ownBestFitness, WHITE, font=('normal', 14, appuifw.STYLE_BOLD))
img.line((int(w/2),0,int(w/2),h),WHITE)
img.line((0,int(h/2),w,int(h/2)),WHITE)
cx = int(w/2) / int(best.getParam("rangePosmax"))
cy = int(-h/2) / int(best.getParam("rangePosmax"))
img.point([int(cx*best.ownBestPosition[0]+ (w/2)),int(cy*best.ownBestPosition[1]+(h/2))],RED,width=7)
handle_redraw(())
e32.ao_sleep(4)
else:
print "\nBest particle fitness: %.2f" % (best.ownBestFitness,)


if __name__ == "__main__":
global graphMode, canvas, w, h

data = appuifw.query(u"Do you want to run on graphics mode ?", "query")

graphMode = data or False

if graphMode:
canvas = appuifw.Canvas(redraw_callback=handle_redraw)
appuifw.app.body = canvas
appuifw.app.screen = 'full'
appuifw.app.orientation = 'landscape'
w,h = canvas.size
img = graphics.Image.new((w,h))
img.clear(BLACK)
handle_redraw(())
e32.ao_yield()

#Parameters
dimmensions = 5
swarm_size = 30
timeSteps = 100

particleRep = Particle1D.Particle1D(dimmensions)
particleRep.setParams(rangePosmin=-5.12, rangePosmax=5.13, rangeVelmin=-5.12, rangeVelmax=5.13, bestFitness= 0.0 ,roundDecimal=2)
particleRep.evaluator.set(sphere)

topology = GlobalTopology.GlobalTopology(particleRep)
pso = Pso.SimplePSO(topology)
pso.setTimeSteps(timeSteps)
pso.setPsoType(Consts.psoType["CONSTRICTED"])
pso.terminationCriteria.set(Pso.FitnessScoreCriteria)
pso.stepCallback.set(pso_callback)
pso.setSwarmSize(swarm_size)

pso.execute()

best = pso.bestParticle()
showBestParticle(best)

To make things more interesting, i've decided to put a simple graphic mode, when the user can choose to see the simulation in graphics mode or console mode. So as soon as you start the PyPsoS60Demo.py script, a dialog will show up to ask which mode the user prefer to see the simulation. You can see the video of the graphics mode running below.




Each point is a particle and they're updating their position through the simulation and since the best optimal solution of the problem is the point (0,0), in the end of the simulation, the particles will be close to the best solution. You can see that the red point is the best particle of all swarm.

You can note at the source code the use of the module "e32" of the PyS60, this is used to process pending events, so we can follow the statistics of the current iteration while it evolves.

I hope you enjoyed this work, the next step is to port the Travelling Salesman Problem to cellphone!

You can download the script above here.

Marcel Pinheiro Caraciolo

Artificial Intelligence goes Mobile



Hi Folks,

I' am Marcel Pinheiro Caraciolo, master degree candidate at Federal University of Pernambuco (CIN/UFPE) located at Recife - Pernambuco - Brazil. As you can see, i am one of the main authors of the A.I. In Motion Blog (funny but the only one who posts here, but this is not the case!). My interests are about artificial intelligence and mobile computing. How to connect them is my daily work and my master thesis will be specific about data mining algorithms (as you saw in the last posts about data mining) and recommendation systems targeted to Mobile devices. On a next post i will talk further about it.

But, in general, one of my goals at my master degree thesis is to study and apply artificial intelligence and data mining algorithms into mobile computing, solving problems or turning possible those machine learning algorithms to offer their results or run them into small and limited processing devices like cell phones.



Let's build real Smart Phones!!


For inspiring our readers to read more about artificial intelligence and mobile computing connected, i've found this article in the internet: "The Artificial Intelligence goes Mobile" An excellent reading for people who wants to inspire themselves and think how the artificial intelligence can be applied at mobile devices. This article was the Introductory remarks of the Artificial Intelligence in Mobile Systems - AIMS2000 Workshop at 2000.
So , stay tuned! More content and tutorials about those topics will be presented here!

Regards,

Marcel Pinheiro Caraciolo

Mobile Recommender Systems


Hi Folks,

I am Marcel Pinheiro Caraciolo , the main author of this blog!

One of my goals at my master degree thesis is to study and apply artificial intelligence and data mining algorithms into mobile computing, solving problems or turning possible those machine learning algorithms run into small and limited processing devices like cell phones. I've already talked about this topic here.

I'm studying now about recommendation system engines and my plan is to develop a system based on machine learning techniques , data mining to offer specific products and services for mobile users that buys using the mobile phone. Based on mobile technology, the system will be possible to estimate by mobile payment the profile of a specific client and recommend products and services into the mobile device screen, with some profile analysis of the user behavior and consuming of products acquired using the mobile phone. We can resume the system features into 3 key points:

(a) Estimate the profile of clients and sellers to make recommendations of services and products.
(b) The automatic discovery of knowledge with induction of rules that explain the operational behavior on cellphones.

(c) The investigation of profiles on any characteristics in the mobile transactions (region, age, gender, consume, salary, habits, etc.)

During those months we will study a lot about data mining algorithms, mobile computing and recommender systems. Stay tuned!

Marcel Pinheiro Caraciolo