【问题标题】:Using python and networkx to find the probability density function使用python和networkx求概率密度函数
【发布时间】:2018-09-05 00:06:02
【问题描述】:

我正在努力为我在网上找到的 Facebook 数据绘制幂律图。我正在使用 Networkx,我发现了如何绘制 Degree Histogram 和学位等级。我遇到的问题是我希望 y 轴是一个概率,所以我假设我需要总结每个 y 值并除以节点总数?谁能帮我做到这一点?一旦我得到了这个,我想画一个对数对数图,看看我是否能得到一条直线。如果有人可以提供帮助,我将不胜感激!这是我的代码:

import collections 
import networkx as nx
import matplotlib.pyplot as plt
from networkx.algorithms import community
import math
import pylab as plt

g = nx.read_edgelist("/Users/Michael/Desktop/anaconda3/facebook_combined.txt","r")
nx.info(g)

degree_sequence = sorted([d for n, d in g.degree()], reverse=True)
degreeCount = collections.Counter(degree_sequence)
deg, cnt = zip(*degreeCount.items())
fig, ax = plt.subplots()
plt.bar(deg, cnt, width=0.80, color='b')
plt.title("Degree Histogram for Facebook Data")
plt.ylabel("Count")
plt.xlabel("Degree")
ax.set_xticks([d + 0.4 for d in deg])
ax.set_xticklabels(deg)
plt.show()

plt.loglog(degree_sequence, 'b-', marker='o')
plt.title("Degree rank plot")
plt.ylabel("Degree")
plt.xlabel("Rank")
plt.show()

【问题讨论】:

    标签: python-3.x dataset histogram networkx power-law


    【解决方案1】:

    您似乎走在正确的轨道上,但一些简化可能会对您有所帮助。下面的代码只使用了 2 个库。

    如果不访问您的图表,我们可以使用一些图表生成器来代替。我在这里选择了 2 种质量不同的类型,并且特意选择了不同的大小,以便需要对直方图进行归一化。

    import networkx as nx
    import matplotlib.pyplot as plt
    
    g1 = nx.scale_free_graph(1000, ) 
    g2 = nx.watts_strogatz_graph(2000, 6, p=0.8) 
    
    # we don't need to sort the values since the histogram will handle it for us
    deg_g1 = nx.degree(g1).values()
    deg_g2 = nx.degree(g2).values()
    # there are smarter ways to choose bin locations, but since
    # degrees must be discrete, we can be lazy...
    max_degree = max(deg_g1 + deg_g2)
    
    # plot different styles to see both
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.hist(deg_g1, bins=xrange(0, max_degree), density=True, histtype='bar', rwidth=0.8)
    ax.hist(deg_g2, bins=xrange(0, max_degree), density=True, histtype='step', lw=3) 
    
    # setup the axes to be log/log scaled
    ax.set_yscale('log')
    ax.set_xscale('log')
    ax.set_xlabel('degree')
    ax.set_ylabel('relative density')
    ax.legend()
    
    plt.show()
    

    这会产生这样的输出图(g1、g2 都是随机的,因此不会相同):

    在这里我们可以看到g1 在度数分布中具有近似直线衰减 - 正如对数对数轴上的无标度分布所预期的那样。相反,g2 没有无标度度分布。

    更正式地说,您可以查看 Aaron Clauset 的工具箱:http://tuvalu.santafe.edu/~aaronc/powerlaws/,它实现了模型拟合和幂律分布的统计测试。

    【讨论】:

      猜你喜欢
      • 2019-04-19
      • 2012-11-21
      • 2016-06-07
      • 2019-07-19
      • 2017-09-20
      • 2015-05-08
      • 1970-01-01
      • 2012-06-06
      • 1970-01-01
      相关资源
      最近更新 更多