Package: markovclick
markovclickPython implementation of the R packageclickstreamwhich models website clickstreams as Markov chains.markovclickallows you to model clickstream data from websites as Markov chains, which can then be used to predict the next likely click on a website for a user, given their history and current state.RequirementsPython 3.Xnumpymatplotlibseaborn (Recommended)pandasInstallationpython setup.py installorpip install markovclickTestsTests can be run using thepytestcommand from the root directory.DocumentationDocumentation can be viewed athttps://markovclick.readthedocs.io/.
To build the documentation, runmake htmlinside the/docsdirectory.UsageQuick startTo start using the package without any data,markovclickcan produce dummy data for you to experiment with:frommarkovclickimportdummyclickstream=dummy.gen_random_clickstream(n_of_streams=100,n_of_pages=12)TerminologyIn the context of this package, streams refer to a series of clicks belonging to a given user. The time difference between clicks is defined by the user when assembling these streams, but is typically taken to be 30 minutes in the industry.The pages refer to the individual clicks of the user, and thus the pages they visit. Rather than storing the entire URL of the page the user visits, it is better to encode pages using a simple code such asPXXwhereXcan be any number. This strategy can be used to group similar pages under the same code, as modelling them as separate pages is sometimes not useful leading to an excessively large probability matrix.Building Markov chainsTo build a Markov chain from the dummy data:frommarkovclick.modelsimportMarkovClickstreamm=MarkovClickstream(clickstream)The instancemof theMarkovClickstreamclass provides access the class's attributes such as the probability matrix (m.prob_matrix) used to model the Markov chain, and the list of unique pages (m.pages) featuring in the clickstream.PageRank scoreThe PageRank score for each page in the clickstream can also be calculated as follows:digraph,pagerank=m.calculate_pagerank(max_nodes=2)ArgumentTypeDescriptionmax_nodesint(Optional, defaults to 2). The number of pages to include as nodes linking to each node when generating the graph. Selected in order of most probable transition from Markov chainpr_kwargsdict(Optional, defaults to{}). Dictionary to pass arguments tonetworkx.linkanalysis.pagerank()function. See detailshere.Thedigraphobject holds thenetworkxDiGraphclass which was used to calculate the PageRank score, and thepagerankobject is a dictionary of PageRank scores for each page in the network.VisualisationVisualising as a heatmapThe probability matrix can be visualised as a heatmap as follows:sns.heatmap(m.prob_matrix,xticklabels=m.pages,yticklabels=m.pages)Visualising the Markov chainA Markov chain can be thought of as a graph of nodes and edges, with the edges representing the transitions from each state.markovclickprovides a wrapper function around thegraphvizpackage to visualise the Markov chain in this manner.frommarkovclick.vizimportvisualise_markov_chaingraph=visualise_markov_chain(m)The functionvisualise_markov_chain()returns aDigraphobject, which can be viewed directly inside a Jupyter notebook by simply calling the reference to the object returned. It can also be outputted to a PDF file by calling therender()function on the object.In the graph produced, the nodes representing the individual pages are shown in green, and up to 3 edges from each node are rendered. The first edge is in a thick blue arrow, depicting the most likely transition from this page / state to the next page / state. The second edge depicted by a thinner blue arrow, depicts the second most likely transition from this state. Finally, a third edge is shown that depicts the transition from this page / state back to itself (light grey). This edge is only shown if the the two most likely transitions are not already to itself. For all transitions, the probability is shown next to the edge (arrow).Clickstream processing withmarkovclick.preprocessingmarkovclickprovides functions to process clickstream data such as server logs, which contain unique identifiers such as cookie IDs associated with each click. This allows clicks to be aggregated into groups, whereby clicks from the same browser (identified by the unique identifier) are grouped such that the difference between individual clicks does not exceed the maximum session timeout (typically taken to be 30 minutes).Sessionise clickstream dataSessioniseTo sessionise clickstream data, the following code can be used that require apandasDataFrame object.frommarkovclic.preprocessingimportSessionisesessioniser=Sessionise(df,unique_id_col='cookie_id',datetime_col='timestamp',session_timeout=30)ArgumentsArgumentTypeDescriptiondfDataFramepandasDataFrame object containing clickstream data. Must contain atleast a timestamp column, unique identifier column such as cookie ID.unique_id_colStringColumn name of unique identifier, e.g.cookie_iddatetime_colStringColumn name of timestamp column.session_timeoutIntegerMaximum time in minutes after which a session is broken.Sessionise.assign_sessions()With aSessioniseobject instantiated, theassign_sessions()function can then be called. This function supports multi-processing, enabling you the split job into multiple processes to take advantage of a multi-core CPU.sessioniser.assign_sessions(n_jobs=2)ArgumentsArgumentTypeDescriptionn_jobsIntegerNumber of processes to spawn to enable parallel processing. If set to1, no splitting occurs.Theassign_sessions()function returns the DataFrame, with an additional column added storing the unique identifier for the session. Rows of the DataFrame can then be grouped using this column.