Package: rankfmc
RankFM[original author]RankFM is a python implementation of the generalFactorization Machinesmodel class adapted for collaborative filtering recommendation/ranking problems with implicit feedback user/item interaction data. It usesBayesian Personalized Ranking (BPR)and a variant ofWeighted Approximate-Rank Pairwise (WARP)loss to learn model weights via Stochastic Gradient Descent (SGD). It can (optionally) incorporate sample weights and user/item auxiliary features to augment the main interaction data.The core (training, prediction, recommendation) methods are written inCython, making it possible to scale to millions of user/item interactions. Designed for ease-of-use, RankFM accepts bothpd.DataFrameandnp.ndarrayinputs - you do not have to convert your data toscipy.sparsematrices or re-map user/item identifiers prior to use. RankFM internally maps all user/item identifiers to zero-based integer indexes, but always converts its output back to the original user/item identifiers from your data, which can be arbitrary (non-zero-based, non-consecutive) integers or even strings.In addition to the familiarfit(),predict(),recommend()methods, RankFM includes additional utilitiessimiliar_users()andsimilar_items()to find the most similar users/items to a given user/item based on latent factor space embeddings. A number of popular recommendation/ranking evaluation metric functions have been included in the separateevaluationmodule to streamline model tuning and validation.see theQuickstartsection below to get started with the basic functionalitysee the/examplesfolder for more in-depth jupyter notebook walkthroughs with several popular open-source data setssee theOnline Documentationfor more comprehensive documentation on the main model class and separate evaluation modulesee theMedium Articlefor contextual motivation and a detailed mathematical description of the algorithmDependenciesPython 3.6+numpy >= 1.15pandas >= 0.24InstallationPrerequisitesTo install RankFM's C extensions you will need theGNU Compiler Collection (GCC). Check to see whether you already have it installed:gcc --versionIf you don't have it already you can easily install it usingHomebrewon OSX or your default linux package manager:# OSX
brew install gcc

# linux
sudo yum install gcc

# ensure [gcc] has been installed correctly and is on the system PATH
gcc --versionPackage InstallationYou can install the latest published version from PyPI usingpip:pip install rankfmcOr alternatively install the current development build directly from GitHub:pip install git+https://github.com/etlundquist/rankfm.git#egg=rankfmIt's highly recommended that you use anAnacondabase environment to ensure that all core numpy C extensions and linear algebra libraries have been installed and configured correctly. Anaconda: it just works.QuickstartLet's work through a simple example of fitting a model, generating recommendations, evaluating performance, and assessing some item-item similarities. The data we'll be using here may already be somewhat familiar: you know it, you love it, it's theMovieLens 1M!Let's first look at the required shape of the interaction data:user_iditem_id323353778610It has just two columns: auser_idand anitem_id(you can name these fields whatever you want or use a numpy array instead). Notice that there is noratingcolumn - this library is forimplicit feedbackdata (e.g. watches, page views, purchases, clicks) as opposed toexplicit feedbackdata (e.g. 1-5 ratings, thumbs up/down). Implicit feedback is far more common in real-world recommendation contexts and doesn't suffer from themissing-not-at-random problemof pure explicit feedback approaches.Now let's import the library, initialize our model, and fit on the training data:fromrankfm.rankfmimportRankFMmodel=RankFM(factors=20,loss='warp',max_samples=20,alpha=0.01,sigma=0.1,learning_rate=0.1,learning_schedule='invscaling')model.fit(interactions_train,epochs=20,verbose=True)# NOTE: this takes about 30 seconds for 750,000 interactions on my 2.3 GHz i5 8GB RAM MacBookIf you setverbose=Truethe model will print the current epoch number as well as the epoch's log-likelihood during training. This can be useful to gauge both computational speed and training gains by epoch. If the log likelihood is not increasing then try upping thelearning_rateor lowering the (alpha,beta) regularization strength terms. If the log likelihood is starting to bounce up and down try lowering thelearning_rateor usinglearning_schedule='invscaling'to decrease the learning rate over time. If you run into overflow errors then decrease the feature and/or sample-weight magnitudes and try uppingbeta, especially if you have a small number of dense user-features and/or item-features. SelectingBPRloss will lead to faster training times, butWARPloss typically yields superior model performance.Now let's generate some user-item model scores from the validation data:valid_scores=model.predict(interactions_valid,cold_start='nan')this will produce an array of real-valued model scores generated using the Factorization Machines model equation. You can interpret it as a measure of the predicted utility of item (i) for user (u). Thecold_start='nan'option can be used to set scores tonp.nanfor user/item pairs not found in the training data, orcold_start='drop'can be specified to drop those pairs so the results contain no missing values.Now let's generate our topN recommended movies for each user:valid_recs=model.recommend(valid_users,n_items=10,filter_previous=True,cold_start='drop')The input should be apd.Series,np.ndarrayorlistofuser_idvalues. You can usefilter_previous=Trueto prevent generating recommendations that include any items observed by the user in the training data, which could be useful depending on your application context. The result will be apd.DataFramewhereuser_idvalues will be the index and the rows will be each user's top recommended items in descending order (best item is in column 0):0123456789323961265357342858317512028173565608161716103418590474858377924103685891036257120282000122011971107801954Now let's see how the model is performing wrt the included validation metrics evaluated on the hold-out data:fromrankfm.evaluationimporthit_rate,reciprocal_rank,discounted_cumulative_gain,precision,recallvalid_hit_rate=hit_rate(model,interactions_valid,k=10)valid_reciprocal_rank=reciprocal_rank(model,interactions_valid,k=10)valid_dcg=discounted_cumulative_gain(model,interactions_valid,k=10)valid_precision=precision(model,interactions_valid,k=10)valid_recall=recall(model,interactions_valid,k=10)hit_rate: 0.796
reciprocal_rank: 0.339
dcg: 0.734
precision: 0.159
recall: 0.077That's a Bingo!Now let's find the most similar other movies for a few movies based on their embedding representations in latent factor space:# Terminator 2: Judgment Day (1991)model.similar_items(589,n_items=10)2571                       Matrix, The (1999)
1527                Fifth Element, The (1997)
2916                      Total Recall (1990)
3527                          Predator (1987)
780             Independence Day (ID4) (1996)
1909    X-Files: Fight the Future, The (1998)
733                          Rock, The (1996)
1376     Star Trek IV: The Voyage Home (1986)
480                      Jurassic Park (1993)
1200                            Aliens (1986)I hope you like explosions...# Being John Malkovich (1999)model.similar_items(2997,n_items=10)2599           Election (1999)
3174    Man on the Moon (1999)
2858    American Beauty (1999)
3317        Wonder Boys (2000)
223              Clerks (1994)
3897      Almost Famous (2000)
2395           Rushmore (1998)
2502       Office Space (1999)
2908     Boys Don't Cry (1999)
3481      High Fidelity (2000)Let's get weird...