Zipf分布:如何使用Python / Numpy测量Zipf分布

时间:2017-04-25 03:27:54

标签: python numpy statistics numpy-random zipf

我有一个大约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

1 个答案:

答案 0 :(得分:2)

如上所述,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()

样本直方图的图,以及概率密度函数 enter image description here