3

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

1 回答 1

3

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

但是,由于您的问题是使用方法有困难,因此这是scipy zipf 文档站点numpy.random.zipf上讨论的幼稚尝试。

下面是一个模拟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()

样本的直方图,以及概率密度函数 在此处输入图像描述

于 2017-04-28T18:39:38.813 回答