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

标签 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

最佳答案

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

关于python - Zipf 分布 : How do I measure Zipf Distribution using Python/Numpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43601074/

相关文章:

python - 在列表的排列中应用排名

python - 将 Lua 移植到 Python

python - Cython:对于类型化的内存 View ,我应该使用 np.float_t 而不是 double

python - 将 I2C 传感器 (DS1624) 读数转换为数字

c++ - C++ 的 NumPy 样式数组?

python - 通过 Python 中的索引删除数组的列

python - 有没有一种简单的方法可以对 pandas 数据框中的分布进行所有成对统计比较?

python-3.x - 使用 "maximum diversity"高效绘制组合

python - 在字典中存储 lambda

c++ - 如何将函数值更改为 C++ 中表( Gamma 分布)中的值?