社交网络度的计算

  • 计算edge list的度

数据集:大概长这样,需要数据集的可以给我留言

2	1
3	1
3	2
4	1
4	2
4	3
5	1
6	1
7	1
7	5
7	6
```python
filename = r"XXX.txt" #自己的数据值的地址
mydict = {}
with open(filename) as f:
    for line in f.readlines(): #一行一行去读取list
        temp_list = line.split() 
        start = temp_list[0]
        end = temp_list[1] #list的中的头尾分别为start和end

        if( start not in mydict ): mydict[start]=0
        if( end not in mydict ): mydict[end] = 0
        mydict[start] += 1 
        mydict[end] += 1 #建立一个mydict的字典,字典的键就是list中的值,字典的值就是list中那个值出现的个数,读取每一个list的时候,碰到那个数字他对应的字典的值就加1,这样就把degree算出来了

        
print(mydict)
  • 怎么将edge list 转换为adjacency list
    代码如下:
import numpy as np
filename = r"XXX.txt" #自己的数据集的路径

n = 34  #数据集里面有34个元素,也就是node number,如果不知道可以通过python中的集合获取到
mydict = {}

with open(filename) as f:    
    for line in f.readlines():
        temp_list = line.split()
        start = temp_list[0]
        end = temp_list[1]

        # store the edge list of start node 
        if( start not in mydict ): mydict[start] = []
        start_list = mydict[start]
        start_list.append(end)
        mydict[start] = start_list

        # store the edge list of end node 
        if( end not in mydict ): mydict[end] = []
        end_list = mydict[end]
        end_list.append(start)
        mydict[end] = end_list
        
print(mydict)

代码的运行结果就是将社交网络度的计算_第1张图片
转化为:
在这里插入图片描述

  • 怎么将edge list 转换为adjacency matrix
import numpy as np
filename = r"XXX.txt" #你的数据集的位置

n = 34  #数据集里面node number是34,如果不知道可以通过python中的集合获取
adjacencyMatrix = np.zeros((n, n))

with open(filename) as f:    
    for line in f.readlines():
        temp_list = line.split()
        adjacencyMatrix[int(temp_list[0])-1][int(temp_list[1])-1]=1  #python中的索引是从0开始的,但是我们的数据集里面最小的元素就是1
        adjacencyMatrix[int(temp_list[1])-1][int(temp_list[0])-1]=1
        
print(adjacencyMatrix)

你可能感兴趣的:(社交网络)