簡體   English   中英

使用python和networkx查找概率密度函數

[英]Using python and networkx to find the probability density function

我正在努力為在網上找到的Facebook數據繪制冪律圖。 我正在使用Networkx,並且發現了如何繪制度直方圖和度等級。 我遇到的問題是我希望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()

您似乎處在正確的軌道上,但是進行一些簡化可能會為您提供幫助。 下面的代碼僅使用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/,該工具箱實現了冪律分布的模型擬合和統計測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM