Pandas to bipartite graph - python

I have already added nodes into my graph but i cant seem to understand the way to add the edges to it. The edges correspond to any value of 1 in my pivot tabel. The table is of the following form:
movie_id 1 2 3 4 5 ... 500
user_id ...
501 1.0 0.0 1.0 0.0 0.0 ... 0.0
502 1.0 0.0 0.0 0.0 0.0 ... 0.0
503 0.0 0.0 0.0 0.0 0.0 ... 1.0
504 0.0 0.0 0.0 1.0 0.0 ... 0.0
. ...
.
1200
This is the code i have used for my nodes:
B = nx.Graph()
B.add_nodes_from(user_rating_pivoted.index, bipartite=0)
B.add_nodes_from(user_rating_pivoted.columns, bipartite=1)
And i imagine the edges should be formed in a similar way :
add_edges_from(...) for idx, row in user_rating_pivoted.iterrows())

Let's add prefixes to those indices and columns, and use them as nodes to more easily associate the connections:
print(df)
movie_1 movie_2 movie_3 movie_4 movie_5 movie_6
user_1 1.0 1.0 1.0 1.0 0.0 0.0
user_2 1.0 0.0 0.0 0.0 0.0 0.0
user_3 0.0 1.0 0.0 0.0 0.0 1.0
user_4 1.0 0.0 1.0 0.0 1.0 0.0
In order to get the edges (and keep the node names) we could use pandas to transform a little the dataframe. We can get a MultiIndex using stack, and then indexing on the values that are 1.Then we can use add_edges_from to add all the edge data:
B = nx.Graph()
B.add_nodes_from(df.index, bipartite=0)
B.add_nodes_from(df.columns, bipartite=1)
s = df.stack()
B.add_edges_from(s[s==1].index)
We can use bipartite_layout for a nice layout of the bipartite graph:
top = nx.bipartite.sets(B)[0]
pos = nx.bipartite_layout(B, top)
nx.draw(B, pos=pos,
node_color='lightgreen',
node_size=2500,
with_labels=True)
Note that it is likely that these highly sparse matrices lead to disconnected graphs though, i.e graphs in which not all nodes are connected to some other node, and attempting to obtain both sets will raise an error as specified here.
AmbiguousSolution – Raised if the input bipartite graph is disconnected and no container with all nodes in one bipartite set is provided. When determining the nodes in each bipartite set more than one valid solution is possible if the input graph is disconnected.
In such case you can just plot as a regular graph with:
rcParams['figure.figsize'] = 10 ,8
nx.draw(B,
node_color='lightgreen',
node_size=2000,
with_labels=True)

Related

Adding labels information in k-core decomposition

I would need to visualize labels in a network where I extract kcore information.
The dataset is
Source Target Edge_Weight Label_Source Label_Target
0 A F 29.1 0.0 0.0
1 A G 46.9 0.0 1.0
2 A B 24.4 0.0 1.0
3 C F 43.4 0.0 0.0
4 C N 23.3 0.0 1.0
5 D S 18.0 1.0 0.0
6 D G 67.6 1.0 0.0
7 D B 37.2 1.0 1.0
8 D E 46.9 1.0 2.0
For extracting kcore information I used the code
G = nx.from_pandas_edgelist(df, 'Source', 'Target')
kcore=nx.k_core(G)
plt.subplot(122)
nx.draw(kcore)
plt.show()
Do you know I can add the label information?
My expected value would be a graph which has colors based on their labels (it does not matter which color to assign to distinct labels values. The values are 0, 1, 2).
Many thanks
A way to do what you want is to create a colormap and associate it to your node label. You can then use the node_colors argument from the nx.draw function to set up the color of the nodes. Additionally, you can use plt.scatter to create empty plots to set up a legend for your labels in your graph.
See code below:
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib import cm
df=pd.read_fwf('graph.txt') #Stored your dataset in a file called 'graph.txt'
G = nx.from_pandas_edgelist(df, 'Source', 'Target')
kcore=nx.k_core(G)
N_colors=3
cm_dis=np.linspace(0, 1,N_colors)
colors = [cm.viridis(x) for x in cm_dis]
color_nodes=[]
for node in kcore:
#Finding out label of the node
temp_src=df.index[df['Source'] == node].tolist()
temp_targ=df.index[df['Target']==node].tolist()
if len(temp_targ)!=0:
label=df['Label_Target'][temp_targ[0]]
color=colors[int(label)]
elif len(temp_src)!=0:
label=df['Label_Source'][temp_src[0]]
color=colors[int(label)]
#Setting up legend
if color not in color_nodes:
plt.scatter([],[],color=color,label=str(label))
color_nodes.append(color)
#Draw graph
nx.draw(kcore,with_labels=True,node_color=color_nodes)
plt.legend()
plt.show()
And the output gives:

