-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDistance_feature.py
More file actions
99 lines (73 loc) · 2.13 KB
/
Copy pathDistance_feature.py
File metadata and controls
99 lines (73 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# -*- coding: utf-8 -*-
"""Distance_Feature.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/17GYNRR7_QUuhY9EUwxQGpX2LnsGKcIT6
"""
from collections import defaultdict
from collections import deque
import csv
import pandas as pd
import json
import random
import math
data = pd.read_excel('socialnetwrokdataset.xlsx')
data = data.drop(["Unnamed: 0"], axis = 1)
early_adopters = list(set(data['user_id']))
len(early_adopters)
# Opening JSON file
g = open('/content/drive/My Drive/followers/merged_file.json',)
# returns JSON object as
# a dictionary
pair_users = json.load(g)
len(pair_users)
graph = {}
for k, v in pair_users:
graph.setdefault(v, [])
graph.setdefault(k, []).append(v)
graph
with open('grap00h.json','w') as f:
json.dump(graph, f)
len(graph.keys())
#to try the code
#graph = {'A': ['B', 'C', 'E'],
#'B': ['A','D', 'E'],
#'C': ['A', 'F', 'G'],
#'D': ['B'],
#'E': ['A', 'B','D'],
#'F': ['C'],
#'G': ['C']}
class bfs_shortest_path:
def __init__(self, graph):
self.graph = graph
def check_distance(self, start, end):
queue = deque([(start, 0)])
seen = set()
while queue:
node, distance = queue.popleft()
if node in seen:
continue
seen.add(node)
if node == end:
return distance
for adjacent in self.graph.get(node, []):
queue.append((adjacent, distance + 1))
bfs = bfs_shortest_path(graph)
#bfs_shortest_path.check_distance('A', 'B') # to try
shortest_path = []
for i in range(len(early_adopters)-1):
try:
shortest_path.append(bfs.check_distance(early_adopters[i], early_adopters[i+1]))
except:
continue
shortest_path
#avarage step distance
avg = sum(shortest_path)/(len(early_adopters)-1)
#CV of step distance
std = math.sqrt((sum(shortest_path)- avg**2)/(len(nodes)-2))
cv = std/avg
# Diameter feature
diameter = max(shortest_path)
print(f'The avarage of step distance: {avg}')
print(f'The CV of step distance: {cv}')
print(f'Diameter: {diameter}')