Skip to main content
 首页 » 编程设计

python之Zipf 分布 : How do I measure Zipf Distribution using Python/Numpy

2024年10月01日7qq号

我有一个大约 700 行的文件(比如说 corpus.txt),每行包含由 - 分隔的数字。例如:

86-55-267-99-121-72-336-89-211 
59-127-245-343-75-245-245 

首先我需要从文件中读取数据,找到每个数字的频率,测量这些数字的 Zipf 分布,然后绘制分布图。我已经完成了任务的前两部分。我一直在绘制 Zipf 分布。

我知道 numpy.random.zipf(a, size=None) 应该用于此。但是我发现使用它非常困难。任何指针或代码片段都会非常有帮助。

代码:

# Counts frequency as per given n 
def calculateFrequency(fileDir): 
  frequency = {} 
  for line in fileDir: 
    line = line.strip().split('-') 
    for i in line: 
      frequency.setdefault(i, 0) 
      frequency[i] += 1 
  return frequency 
 
fileDir = open("corpus.txt") 
frequency = calculateFrequency(fileDir) 
fileDir.close() 
print(frequency) 
 
## TODO: Measure and draw zipf distribution 

请您参考如下方法:

如所述,numpy.random.zipf(a, size=None) 将生成从 zipf 分布中抽取的样本图,指定参数为 > 1 .

但是,由于您的问题是难以使用 numpy.random.zipf 方法,这里是一个天真的尝试,如 scipy zipf documentation 中所讨论的那样网站。

下面是一个模拟的 corpus.txt,每行有 10 行随机数据。但是,与其他行相比,每行可能有重复项以模拟重复。

16-45-3-21-16-34-30-45-5-28 
11-40-22-10-40-48-22-23-22-6 
40-5-33-31-46-42-47-5-27-14 
5-38-12-22-19-1-11-35-40-24 
20-11-24-10-9-24-20-50-21-4 
1-25-22-13-32-14-1-21-19-2 
25-36-18-4-28-13-29-14-13-13 
37-6-36-50-21-17-3-32-47-28 
31-20-8-1-13-24-24-16-33-47 
26-17-39-16-2-6-15-6-40-46 

工作代码

import csv 
from operator import itemgetter 
import matplotlib.pyplot as plt 
from scipy import special 
import numpy as np 
 
#Read '-' seperated corpus data and get its frequency in a dict 
frequency = {} 
with open('corpus.txt', 'rb') as csvfile: 
    reader = csv.reader(csvfile, delimiter='-', quotechar='|') 
    for line in reader: 
        for word in line:             
            count = frequency.get(word,0) 
            frequency[word] = count + 1 
 
#define zipf distribution parameter 
a = 2.  
 
#get list of values from frequency and convert to numpy array 
s = frequency.values() 
s = np.array(s) 
 
# Display the histogram of the samples, along with the probability density function: 
count, bins, ignored = plt.hist(s, 50, normed=True) 
x = np.arange(1., 50.) 
y = x**(-a) / special.zetac(a) 
plt.plot(x, y/max(y), linewidth=2, color='r') 
plt.show() 

样本直方图以及概率密度函数图