Degree Centrality and Clustering Coefficient in Adjacent matrix

Based on a dataset extracted from this link: Brain and Cosmic Web samples, I'm trying to do some Complex Network analysis.
The paper The Quantitative Comparison Between the Neuronal Network and the Cosmic Web, claims to have used this dataset, as well as its adjacent matrixes
"Mij, i.e., a matrix with rows/columns equal to the number of detected nodes, with value Mij = 1 if the nodes are separated by a distance ≤ llink , or Mij = 0 otherwise".
I then probed into the matrix, like so:
from astropy.io import fits
with fits.open('mind_dataset/matrix_CEREBELLUM_large.fits') as data:
matrix_cerebellum = pd.DataFrame(data[0].data)
which does not print a sparse matrix, but rather a matrix with distances from nodes expressed as pixels.
I've learned that the correspondence between 1 pixel and scale is:
neuronal_web_pixel = 0.32 # micrometers
And came up with a method in order to convert pixels to microns:
def pixels_to_scale(df, mind=False, cosmos=False):
one_pixel_equals_parsec = cosmic_web_pixel
one_pixel_equals_micron = neuronal_web_pixel
if mind:
df = df/one_pixel_equals_micron
if cosmos:
df = df/one_pixel_equals_parsec
return df
Then, another method to binaryze the matrix after the conversion:
def binarize_matrix(df, mind=False, cosmos=False):
if mind:
brain_Llink = 16.0 # microns
# distances less than 16 microns
brain_mask = (df<=brain_Llink)
# convert to 1
df = df.where(brain_mask, 1.0)
if cosmos:
cosmos_Llink = 1.2 # 1.2 mpc
brain_mask = (df<=cosmos_Llink)
df = df.where(brain_mask, 1.0)
return df
Finally, with:
matrix_cerebellum = pixels_to_scale(matrix_cerebellum, mind=True)
matrix_cerebellum = binarize_matrix(matrix_cerebellum, mind=True)
matrix_cerebellum.head(5) prints my sparse matrix of (mostly) 0.0s and 1.0s:
0 1 2 3 4 5 6 7 8 9 ... 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857
0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
1 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
4 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
5 rows × 1858 columns
Now I would like to calculate:
Degree Centrality of the network, given by the formula:
Cd(j) = Kj / n-1
Where kj is the number of (undirected) connections to/from each j-node and n is the total number of nodes in the entire network.
Clustering Coefficient, which quantifies the existence of infrastructure within the local vicinity of nodes, given by the formula:
C(j) = 2yi / Kj(Kj -1)
in which yj is the number of links between neighbooring nodes of the j-node.
For finding Degree Centrality, I have tried:
# find connections by adding matrix row values
matrix_cerebellum['K'] = matrix_cerebellum.sum(axis=1)
# applying formula
matrix_cerebellum['centrality'] = matrix_cerebellum['K']/matrix_cerebellum.shape[0]-1
Generates:
... K centrality
9.0 -0.995156
6.0 -0.996771
7.0 -0.996771
11.0 -0.996233
11.0 -0.994080
According to the paper, I should be finding:
"For the cerebellum slices we measured 〈k〉 ∼ 1.9 − 3.7",
For the average numbers of connections per node.
Also I'm finding negative centralities.
Does anyone know how to apply any of these formulas based on the dataframe above?
This is not really a programming question, but I will try to answer it. The webpage with the data sources states that the adjacent matrix files for brain samples give distances between connected nodes expressed in pixels of the images used to reconstruct the networks. The paper then explains that to get the real adjacency matrix Mij (with 0 and 1 values only) the authors consider as connected nodes where the distance is at most 16 micrometers. I don't see the information on how many pixels in the image corresponds to one micrometer. This would be needed to compute the same matrix Mij that the authors used in their calculations.
Furthermore, the value〈k〉is not the degree centrality or the clustering coefficient (that depend on a node), but rather the average number of connections per node in the network, computed using the matrix Mij. The paper then compares the observed distributions of degree centralities and clustering coefficients in the brain and cosmic networks to the distribution one would see in a random network with the same number of nodes and the same value of〈k〉. The conclusion is that brain and cosmic networks are highly non-random.
Edits:
1. The conversion of 0.32 micrometers per pixel seems to be right. In the files with data on brain samples (both for cortex and cerebellum) the largest value is 50 pixels, which with this conversion corresponds to 16 micrometers. This suggests that the authors of the paper already thresholded the matrices, listing in them only distances not exceeding 16 micrometers. In view of this, to obtain the matrix Mij with 0 and 1 values only, one simply needs to replace all non-zero values with 1. An issue is that using the matrices obtained in this way one gets 〈k〉 = 9.22 for cerebellum and 〈k〉 = 7.13 for cortex, which is somewhat outside the ranges given in the paper. I don't know how to account for this discrepancy.
2. Negative centrality values are due to a mistake (missing parentheses) in the code. It should be:
matrix_cerebellum['centrality'] = matrix_cerebellum['K']/(matrix_cerebellum.shape[0] - 1)
3. Clustering coefficient and degree centrality of each node can be computed using tools provided by the networkx library:
from astropy.io import fits
import networkx as nx
# get the adjacency matrix for cortex
with fits.open('matrix_CORTEX_large.fits') as data:
M = data[0].data
M[M > 0] = 1
# create a graph object
G_cortex = nx.from_numpy_matrix(M)
# compute degree centrality of all nodes
centrality = nx.degree_centrality(G_cortex)
# compute clustering coefficient of all nodes
clustering = nx.clustering(G_cortex)

