Data Science Asked on November 17, 2021
If I have a dataset in a csv that looks like the one shown below.
How do I convert this into a laplacian matrix using Python?
Use SciPy's Laplacian function:
import numpy as np
from scipy.sparse.csgraph import laplacian
g = np.array([[1, 0, 0, 0],
[0, 1, 0, 1],
[0, 0, 0, 1],
[0, 1, 1, 1]])
laplacian(g)
Answered by Brian Spiering on November 17, 2021
Well the Laplacian
matrix is achieved by:
$degree (v_i) $ for $space$ i=j
$-1$ for $space$ if $v_j$ and $v_i$ are not adjacent to each other
$0$ otherwise
First, you need to store your file to a 2d-array
Then you need to define another 2d-array matrix the same size of your first matrix. Then loop over the elements to fill the Laplacian
matrix
import pandas as pd
data = pd.read_csv('data.csv')
df = pd.Dataframe(data)
M = df.as_matrix()
L = np.zeros(df.shape[0], df.shape[1]) #shape[0] and shape[1] should be equal
Then for each element $A_{i,j}$ we calculate their corresponding value in L
for i in range(len(df.shape[0])):
for j in range(len(df.shape[0])): # or shape[1]
if M[i][j] == 0 and M[j][i]== 0:
L[i][j] = -1
if i == j:
L[i][j] = sum(M[i][:])
else:
L[i][j] = 0
I haven't tried the code so consider it much like a pseudo-code.
Answered by Fatemeh Asgarinejad on November 17, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP