1 year ago
#329091

8-Bit Borges
Create graph from euclidean distances using KNN
import numpy as np
import pandas as pd
import networkx as nx
from scipy.spatial.distance import cdist
from sklearn.neighbors import NearestNeighbors
Given the following array:
A = np.array([[1.25,1.1,0.8,1.23,2.,1.2],
[1.44,0.9,0.8,1.01,3.,1.2],
[0.3,2.8,2.8,1.,1.,1.3]])
I build a dataframe
of 5 objects with 3 features each, like so:
# creating a list of index names
index_values = ['first', 'second', 'third',
'fourth', 'fifth','sixth']
columns = ['feat_1', 'feat_2', 'feat_3']
# creating the dataframe
df = pd.DataFrame(data = array,
index = index_values,
columns = columns)
# displaying the dataframe
print(df)
feat_1 feat_2 feat_3
first 1.25 1.44 0.3
second 1.10 0.90 2.8
third 0.80 0.80 2.8
fourth 1.23 1.01 1.0
fifth 2.00 3.00 1.0
sixth 1.20 1.20 1.3
Then I calculate the euclidean distances between all objects:
from scipy.spatial.distance import cdist
euclidean = cdist(df, df, 'euclid')
array([[0. , 2.56204996, 2.61956103, 0.82176639, 1.86711007,
1.02961158],
[2.56204996, 0. , 0.31622777, 1.80803761, 2.90860791,
1.53297097],
[2.61956103, 0.31622777, 0. , 1.86252517, 3.08544972,
1.60312195],
[0.82176639, 1.80803761, 1.86252517, 0. , 2.133776 ,
0.35637059],
[1.86711007, 2.90860791, 3.08544972, 2.133776 , 0. ,
1.99248588],
[1.02961158, 1.53297097, 1.60312195, 0.35637059, 1.99248588,
0. ]])
Now I need to transform distances into similarity, with 1/distances, I guess, and finally
use KNN
to build a graph with 5 nodes, considering k=3
, in order to find the degree of all nodes.
How do I do this last part?
networkx
knn
euclidean-distance
0 Answers
Your Answer