k-means returns nan values?

I recently came across a k-means tutorial that looks a bit different than what I remember the algorithm to be, but it should still do the same after all it's k-means. So, I went and gave it a try with some data, here's how the code looks:
# Assignment Stage:
def assignment(data, centroids):
for i in centroids.keys():
#sqrt((x1-x2)^2+(y1-y2)^2 + etc)
data['distance_from_{}'.format(i)]= (
np.sqrt((data['soloRatio']-centroids[i][0])**2
+(data['secStatus']-centroids[i][1])**2
+(data['shipsDestroyed']-centroids[i][2])**2
+(data['combatShipsLost']-centroids[i][3])**2
+(data['miningShipsLost']-centroids[i][4])**2
+(data['exploShipsLost']-centroids[i][5])**2
+(data['otherShipsLost']-centroids[i][6])**2
))
print(data['distance_from_{}'.format(i)])
centroid_distance_cols = ['distance_from_{}'.format(i) for i in centroids.keys()]
data['closest'] = data.loc[:, centroid_distance_cols].idxmin(axis=1)
data['closest'] = data['closest'].astype(str).str.replace('\D+', '')
return data
data = assignment(data, centroids)
and:
#Update stage:
import copy
old_centroids = copy.deepcopy(centroids)
def update(k):
for i in centroids.keys():
centroids[i][0]=np.mean(data[data['closest']==i]['soloRatio'])
centroids[i][1]=np.mean(data[data['closest']==i]['secStatus'])
centroids[i][2]=np.mean(data[data['closest']==i]['shipsDestroyed'])
centroids[i][3]=np.mean(data[data['closest']==i]['combatShipsLost'])
centroids[i][4]=np.mean(data[data['closest']==i]['miningShipsLost'])
centroids[i][5]=np.mean(data[data['closest']==i]['exploShipsLost'])
centroids[i][6]=np.mean(data[data['closest']==i]['otherShipsLost'])
return k
#TODO: add graphical representation?
while True:
closest_centroids = data['closest'].copy(deep=True)
centroids = update(centroids)
data = assignment(data,centroids)
if(closest_centroids.equals(data['closest'])):
break
When I run the initial assignment stage, it returns the distances, however when I run the update stage, all distance values become NaN, and I just dont know why or at which point exactly this happens... Maybe I made I mistake I can't spot?
Here's an excerpt of the data im working with:
Unnamed: 0 characterID combatShipsLost exploShipsLost miningShipsLost \
0 0 90000654.0 8.0 4.0 5.0
1 1 90001581.0 97.0 5.0 1.0
2 2 90001595.0 61.0 0.0 0.0
3 3 90002023.0 22.0 1.0 0.0
4 4 90002030.0 74.0 0.0 1.0
otherShipsLost secStatus shipsDestroyed soloRatio
0 0.0 5.003100 1.0 10.0
1 0.0 2.817807 6251.0 6.0
2 0.0 -2.015310 752.0 0.0
3 4.0 5.002769 43.0 5.0
4 1.0 3.090204 301.0 7.0

Getting NaN's instead of the correct values inside dataframe column

