A.I, Data and Software Engineering

Create bipartite graph from a rating matrix

C

As deep learning on graphs is trending recently, this article will quickly demonstrate how to use networkx to turn rating matrices, such as MovieLens dataset, into graph data.

The rating data

We use rating data from the movie lens. The rating data is loaded into rdata which is a Pandas DataFrame. This article demonstrates how to preprocess movie lens data.

After processing, the rdata should look like this:

userIdmovieIdratingtimestamp
01962423881250949
11863023891717742
2223771878887116
3244512880606923
41663461886397596

Nevertheless, we should avoid confusion between userId and movieId. Therefore, we added the prefix for each id as follow.

userIdmovieIdratingtimestamp
0u196i2423881250949
1u186i3023891717742
2u22i3771878887116
3u244i512880606923
4u166i3461886397596

Transform the matrix to a bipartite graph

We will use networkx to create a bipartite undirected weighted graph. It is simple as follows.

Get graph properties

First, we can get the basic information about the graph

We now can check if the graph is directed, multi-graphs, or bipartite.

Next, we can get a more detailed insight into this graph.

Visualize the graph

For better visualization, we first map nodes with two colours:

After that, we use networkx to draw the graph, spring and bipartite.

graph with spring layout
Draw graph with spring layout

Otherwise, we can use the classical plot for bipartite graph as flow.

Bipartite graph of movie lens 100k.

Now, the graph is ready for your learning algorithm.

Add comment

A.I, Data and Software Engineering

PetaMinds focuses on developing the coolest topics in data science, A.I, and programming, and make them so digestible for everyone to learn and create amazing applications in a short time.

Pin It on Pinterest

Newsletters

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Petaminds will use the information you provide on this form to be in touch with you and to provide updates.