I created a dataframe of zeros using this syntax:
ltv = pd.DataFrame(data=np.zeros([actual_df.shape[0], 6]),
columns=['customer_id',
'actual_total',
'predicted_num_purchases',
'predicted_value',
'predicted_total',
'error'], dtype=np.float32)
It comes out perfectly as expected
customer_id | actual_total | predicted_num_purchases | predicted_value | predicted_total | error
0 0.0 0.0 0.0 0.0 0.0 0.0
1 0.0 0.0 0.0 0.0 0.0 0.0
2 0.0 0.0 0.0 0.0 0.0 0.0
When I run this syntax:
ltv['customer_id'] = actual_df['customer_id']
I get all NaNs in ltv['customer_id']. What is causing this and how can I prevent it from happening?
NB: I also checked actual_dfand there are no NaNs inside of it
You need same index values in both (and also same length of both DataFrames).
So first solution is create default RabgeIndex in actual_df, in ltv is not specify, so created by default:
actual_df = actual_df.reset_index(drop=True)
ltv['customer_id'] = actual_df['customer_id']
Or add parameter index to DataFrame constructor:
ltv = pd.DataFrame(data=np.zeros([actual_df.shape[0], 6]),
columns=['customer_id',
'actual_total',
'predicted_num_purchases',
'predicted_value',
'predicted_total',
'error'], dtype=np.float32,
index=actual_df.index)
ltv['customer_id'] = actual_df['customer_id']
Another option (more complicated than jezrael's great answer) is using pd.concat() followed by .drop():
ltv = pd.concat([ltv.drop(columns=['customer_id']),actual_df[['customer_id']]],axis=1,ignore_index=True)

smooth plotting all columns of a data-frame

I have a data frame of:
Index Date AA BB CC DD EE FF
0 2019-01-15 0.0 -1.0 0.0 0.0 0.0 2.0
1 2019-01-17 0.0 -1.0 -1.0 -1.0 0.0 2.0
2 2019-01-22 1.0 -1.0 1.0 -1.0 0.0 2.0
3 2019-01-24 0.0 0.0 0.0 0.0 0.0 2.0
4 2019-01-29 1.0 0.0 -1.0 0.0 -1.0 2.0
5 2019-01-31 0.0 -1.0 0.0 0.0 0.0 2.0
6 2019-02-05 1.0 1.0 1.0 0.0 1.0 2.0
7 2019-02-12 2.0 1.0 1.0 0.0 2.0 2.0
which I'm plotting with:
dfs = dfs.melt('Date', var_name = 'cols', value_name = 'vals')
ax = sns.lineplot(x = "Date", y = 'vals', hue = 'cols',
style = 'cols', markers = True, dashes = False, data = dfs)
ax.set_xticklabels(dfs['Date'].dt.strftime('%d-%m-%Y'))
plt.xticks(rotation = -90)
plt.tight_layout()
plt.show()
resulting:
which is ugly. I want to have the markers in the exact place as what is in the data-frame but the lines to be smoothed. I'm aware of scipy -> spline (e.g. here), however that seems to be too much hassle to convert all the columns. There is also Pandas -> resample -> interpolate (e.g. here) which is very close to what I want but I have to turn the Date column to index which I don't want to do...
I would appreciate if you could help me know what is the best Pythonic way to do this.
P.S. A complete version of my code can be seen here.
I think you need to write a custom plotting function that iterates over all
columns and plots interpolated data to specified axes instance. Look at the following code:
import pandas as pd
import numpy as np
# data = pd.read_clipboard()
# data.drop(['Index'], axis=1, inplace=True)
def add_smooth_plots(df, ax, timecolumn='Date', interpolation_method='cubic', colors='rgbky'):
from itertools import cycle
ind = pd.to_datetime(df.loc[:, timecolumn])
tick_labels =ind.dt.strftime("%Y-%m-%d")
color = cycle(colors)
for i, col in enumerate(df.columns):
if col != timecolumn:
c = next(color)
s = pd.Series(df.loc[:, col].values, index=ind)
intp = s.resample('0.5D').interpolate(method=interpolation_method)
true_ticks = intp.index.isin(ind)
vals = intp.values
intp = intp.reset_index()
ticks = intp.index[true_ticks]
ax.plot(np.arange(len(vals)), vals, label=col, color=c)
ax.set_xticks(ticks)
ax.set_xticklabels(tick_labels.values, rotation=45)
ax.legend(title='Columns')
return ax
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
add_smooth_plots(data, ax)
plt.show()

Categories